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.

209 KB
Raw Blame
import copy
import ipaddress
import json
import logging
import math
import os
import re
import shutil
import tempfile
import threading
from contextlib import contextmanager
from dataclasses import dataclass, field, fields, replace
from datetime import datetime
from pathlib import Path
from typing import (
    Any,
    Callable,
    ClassVar,
    Iterator,
    List,
    Literal,
    Mapping,
    Optional,
    TypeVar,
)
from urllib.parse import parse_qsl, urlsplit, urlunsplit

from config import paths
from config.atomic_io import write_atomic
from config.platform_registry import (
    WORKBENCH_PLATFORM_ID,
    get_platform_descriptor,
    is_workbench_platform,
    platform_catalog_payload,
    platform_descriptors,
    supported_platform_ids,
    supported_platform_set,
)
from modules.agents.catalog import AGENT_BACKENDS, NATIVE_CLI_BACKENDS, AgentBackend, DEFAULT_AGENT_BACKEND
from modules.im.base import BaseIMConfig
from vibe.i18n import normalize_language
from vibe.trace_retention_policy import validate_retention_days

logger = logging.getLogger(__name__)

CONFIG_LOCK = threading.RLock()

#: How long a config write waits for a peer process before giving up. Config
#: writes are small and bounded, so a wait this long says the holder is stuck
#: rather than busy, and a settings save that fails is better than one that
#: never returns.
CONFIG_FILE_LOCK_TIMEOUT_SECONDS = 30.0


def _path_file_lock(lock_path: Path, *, timeout_seconds: float | None):
    """The shared cross-process lock for one path.

    Nesting is safe, and that is why this file no longer keeps a lock of its
    own: ``MigrationFileLock`` is re-entrant per path and thread, which both
    transactions here used to hand-roll as a thread-local depth counter beside
    a private descriptor and a private copy of the platform lock calls.
    """

    # Import lazily because storage's package initializer imports V2Config.
    from storage.lock import MigrationFileLock

    return MigrationFileLock(lock_path, timeout_seconds=timeout_seconds)


@contextmanager
def config_write_transaction(config_path: Optional[Path] = None) -> Iterator["V2Config"]:
    """Cross-process read-modify-write transaction for ``config.json`` (#1458).

    The file lock serializes the
    WHOLE load→mutate→save cycle, so the mutator always sees a snapshot
    loaded inside the transaction and cannot revert a concurrent writer's
    fields (the stale-snapshot race ``CONFIG_LOCK`` cannot fix because it
    is process-local while the UI API and controller are separate
    processes). Lock order and re-entrancy match the config lock:
    ``CONFIG_LOCK`` first, then the file lock; both are re-entrant, so a
    nested transaction on the same config takes the same pair.

    Yields a freshly loaded ``V2Config``; mutate it in place and it is
    saved on clean context exit. Mutator exceptions abort with no write.
    """

    from config import paths as _paths

    path = config_path or _paths.get_config_path()
    with config_file_lock(path):
        try:
            config = V2Config.load(path)
        except FileNotFoundError:
            config = V2Config.default()
        yield config
        config.save(path)


def update_config_fields(
    mutator: Callable[["V2Config"], None],
    *,
    config_path: Optional[Path] = None,
) -> "V2Config":
    """Apply ``mutator`` to a fresh config under the cross-process lock.

    The preferred shape for narrow field writers (relay marker, language,
    default provider, secrets rotation): decisions are made before the
    call, the mutator only assigns fields, and the transaction guarantees
    neither snapshot staleness nor lost updates. Direct
    ``V2Config.load`` → mutate → ``save()`` pairs outside a transaction
    are a defect for cross-process state (see docs/plans/
    config-cross-process-write-serialization.md).
    """

    with config_write_transaction(config_path) as config:
        mutator(config)
    return config


_MODEL_HUB_CREDENTIAL_PATTERNS = (
    re.compile(r"(?i)\b(?:sk|rk|pk|sess|token)[-_][a-z0-9_-]{8,}\b"),
    re.compile(
        r"(?i)\b(?:authorization|api[_ -]?key|access[_ -]?token)\s*[:=]\s*"
        r"(?:sk[-_][a-z0-9_-]{8,}|[a-z0-9._~+/=-]{16,})"
    ),
    re.compile(r"(?i)\bbearer\s+[a-z0-9._~+/=-]{8,}"),
)


def _contains_model_hub_credential_material(value: object) -> bool:
    rendered = json.dumps(value, ensure_ascii=False, sort_keys=True)
    return any(pattern.search(rendered) for pattern in _MODEL_HUB_CREDENTIAL_PATTERNS)

DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS = 600
DEFAULT_SHOW_PAGE_API_TIMEOUT_SECONDS = 90.0

# Harness run staleness sweep (``docs/plans/agent-run-zombie-settlement.md`` §4.4).
# How often the sweep may run at all — it rides the scheduler's existing 2 s tick, so
# this only rate-limits the candidate query.
DEFAULT_HARNESS_RUN_SWEEP_INTERVAL_SECONDS = 60
# How long a ``running`` agent run may have no live owner before it is declared
# orphaned. Must comfortably exceed the gap between claiming a row and registering the
# executing turn, so a legitimately-starting run is never swept.
DEFAULT_HARNESS_RUN_ORPHAN_GRACE_SECONDS = 120
# How long a ``queued`` run may sit while its transport is unavailable. Long enough
# that a brief IM reconnect just delivers late instead of failing the run.
DEFAULT_HARNESS_RUN_QUEUED_TTL_SECONDS = 1800
# How long a workbench queue hold may go unrefreshed. Deliberately the longest of the
# three: a session actively recovering its queue keeps touching the row.
DEFAULT_HARNESS_RUN_HOLD_TTL_SECONDS = 3600

# Repair stale Codex adapter-local active flags only after durable ownership
# allows reclamation. Silence never overrides an owned Turn or Activity.
# The repair threshold is max(idle_timeout * multiplier, floor); a nonpositive
# multiplier disables stale-flag repair.
DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER = 3
DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS = 1800

# Claude uses the same ownership-first policy for its receiver's active flag.
DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER = 3
DEFAULT_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS = 1800
DEFAULT_OPENCODE_ERROR_RETRY_LIMIT = 1
# OpenCode >= 1.18.x bounds its own provider retries (RETRY_MAX_RETRIES = 5) and
# writes the exhausted error onto the assistant message, which the poll loop's
# error-driven settlement already turns into a failed terminal result. The
# historical wall-clock cap from #1197 therefore default-offs here: a positive
# value is an explicit opt-in for operators who still want a hard bound.
DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS = 0
# The shipped default before the opt-in change. A settings save materializes the
# whole ``agents.opencode`` section, so a persisted value equal to this constant
# is the old default's echo rather than an operator's choice; load-time
# migration neutralizes exactly that value. Any other value is an explicit
# choice and survives the migration.
LEGACY_DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS = 90 * 60
DEFAULT_CHAT_MESSAGE_FONT_SIZE_PX = 14
MIN_CHAT_MESSAGE_FONT_SIZE_PX = 12
MAX_CHAT_MESSAGE_FONT_SIZE_PX = 20
DEFAULT_AGENT_PROGRESS_STYLE = "off"
MODEL_HUB_ENABLED_ENV = "VIBE_MODEL_HUB_ENABLED"
MODEL_HUB_BACKENDS = AGENT_BACKENDS
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:
    """Return the canonical persisted vendor id used by matching-v1."""

    if not isinstance(value, str):
        raise ValueError("Config 'model_hub.sources.vendor' must be a non-empty string")
    vendor = value.strip().lower()
    if (
        not vendor
        or re.fullmatch(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", vendor) is None
        or _contains_model_hub_credential_material(vendor)
    ):
        raise ValueError("Config 'model_hub.sources.vendor' is invalid")
    return vendor


def validate_model_hub_protocol_vendor(vendor: str, protocol: str) -> None:
    """Validate protocol/vendor combinations that are intrinsic to persisted shapes."""
    if protocol == "google" and vendor not in {"custom", "gemini"}:
        raise ValueError("Google Sources require the custom or gemini vendor")


# Google's OpenAI-compatible endpoint, the Gemini preset's endpoint before Gemini API keys spoke Gemini natively,
# and its native root (``vibe/data/api_key_vendors.json``; ``docs/plans/vibey-gemini-native.md`` §3).
_GEMINI_OPENAI_COMPATIBLE_ENDPOINT = ("https", "generativelanguage.googleapis.com", "/v1beta/openai")
GEMINI_NATIVE_BASE_URL = "https://generativelanguage.googleapis.com"


def on_gemini_openai_compatible_endpoint(vendor: object, protocol: object, base_url: object) -> bool:
    """A Gemini API key bound to Google's official OpenAI-compatible endpoint, named or by default (a relay is not).

    Both the saved Source (``_migrate_gemini_native_sources``) and its engine credential binding
    (``EngineStateStore.sync_sources``) move from it to the native root by this one test.
    """

    if vendor != "gemini" or protocol != "openai_chat":
        return False
    if base_url is None:
        # The vendor's official endpoint, which was the OpenAI-compatible one.
        return True
    if not isinstance(base_url, str):
        return False
    try:
        parsed = urlsplit(base_url.strip())
        port = parsed.port
    except ValueError:
        return False
    endpoint = (parsed.scheme.lower(), (parsed.hostname or "").lower(), parsed.path.rstrip("/"))
    return endpoint == _GEMINI_OPENAI_COMPATIBLE_ENDPOINT and not parsed.query and port in (None, 443)


def _migrate_gemini_native_sources(payload: dict) -> dict:
    """Move every Gemini API key saved on Google's OpenAI-compatible endpoint to the native protocol it now speaks.

    Only the protocol and the endpoint change. The Source keeps its id, credential, models and routes: a Gemini Source
    names its models as Google lists them on either surface (``models/<id>``). Idempotent: a moved Source no longer
    matches.
    """

    def moves(source: object) -> bool:
        return (
            isinstance(source, dict) and source.get("kind") == "api_key"
            and on_gemini_openai_compatible_endpoint(source.get("vendor"), source.get("protocol"), source.get("base_url"))
        )

    hub = payload.get("model_hub")
    sources = hub.get("sources") if isinstance(hub, dict) else None
    if not isinstance(sources, list) or not any(moves(source) for source in sources):
        return payload
    migrated_hub = dict(hub)
    migrated_hub["sources"] = [
        {**source, "protocol": "google", "base_url": GEMINI_NATIVE_BASE_URL} if moves(source) else source
        for source in sources
    ]
    return {**payload, "model_hub": migrated_hub}


def model_hub_fixed_menu_ids(backend: str) -> tuple[str, ...]:
    """Return the bundled fixed-menu ids used by persisted Hub routes."""

    if backend not in {"claude", "codex"}:
        return ()
    from vibe.backend_model_catalog import backend_model_entries, load_bundled_catalog

    return tuple(
        entry["id"]
        for entry in backend_model_entries(backend, load_bundled_catalog())
    )


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 so the resulting override
    retains its exact historical target independently of automatic routing.
    """

    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]]:
    hops: 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 model_id == target_model_id:
                hops.append({"source_id": source_id, "model_id": model_id})
    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 in ("claude", "codex"):
        agent = agents.get(backend)
        if agent is None:
            continue
        if not isinstance(agent, dict):
            return payload, False, ()
        if set(agent) - {
            "backend",
            "mode",
            "menu_kind",
            "sources",
            "mappings",
            "routes",
            "menu",
            "models",
            "removed_model_ids",
        }:
            return payload, False, ()
        if agent.get("backend") != backend or agent.get("menu_kind") != "fixed":
            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, ()
        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(agents.get(backend), dict)
            and "mappings" in agents[backend]
            for backend in ("claude", "codex")
        )
        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] = copy.deepcopy(agents)
    for backend in ("claude", "codex"):
        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(model_hub_fixed_menu_ids(backend))

        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
            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", "models"}
        }
        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"] = "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_legacy_opencode_catalog(payload: dict) -> tuple[dict, bool, tuple[str, ...]]:
    """Fill released catalog omissions using only persisted routing evidence.

    This is a disk-load migration, not a relaxed write parser. A selected model
    with no unambiguous, representable native protocol must keep the original
    file and the ordinary recovery write guard instead of losing its selection.
    """
    hub = payload.get("model_hub")
    if not isinstance(hub, dict) or not isinstance(hub.get("agents"), dict):
        return payload, False, ()
    agent = hub["agents"].get("opencode")
    if not isinstance(agent, dict):
        return payload, False, ()
    rows = agent.get("models")
    missing_catalog = "models" not in agent
    if not missing_catalog and (
        not isinstance(rows, list)
        or not any(isinstance(row, dict) and "native_protocol" not in row for row in rows)
    ):
        return payload, False, ()

    try:
        menu = ModelHubMenuConfig.from_payload(agent.get("menu"))
        if missing_catalog:
            rows = [{"id": model_id} for model_id in menu.checked]
        models = [ModelHubBackendModelConfig.from_payload(row) for row in rows]
        source_order = ModelHubAgentSourcesConfig.from_payload(agent.get("sources", {"order": []})).order
        raw_sources = hub.get("sources", [])
        raw_routes = agent.get("routes", {})
        if not isinstance(raw_sources, list) or not isinstance(raw_routes, dict):
            return payload, False, ()
        sources = {
            source.id: source
            for source in (
                ModelHubSourceConfig.from_payload(raw, repairing=True)
                for raw in raw_sources
            )
        }
        routes = {
            model_id: ModelHubRouteConfig.from_payload(route, repairing=True)
            for model_id, route in raw_routes.items()
        }
    except (TypeError, ValueError):
        # Let the strict parser report malformed/retired fields as before.
        return payload, False, ()

    migrated_rows = copy.deepcopy(rows)
    for row, model in zip(migrated_rows, models):
        if "native_protocol" in row:
            continue
        route = routes.get(model.id)
        if route and route.hops:
            supplier_ids = [hop.source_id for hop in route.hops]
        else:
            supplier_ids = [
                source_id for source_id in source_order
                if source_id in sources
                and any(item.id == model.id for item in sources[source_id].models)
            ]
        protocols = {
            sources[source_id].protocol if source_id in sources else None
            for source_id in supplier_ids
        }
        if len(protocols) != 1 or not protocols <= {"anthropic", "openai_responses"}:
            return payload, False, (
                "Model Hub legacy OpenCode selection has no unambiguous supported native_protocol; "
                "repair model_hub.agents.opencode.models with an explicit native_protocol "
                "for each selected model. The original config is preserved.",
            )
        row["native_protocol"] = next(iter(protocols))

    migrated = copy.deepcopy(payload)
    migrated["model_hub"]["agents"]["opencode"]["models"] = migrated_rows
    return migrated, True, ()


def _migrate_opencode_active_turn_timeout_on_load(payload: dict) -> dict:
    """Neutralize the legacy wall-clock default echo on reload, once.

    Configs saved while the cap shipped carry
    ``agents.opencode.active_turn_timeout_seconds: 5400`` because a settings
    save materializes the whole section. That value names the old default, not
    an operator's choice, so exactly that value rewrites to the disabled
    default. ``legacy_turn_timeout_neutralized`` is the provenance marker: a
    config written under the opt-in semantics carries it, so a deliberate
    5400-second choice saved afterwards survives every later load. Idempotent:
    once rewritten (or never eligible) the pattern never matches again.
    """

    agents = payload.get("agents")
    if not isinstance(agents, dict):
        return payload
    opencode = agents.get("opencode")
    if not isinstance(opencode, dict):
        return payload
    if "legacy_turn_timeout_neutralized" in opencode:
        return payload
    if (
        opencode.get("active_turn_timeout_seconds")
        != LEGACY_DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS
    ):
        return payload
    migrated = dict(payload)
    migrated_agents = dict(agents)
    migrated_opencode = dict(opencode)
    migrated_opencode["active_turn_timeout_seconds"] = (
        DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS
    )
    migrated_opencode["legacy_turn_timeout_neutralized"] = True
    migrated_agents["opencode"] = migrated_opencode
    migrated["agents"] = migrated_agents
    return migrated


def _migrate_config_payload_on_load(payload: dict) -> tuple[dict, bool, tuple[str, ...]]:
    migrated, changed, warnings = _migrate_legacy_model_hub_payload(payload)
    migrated, catalog_changed, catalog_warnings = _migrate_legacy_opencode_catalog(migrated)
    migrated = _migrate_gemini_native_sources(migrated)
    model_hub_changed = changed or catalog_changed or migrated.get("model_hub") != payload.get("model_hub")
    migrated = _migrate_opencode_active_turn_timeout_on_load(migrated)
    return migrated, model_hub_changed, (*warnings, *catalog_warnings)


# The spellings a hand-edited config may use for a boolean, both sides in one
# place. ``""`` reads as off because ``test_show_agent_activity_defaults_off_and
# _round_trips`` states it; anything absent from here names no side at all.
_BOOL_SPELLINGS = {
    "1": True,
    "true": True,
    "yes": True,
    "on": True,
    "0": False,
    "false": False,
    "no": False,
    "off": False,
    "": False,
}


def _named_bool(path: str, value: object) -> bool:
    """The side a switch's value names, or a refusal.

    ``true``/``1``/``"yes"``/``"off"`` all name a side the caller meant, and
    ``_BOOL_SPELLINGS`` is the whole vocabulary in one place rather than a
    truthy list plus an implicit else. A value outside it names no side at all
    — ``"garbage"``, ``5``, ``[]`` — and is refused rather than read as false,
    which on a write path would answer 200 having stored the side the caller
    never asked for.
    """

    if isinstance(value, bool):
        return value
    if isinstance(value, str):
        spelled = _BOOL_SPELLINGS.get(value.strip().lower())
        if spelled is not None:
            return spelled
    elif isinstance(value, int) and value in (0, 1):
        return bool(value)
    raise ValueError(f"Config '{path}' must be a boolean")


def _named_value(path: str, declared: object, value: object) -> object:
    """The value a field's declared kind names, or a refusal.

    One vocabulary for every field this reaches, because the alternative is
    what the review found twice: each field open-coding its own ``int(...)`` /
    ``str(...)`` / truthy test, and each one deciding on its own whether a
    value it cannot read is an error or something to repair in place. Repair
    belongs to ``V2Config.load``, behind a backup and a warning; this states
    only what a value must name to be readable at all.

    A switch reads the spellings above. A number reads any spelling that names
    one, so a hand-edited ``"14"`` still means 14, and otherwise reads only a
    number it can store unchanged: a ``bool`` is refused because Python makes it
    an ``int`` and ``int(True)`` is a legal ``1``, an infinity and a NaN are
    refused because neither names a setting any field here can hold, and a
    fractional value posted to an integer field is refused because ``int(14.9)``
    is ``14`` — every one of them otherwise answers 200 having stored a setting
    the caller never sent. A string reads only a string: no
    number names a URL or a credential, and silently emptying one logs the
    operator out or unpairs the instance. Kinds outside this vocabulary —
    containers, nested sections — are left to the code that already
    understands them.
    """

    if isinstance(declared, str):
        text = declared
    elif isinstance(declared, type):
        text = declared.__name__
    else:
        # ``Optional[int]`` and friends are not classes, and their ``__name__``
        # is the bare ``"Optional"``, which would drop the kind being wrapped.
        text = str(declared)
    optional = re.fullmatch(r"(?:typing\.)?Optional\[(?:typing\.)?(.+)\]", text)
    if optional:
        if value is None:
            return None
        text = optional.group(1)
    if text == "bool":
        return _named_bool(path, value)
    if text in ("int", "float"):
        if isinstance(value, bool):
            raise ValueError(f"Config '{path}' must be a number")
        try:
            number = int(value) if text == "int" else float(value)
        except (TypeError, ValueError, OverflowError) as exc:
            # ``OverflowError`` is how Python spells "this float names no
            # integer": ``int(float("inf"))`` raises it rather than
            # ``ValueError``, and JSON turns both a hand-edited ``1e309`` and
            # the ``Infinity`` an older release serialized back into that
            # float. Left uncaught it escapes recovery on the disk path and
            # answers 500 on the write path, so it is spelled here as what it
            # is — a value naming no number — instead of being caught wider.
            raise ValueError(f"Config '{path}' must be a number") from exc
        if isinstance(number, float) and not math.isfinite(number):
            # An infinity or a NaN survives ``float(...)`` and then behaves as
            # a setting: an infinite ASR timeout never expires, and a NaN loses
            # every range comparison so it clamps to whichever bound is written
            # first. Refused for the same reason as the rest — it names no
            # setting — rather than clamped, which would answer 200 having
            # stored a bound the caller never asked for. Only floats are
            # checked: an ``int`` is always finite, and asking ``math`` about a
            # large one would raise the overflow just caught above.
            raise ValueError(f"Config '{path}' must be a number")
        if isinstance(value, (int, float)) and number != value:
            # The conversion succeeded and changed the number. ``int(14.9)`` is
            # ``14``, so a posted font size of 14.9 answered 200 having stored a
            # size nobody asked for, and ``float`` of an integer past 2**53 lands
            # on its neighbour the same way. Both are the defect this whole
            # vocabulary exists to refuse — a value coerced into a legal setting
            # instead of refused — so the rule is stated as what it is: a number
            # this reads is the number it was given. Only a numeric input is
            # held to it. A string is a spelling, not a number, and reading
            # ``"14"`` as 14 is the normalization this deliberately keeps; a
            # fractional spelling has no route here anyway, because ``int`` of
            # ``"14.9"`` already raises above.
            raise ValueError(f"Config '{path}' must be a number")
        return number
    if text == "str":
        if not isinstance(value, str):
            raise ValueError(f"Config '{path}' must be a string")
    return value


def _refuse_values_naming_nothing(section: str, instance: object) -> None:
    """Hold every field of ``instance`` to the kind it declares.

    Stated over the declared fields rather than over the ones some reviewer
    reached, so a field added to the dataclass is held to its own declaration
    without editing this call site — which is the difference between closing
    this class and paying for it one review round per field.

    Raised one field at a time, in the ``Config '<section>.<field>'`` shape
    every other message on this path uses, because that is what lets a disk
    load recover the unreadable field alone instead of discarding the section.
    A second unreadable field simply raises on the next pass of the recovery
    loop.
    """

    for info in fields(instance):
        setattr(
            instance,
            info.name,
            _named_value(f"{section}.{info.name}", info.type, getattr(instance, info.name)),
        )


# Sections whose fields are independent of one another, so a single unreadable
# field is recovered on its own instead of discarding its siblings — and whose
# switches recover to off rather than to the fresh-install default. See
# ``_reset_recoverable_config_section``.
_FIELD_SCOPED_RECOVERY_SECTIONS = ("ui", "audio_asr")

# Retention is optional and destructive: a malformed field must disable only
# that policy while preserving the rest of the runtime settings (cwd, logging,
# resource governance, and Harness timeouts).
_RUNTIME_RETENTION_FIELDS = frozenset(
    {
        "agent_events_trace_retention_enabled",
        "agent_events_trace_retention_days",
    }
)

# A backend's unattended-upgrade switch recovers alone and off, keeping the
# backend's CLI path, credentials, and enablement.
_BACKEND_AUTO_UPDATE_FIELD = "auto_update"

# The switch that decides whether an optional feature runs at all. Named once
# because recovery has to tell it apart from every other switch in a section:
# the rest describe how a feature behaves, this one decides whether it happens.
_FEATURE_SWITCH_FIELD = "enabled"


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",
        "remote_access",
        "audio_asr",
        "runtime",
        "agents",
        "platforms",
        "update",
        "ui",
    ):
        if section in lowered:
            return section
    return None


def _recovery_field_for_error(section: Optional[str], error: BaseException) -> Optional[str]:
    """The single field an error names, for the field-scoped sections only.

    Restricted to those sections so every other section keeps recovering — and
    de-duplicating — as a whole, which is what stops the recovery loop.
    """

    if section == "runtime":
        match = re.search(r"Config '([^']+)'", str(error))
        if not match:
            return None
        path = match.group(1)
        prefix = "runtime."
        if not path.startswith(prefix):
            return None
        field_name = path[len(prefix) :].split(".", 1)[0]
        return field_name if field_name in _RUNTIME_RETENTION_FIELDS or field_name == "skill_observability_enabled" else None
    if section is not None and section.startswith("agents."):
        match = re.search(r"Config '([^']+)'", str(error))
        auto_update = f"{section}.{_BACKEND_AUTO_UPDATE_FIELD}"
        return _BACKEND_AUTO_UPDATE_FIELD if match and match.group(1) == auto_update else None
    if section not in _FIELD_SCOPED_RECOVERY_SECTIONS:
        return None
    match = re.search(r"Config '([^']+)'", str(error))
    if not match:
        return None
    path = match.group(1).split(".", 1)
    if len(path) != 2 or path[0] != section:
        return None
    return path[1]


def _recover_switch_section_field(
    payload: dict, section: str, field_name: Optional[str]
) -> bool:
    """Keep what the file still says, and leave a recovered feature switched off.

    Two questions, answered separately, because answering both the same way is
    what produced this function's two review rounds.

    *How much of what the operator wrote is discarded?* As little as possible.
    Replacing the whole section answers an unreadable font size by hiding the
    tool-call rows and an unreadable model name by forgetting the endpoint, so
    the unreadable field is recovered alone: a field declared ``bool`` resolves
    to ``False`` because a value naming no side is no evidence the feature was
    on, and any other field is dropped so its declared default applies.

    *Does an optional feature still run afterwards?* No. ``AGENTS.md`` states it
    — "a broken optional-feature section disables that feature and warns" — and
    the two directions are not the symmetric pair the previous round argued they
    were. Leaving ``audio_asr.enabled`` on runs transcription under a
    configuration nobody wrote, shipping user audio off-machine against
    substituted settings, and that cannot be taken back. Leaving it off costs a
    warning the operator reads before turning it back on. Only one of those is
    reversible, so any repair here clears the section's ``enabled`` switch.

    Both answers are stated over the section's declared fields rather than over
    the sections that exist today: a section with no ``enabled`` is presentation
    and keeps its siblings untouched, and one that declares it inherits the
    disable without editing this function.
    """

    declared = V2Config.__dataclass_fields__[section].default_factory
    declared_fields = {info.name for info in fields(declared)}
    switches = {info.name for info in fields(declared) if info.type in (bool, "bool")}
    stored = payload.get(section)
    if not isinstance(stored, dict):
        # Nothing readable to keep, so every switch resolves off.
        stored = {name: False for name in switches}
        payload[section] = stored
    elif field_name is None:
        stored.update({name: False for name in switches})
    elif field_name in switches:
        stored[field_name] = False
    elif field_name in declared_fields:
        stored.pop(field_name, None)
    else:
        return False
    if _FEATURE_SWITCH_FIELD in switches:
        stored[_FEATURE_SWITCH_FIELD] = False
    return True
    return False


def _recover_runtime_field(payload: dict, field_name: Optional[str]) -> bool:
    """Repair one retention or collection field without discarding runtime."""

    if field_name not in _RUNTIME_RETENTION_FIELDS and field_name != "skill_observability_enabled":
        return False
    runtime = payload.get("runtime")
    if not isinstance(runtime, dict):
        return False
    if field_name == "skill_observability_enabled":
        runtime[field_name] = False
        return True
    # A recovered policy is disabled even if the other retention field looked
    # valid. The warning attached by ``V2Config.load`` keeps all automatic and
    # status consumers fail-closed until the operator repairs the file.
    runtime["agent_events_trace_retention_enabled"] = False
    if field_name == "agent_events_trace_retention_days":
        runtime[field_name] = 30
    else:
        runtime[field_name] = False
    return True


def _reset_recoverable_config_section(
    payload: dict, section: str, field_name: Optional[str] = None
) -> 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" and field_name is not None:
        if _recover_runtime_field(payload, field_name):
            return True
    if section in _FIELD_SCOPED_RECOVERY_SECTIONS:
        return _recover_switch_section_field(payload, section, field_name)
    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 == "model_hub":
        # Recovery is not an installation upgrade or consent to reroute native
        # backends. Keep the optional runtime disabled until the file is fixed.
        payload[section] = {"enabled": False, "runtime_default_applied": True}
        return True
    if section in {
        "remote_access",
        "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",
        "setup_completed",
    }:
        payload[section] = {
            "show_duration": False,
            "include_time_info": True,
            "include_user_info": True,
            "reply_enhancements": 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 field_name == _BACKEND_AUTO_UPDATE_FIELD and isinstance(agents_payload.get(agent_name), dict):
            agents_payload[agent_name][field_name] = False
            return True
        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


# A config path is a tuple of object keys from the document root. Recovery
# regions are tracked at most two keys deep: deep enough to keep one recovered
# Agent backend or one field-scoped setting apart from its siblings, shallow
# enough that a replaced section is compared and preserved as one value.
_RECOVERY_REGION_DEPTH = 2
_MISSING = object()
_RECOVERY_SAVE_REFUSAL = (
    "Config was loaded with recovery warnings; repair the backed-up "
    "config before saving changes"
)


def _config_json_text(value: object) -> Optional[str]:
    """Order-independent JSON identity of a stored value; ``None`` when absent."""

    if value is _MISSING:
        return None
    return json.dumps(value, sort_keys=True, default=repr)


def _config_value_at(document: object, path: tuple[str, ...]) -> object:
    value = document
    for key in path:
        if not isinstance(value, dict) or key not in value:
            return _MISSING
        value = value[key]
    return value


def _changed_config_paths(
    before: object, after: object, prefix: tuple[str, ...] = ()
) -> set[tuple[str, ...]]:
    """Where one recovery step rewrote the stored document."""

    if _config_json_text(before) == _config_json_text(after):
        return set()
    if (
        len(prefix) >= _RECOVERY_REGION_DEPTH
        or not isinstance(before, dict)
        or not isinstance(after, dict)
    ):
        return {prefix}
    changed: set[tuple[str, ...]] = set()
    for key in dict.fromkeys((*before, *after)):
        changed |= _changed_config_paths(
            before.get(key, _MISSING), after.get(key, _MISSING), (*prefix, key)
        )
    return changed


def _recovered_write_regions(
    regions: dict[tuple[str, ...], set[str]], candidate: dict
) -> tuple[tuple[tuple[str, ...], tuple[str, ...]], ...]:
    """Close recovery's rewritten paths over the values ``from_payload`` derives.

    A save writes derived values from memory, so when recovery rewrote their
    source the derived value would describe the recovered defaults instead of
    the preserved file: the legacy ``platform`` mirrors ``platforms.primary``,
    a forced-off ``audio_asr.enabled`` marks the switch as configured, and an
    absent ``setup_completed`` is inferred from the configured platforms.
    """

    regions = {path: set(causes) for path, causes in regions.items()}

    def follow(target: tuple[str, ...], is_source: Callable[[tuple[str, ...]], bool]) -> None:
        causes = set().union(*(owners for path, owners in regions.items() if is_source(path)))
        if causes:
            regions.setdefault(target, set()).update(causes)

    follow(("platform",), lambda path: path[0] == "platforms")
    follow(
        ("audio_asr", "enabled_configured"),
        lambda path: path == ("audio_asr", "enabled")[: len(path)],
    )
    if "setup_completed" not in candidate:
        setup_sources = {"mode", "platforms", "platform"} | {
            descriptor.config_key for descriptor in platform_descriptors()
        }
        follow(("setup_completed",), lambda path: path[0] in setup_sources)

    # A path inside another region is already preserved with it.
    merged: dict[tuple[str, ...], set[str]] = {}
    for path in sorted(regions, key=len):
        owner = next((region for region in merged if path[: len(region)] == region), None)
        merged.setdefault(owner or path, set()).update(regions[path])
    return tuple((path, tuple(sorted(causes))) for path, causes in sorted(merged.items()))


@dataclass(frozen=True)
class _RecoveredSectionGuard:
    """Write fence for a config whose sections were recovered at load (#2079).

    Recovery keeps strict parsing and substitutes safe defaults in memory. Those
    defaults must never become the file: a save that leaves every recovered
    region as loaded writes each region back from the file on disk, and a save
    that changes one is refused before anything is written.
    """

    warnings: tuple[str, ...]
    regions: tuple[tuple[tuple[str, ...], tuple[str, ...]], ...]
    loaded: tuple[Optional[str], ...]
    backup: Optional[str]

    @classmethod
    def capture(
        cls,
        config: "V2Config",
        warnings: tuple[str, ...],
        regions: tuple[tuple[tuple[str, ...], tuple[str, ...]], ...],
        backup: Optional[Path],
    ) -> "_RecoveredSectionGuard":
        document = config._persisted_document()
        return cls(
            warnings=warnings,
            regions=regions,
            loaded=tuple(_config_json_text(_config_value_at(document, path)) for path, _ in regions),
            backup=str(backup) if backup is not None else None,
        )

    def refusal(self, touched: list[tuple[tuple[str, ...], tuple[str, ...]]]) -> str:
        sections = sorted({section for _, causes in touched for section in causes})
        changed = ", ".join(".".join(path) for path, _ in touched)
        return (
            f"Config was loaded with recovery warnings for {', '.join(sections)}; "
            f"repair the backed-up config ({self.backup or 'backup unavailable'}) "
            f"before changing {changed}"
        )

    def change_refusal(self, document: dict) -> Optional[str]:
        touched = [
            region
            for region, loaded in zip(self.regions, self.loaded)
            if _config_json_text(_config_value_at(document, region[0])) != loaded
        ]
        return self.refusal(touched) if touched else None

    def scope_refusal(self, sections: tuple[str, ...]) -> Optional[str]:
        touched = [region for region in self.regions if region[0][0] in sections]
        return self.refusal(touched) if touched else None

    def preserve_stored_regions(self, path: Path, document: dict) -> dict:
        """Replace each recovered region with what the file holds now.

        The current file, not the bytes read at load: a region repaired or
        rewritten by another writer since then is kept as it now stands.
        """

        try:
            stored = json.loads(path.read_bytes().decode("utf-8"))
        except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
            raise ValueError(
                "Config was loaded with recovery warnings and its recovered sections "
                f"could not be re-read before saving: {exc}"
            ) from exc
        if not isinstance(stored, dict):
            raise ValueError(
                "Config was loaded with recovery warnings and the file on disk is no "
                "longer an object; repair it before saving changes"
            )
        for region, _ in self.regions:
            stored_parent = _config_value_at(stored, region[:-1])
            written_parent = _config_value_at(document, region[:-1])
            if not isinstance(written_parent, dict) or (
                stored_parent is not _MISSING and not isinstance(stored_parent, dict)
            ):
                raise ValueError(
                    "Config was loaded with recovery warnings and "
                    f"'{'.'.join(region)}' can no longer be preserved; repair the "
                    "config before saving changes"
                )
            value = stored_parent.get(region[-1], _MISSING) if isinstance(stored_parent, dict) else _MISSING
            if value is _MISSING:
                written_parent.pop(region[-1], None)
            else:
                written_parent[region[-1]] = value
        return document


def _active_recovery_guard(config: object) -> Optional[_RecoveredSectionGuard]:
    guard = getattr(config, "_recovery_guard", None)
    warnings = tuple(getattr(config, "load_warnings", ()) or ())
    if not isinstance(guard, _RecoveredSectionGuard) or not warnings or guard.warnings != warnings:
        return None
    return guard


# Model Hub writes and native Agent credential writes move both sections: the
# native takeover migrates Agent backend settings into the Hub.
AGENT_CREDENTIAL_SECTIONS = ("model_hub", "agents")


def config_recovery_refusal(config: object, *sections: str) -> Optional[str]:
    """Why a writer owning ``sections`` must wait for the config to be repaired.

    Section recovery blocks only the writers of the recovered sections; every
    other warning (migration, persistence, whole-document recovery) still blocks
    every writer. ``V2Config.save`` enforces the same regions on the final write.
    """

    if not getattr(config, "load_warnings", ()):
        return None
    guard = _active_recovery_guard(config)
    if guard is None:
        return _RECOVERY_SAVE_REFUSAL
    return guard.scope_refusal(sections)


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):
    """The shared cross-process lock guarding one config file."""

    return _path_file_lock(
        path.with_name(f".{path.name}.lock"),
        timeout_seconds=CONFIG_FILE_LOCK_TIMEOUT_SECONDS,
    )


@contextmanager
def config_file_lock(config_path: Optional[Path] = None) -> Iterator[None]:
    """Serialize work that must observe one exact persisted config snapshot.

    This is the same cross-process transaction used by ``V2Config.save`` and
    ``config_write_transaction``. It also takes the migration lock used by
    ``V2Config.load`` while persisting migrations, so ordinary saves cannot
    replace a file between migration verification and replacement. Keeping one
    lock path for ordinary config writes and guarded state transitions prevents
    a pairing update from racing a reader that is about to persist
    instance-owned state.
    """

    path = config_path or paths.get_config_path()
    path.parent.mkdir(parents=True, exist_ok=True)
    # Match load/migration and callers already holding the process-local lock.
    # Both locks are re-entrant; never acquire them in the opposite order.
    with CONFIG_LOCK:
        with _config_file_lock(path):
            yield


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_file_lock(path):
        write_atomic(path, content)


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",
    "apikey",
    "auth",
    "authorization",
    "bearer",
    "credential",
    "key",
    "password",
    "passwd",
    "secret",
    "sig",
    "signature",
    "token",
}


def is_model_hub_enabled(environ: Optional[Mapping[str, str]] = None) -> bool:
    """Enable Model Hub by default, honoring an explicit deployment override."""

    source = os.environ if environ is None else environ
    return source.get(MODEL_HUB_ENABLED_ENV, "1").strip().lower() in {"1", "true", "yes", "on"}


HubSupplyBlock = Literal["hub_disabled", "gateway_off", "no_source"]


def hub_supply_block(backend: str, hub: Optional["ModelHubConfig"]) -> Optional[HubSupplyBlock]:
    """Why the Model Hub leaves ``backend`` no model to run on now, or ``None``: the one owner of that answer.

    A backend without its own CLI gets every model through the Hub, so the operator's
    Model Hub switch (``VIBE_MODEL_HUB_ENABLED``) leaves it none, and so does a Hub with no
    source that may supply it. Any backend the Hub supplies has none while the user has
    turned the gateway off in Models. Without a Hub config only the switch can be read.
    """

    if not is_model_hub_enabled():
        return None if backend in NATIVE_CLI_BACKENDS else "hub_disabled"
    if hub is None:
        return None
    if not hub.enabled and hub.agents[backend].mode == "hub":
        return "gateway_off"
    if backend not in NATIVE_CLI_BACKENDS and not any(
        hub.source_eligible_for_backend(source, backend) for source in hub.sources
    ):
        return "no_source"
    return None


def _validate_optional_datetime(value: object, field_path: str) -> Optional[str]:
    if value is None:
        return None
    if not isinstance(value, str):
        raise ValueError(f"Config '{field_path}' must be a date-time string or null")
    try:
        parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
    except ValueError as exc:
        raise ValueError(f"Config '{field_path}' must be a valid date-time") from exc
    if parsed.tzinfo is None:
        raise ValueError(f"Config '{field_path}' must include a timezone")
    return value


def normalize_model_hub_base_url(
    value: object,
    *,
    append_path: str | None = None,
) -> Optional[str]:
    """Validate a Source URL and optionally append an upstream API path."""

    if value is None:
        return None
    if not isinstance(value, str) or not value.strip():
        raise ValueError("Config 'model_hub.sources.base_url' is invalid")
    try:
        parsed = urlsplit(value.strip())
        hostname = parsed.hostname
    except ValueError as exc:
        raise ValueError("Config 'model_hub.sources.base_url' is invalid") from exc
    if (
        parsed.scheme.lower() not in {"http", "https"}
        or not hostname
        or parsed.username is not None
        or parsed.password is not None
        or parsed.fragment
    ):
        raise ValueError("Config 'model_hub.sources.base_url' is invalid")
    for key, _ in parse_qsl(
        parsed.query,
        keep_blank_values=True,
    ):
        normalized = key.strip().lower().replace("-", "_").replace(".", "_")
        if normalized in _MODEL_HUB_CREDENTIAL_QUERY_KEYS or any(
            marker in normalized
            for marker in (
                "api_key",
                "access_token",
                "auth_token",
                "token",
                "authorization",
                "signature",
                "secret",
                "password",
                "credential",
            )
        ):
            raise ValueError("Config 'model_hub.sources.base_url' is invalid")
    if _contains_model_hub_credential_material(value):
        raise ValueError("Config 'model_hub.sources.base_url' is invalid")
    path = parsed.path.rstrip("/")
    if append_path is not None:
        if not append_path.startswith("/") or append_path.startswith("//"):
            raise ValueError("Model Hub URL path must be relative to the API root")
        path = f"{path}{append_path}"
    return urlunsplit((parsed.scheme.lower(), parsed.netloc, path, parsed.query, ""))


def _validate_model_hub_base_url(value: object) -> Optional[str]:
    return normalize_model_hub_base_url(value)


_MODEL_HUB_SOURCE_CLIENT_NONCE_PATTERN = re.compile(r"^scn_[a-z0-9]{16,64}$")


def validate_model_hub_source_client_nonce(value: object) -> str:
    if (
        not isinstance(value, str)
        or _MODEL_HUB_SOURCE_CLIENT_NONCE_PATTERN.fullmatch(value) is None
    ):
        raise ValueError("Config 'model_hub.sources.client_nonce' is invalid")
    return value


def _filter_dataclass_fields(dc_class, payload: dict) -> dict:
    """Filter payload to only include fields defined in dataclass."""
    valid_fields = {f.name for f in fields(dc_class)}
    return {k: v for k, v in payload.items() if k in valid_fields}


@dataclass
class SlackConfig(BaseIMConfig):
    bot_token: str = ""
    app_token: Optional[str] = None
    signing_secret: Optional[str] = None
    team_id: Optional[str] = None
    team_name: Optional[str] = None
    app_id: Optional[str] = None
    require_mention: bool = False
    # Global default for the per-channel require_bind gate (allowed users).
    # False=any channel member may drive the agent, True=only bound users.
    # Seeds newly enabled channels; runtime None/False remains unrestricted.
    require_bind: bool = False
    disable_link_unfurl: bool = False

    def validate(self) -> None:
        # Allow empty token for initial setup
        if self.bot_token and not self.bot_token.startswith("xoxb-"):
            raise ValueError("Invalid Slack bot token format (should start with xoxb-)")
        if self.app_token and not self.app_token.startswith("xapp-"):
            raise ValueError("Invalid Slack app token format (should start with xapp-)")


@dataclass
class DiscordConfig(BaseIMConfig):
    bot_token: str = ""
    application_id: Optional[str] = None
    # Legacy input fields. Runtime server access is stored in settings.json
    # under scopes.guild.discord so it stays with channel/user scope settings.
    guild_allowlist: Optional[List[str]] = None
    guild_denylist: Optional[List[str]] = None
    require_mention: bool = False
    # Global default for the per-channel require_bind gate (allowed users).
    require_bind: bool = False
    # Auto-archive duration (minutes) for threads created by vibe-remote.
    # Discord only accepts 60, 1440, 4320, or 10080 (1h / 1d / 3d / 7d).
    # Defaults to 10080 (7d) to match Discord's longest native inactivity window
    # rather than aggressively archiving idle sessions after 1 hour.
    thread_auto_archive_minutes: int = 10080

    def validate(self) -> None:
        # Allow empty token for initial setup
        if self.bot_token and len(self.bot_token.strip()) < 10:
            raise ValueError("Invalid Discord bot token format")
        allowed_archive = {60, 1440, 4320, 10080}
        if self.thread_auto_archive_minutes not in allowed_archive:
            raise ValueError(
                "Invalid Discord thread_auto_archive_minutes "
                f"{self.thread_auto_archive_minutes!r}; must be one of "
                f"{sorted(allowed_archive)}"
            )


@dataclass
class TelegramConfig(BaseIMConfig):
    bot_token: str = ""
    require_mention: bool = True
    # Global default for the per-channel require_bind gate (allowed users).
    require_bind: bool = False
    forum_auto_topic: bool = True
    use_webhook: bool = False
    webhook_url: Optional[str] = None
    webhook_secret_token: Optional[str] = None
    allowed_chat_ids: Optional[List[str]] = None
    allowed_user_ids: Optional[List[str]] = None

    def validate(self) -> None:
        # Allow empty token for initial setup
        if self.bot_token and ":" not in self.bot_token:
            raise ValueError("Invalid Telegram bot token format")


@dataclass
class LarkConfig(BaseIMConfig):
    app_id: str = ""
    app_secret: str = ""
    require_mention: bool = False
    # Global default for the per-channel require_bind gate (allowed users).
    require_bind: bool = False
    domain: str = "feishu"  # "feishu" for domestic (open.feishu.cn), "lark" for international (open.larksuite.com)

    def validate(self) -> None:
        if self.domain not in ("feishu", "lark"):
            raise ValueError(f"Invalid lark domain: {self.domain!r}. Must be 'feishu' or 'lark'.")

    @property
    def api_base_url(self) -> str:
        """Return the base API URL for the configured domain."""
        if self.domain == "lark":
            return "https://open.larksuite.com"
        return "https://open.feishu.cn"


@dataclass
class WeChatConfig(BaseIMConfig):
    bot_token: str = ""
    base_url: str = "https://ilinkai.weixin.qq.com"
    cdn_base_url: str = "https://novac2c.cdn.weixin.qq.com/c2c"
    require_mention: bool = False  # unused for WeChat DM-only, kept for interface compat
    require_bind: bool = False  # unused for WeChat DM-only, kept for interface compat

    def validate(self) -> None:
        # bot_token can be empty during setup wizard (filled after QR login)
        pass


@dataclass
class AvibeConfig(BaseIMConfig):
    """Avibe — Vibe Remote's own Web UI surfaced as a first-class IM platform.

    Runs in-process; no remote credentials. ``enabled`` lets headless
    deployments skip the workbench surface entirely while keeping the
    other IM-bridge platforms (Slack/Discord/...) wired up.
    """

    enabled: bool = True

    def validate(self) -> None:
        return None


@dataclass
class GatewayConfig:
    relay_url: Optional[str] = None
    workspace_token: Optional[str] = None
    client_id: Optional[str] = None
    client_secret: Optional[str] = None
    last_connected_at: Optional[str] = None


@dataclass
class AudioAsrConfig:
    enabled: bool = True
    echo_transcript: bool = True
    enabled_configured: bool = False
    timeout_seconds: float = 60.0
    endpoint_path: str = "/v1/audio/transcriptions"
    model: str = "qwen3-asr-flash"
    max_file_bytes: Optional[int] = None

    def __post_init__(self) -> None:
        """Refuse a value that is not the kind this class declares.

        ``from_payload`` copies this section verbatim, and an Editor may now
        persist it, so a stale client or a hand-edited config can put ``[]``
        where a switch belongs. Nothing further down coerces it: the Settings
        pages read ``value !== false`` as on while ``AudioAsrService`` reads the
        same value for truth, so ASR renders as enabled while transcription is
        off. A ``true`` where ``timeout_seconds`` belongs is the same defect one
        kind over — ``float(True)`` is a legal one-second timeout.

        Enforced here rather than in ``from_payload`` so every construction path
        holds the invariant the field types already claim.
        """
        _refuse_values_naming_nothing("audio_asr", self)


def _looks_like_ui_mask(value: str) -> bool:
    stripped = value.strip()
    return bool(stripped) and all(character in {"*", "•", "x", "X"} for character in stripped)


@dataclass
class RuntimeConfig:
    default_cwd: str
    log_level: str = "INFO"
    # Synchronous handlers under /show/*/api and /p/*/api may depend on slower
    # operational systems. Keep this separate from ordinary Runtime asset
    # requests, which retain their shorter transport timeout.
    show_page_api_timeout_seconds: float = DEFAULT_SHOW_PAGE_API_TIMEOUT_SECONDS
    # Linux/cgroup v2 best-effort resource governance for aggregate agent
    # workload. "auto" enables it only when Avibe can create and write the
    # delegated cgroup; unsupported systems silently fall back to legacy spawn.
    resource_governance: dict = field(default_factory=lambda: {"mode": "auto"})
    # Harness run staleness sweep. A Run whose executor died, whose transport never
    # came back, or whose workbench queue hold was never released has nothing left to
    # write its terminal state, so it would sit ``running``/``queued`` forever. The
    # sweep terminalizes those on evidence (see
    # ``docs/plans/agent-run-zombie-settlement.md`` §4). Each key is seconds and ``0``
    # disables that class; the defaults are the product decision, so there is no UI.
    harness_run_sweep_interval_seconds: int = DEFAULT_HARNESS_RUN_SWEEP_INTERVAL_SECONDS
    harness_run_orphan_grace_seconds: int = DEFAULT_HARNESS_RUN_ORPHAN_GRACE_SECONDS
    harness_run_queued_ttl_seconds: int = DEFAULT_HARNESS_RUN_QUEUED_TTL_SECONDS
    harness_run_hold_ttl_seconds: int = DEFAULT_HARNESS_RUN_HOLD_TTL_SECONDS
    # Echo the Harness-originated prompt into the IM conversation when a background
    # task (scheduled task, watch, webhook, hook, ``vibe agent run``) starts an agent
    # turn there. The Workbench transcript already renders that prompt from the
    # ``harness`` Message row; an IM channel had no equivalent, so a scheduled reply
    # arrived as an answer to a question nobody in the channel could see. Off means
    # today's behavior (result only).
    harness_prompt_echo: bool = True
    # Bounded retention for internal agent trace events (``agent_events`` rows
    # with ``event_type='tool_call'`` and ``visibility='trace'``). These are
    # debug/diagnostic material, never chat messages; without a bound an active
    # installation grows ``vibe.sqlite`` without limit. Default-on: the first
    # controller startup after upgrading runs a pass that permanently deletes
    # tool_call traces older than the window — set ``enabled=False`` BEFORE
    # upgrading to preserve old diagnostics. User docs (en+zh): the
    # ``vibe data retention`` section of the CLI reference (avibe-docs).
    agent_events_trace_retention_enabled: bool = True
    agent_events_trace_retention_days: int = 30
    skill_observability_enabled: bool = True

    def __post_init__(self) -> None:
        if not isinstance(self.skill_observability_enabled, bool):
            raise ValueError("Config 'runtime.skill_observability_enabled' must be a boolean")
        self.show_page_api_timeout_seconds = _named_value(
            "runtime.show_page_api_timeout_seconds",
            float,
            self.show_page_api_timeout_seconds,
        )
        if self.show_page_api_timeout_seconds <= 0:
            raise ValueError(
                "Config 'runtime.show_page_api_timeout_seconds' must be greater than zero"
            )
        # These values control irreversible deletion.  Dataclass annotations do
        # not validate JSON payloads, and coercing a string/bool here could turn
        # a malformed config into a shorter retention window.
        if not isinstance(self.agent_events_trace_retention_enabled, bool):
            raise ValueError(
                "Config 'runtime.agent_events_trace_retention_enabled' must be a boolean"
            )
        validate_retention_days(
            self.agent_events_trace_retention_days,
            field="Config 'runtime.agent_events_trace_retention_days'",
        )


@dataclass
class OpenCodeConfig:
    enabled: bool = True
    cli_path: str = "opencode"
    # Install a newer release of this backend CLI once no turn is using it.
    # Runs on the Avibe update checker, so ``update.check_interval_minutes = 0``
    # also stops it.
    auto_update: bool = True
    default_agent: Optional[str] = None
    default_reasoning_effort: Optional[str] = None
    error_retry_limit: int = DEFAULT_OPENCODE_ERROR_RETRY_LIMIT  # Max retries on LLM stream errors (0 = no retry)
    active_turn_timeout_seconds: int = DEFAULT_OPENCODE_ACTIVE_TURN_TIMEOUT_SECONDS
    # Provenance for the legacy-default neutralization: once this config has
    # been written (or migrated) under the opt-in semantics the key is present,
    # and a deliberate ``active_turn_timeout_seconds == 5400`` saved afterwards
    # is an explicit operator choice the load migration must preserve.
    legacy_turn_timeout_neutralized: bool = True
    # Provider the user picked in Settings → Backends → OpenCode. The provider
    # catalog itself lives in ~/.config/opencode/opencode.json (OpenCode's own
    # state file). Stays ``None`` until the user explicitly chooses so legacy
    # installs (e.g. Ollama/OpenAI users) keep falling back to OpenCode's own
    # routing for bare-model strings instead of being silently rerouted to
    # Anthropic on upgrade.
    default_provider: Optional[str] = None


@dataclass
class ClaudeConfig:
    enabled: bool = True
    cli_path: str = "claude"
    auto_update: bool = True  # See ``OpenCodeConfig.auto_update``.
    idle_timeout_seconds: int = DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
    # Auth model: "oauth" relies on Claude Code's own credential storage;
    # "api_key" injects ANTHROPIC_API_KEY (and optionally ANTHROPIC_BASE_URL)
    # at CLI launch time for API gateway / proxy setups.
    auth_mode: Literal["oauth", "api_key"] = "oauth"
    api_key: Optional[str] = None
    base_url: Optional[str] = None
    # ``True`` once the user has saved a Claude auth choice through the
    # Settings UI (or removed the API key, or signed out). Legacy installs
    # — V2 configs that predate the Settings page or have never touched
    # it — load with ``False`` because the field defaults to ``False`` and
    # isn't in their on-disk JSON. ``build_claude_subprocess_env`` reads
    # this to decide whether to honor ``auth_mode`` strictly (strip
    # inherited ``ANTHROPIC_*`` env in OAuth mode) or preserve the
    # legacy env-var-only auth path. Without this flag the schema's
    # ``auth_mode == "oauth"`` default is indistinguishable between
    # "explicit OAuth pick" and "user has never opened Settings".
    auth_mode_set: bool = False


@dataclass
class CodexConfig:
    enabled: bool = True
    cli_path: str = "codex"
    auto_update: bool = True  # See ``OpenCodeConfig.auto_update``.
    idle_timeout_seconds: int = DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
    # Auth model: "oauth" defers to whatever ~/.codex/config.toml already
    # has (typically `auth.method = "ChatGPT"`); "api_key" writes the
    # config.toml fields that point Codex at an API key + custom base URL.
    auth_mode: Literal["oauth", "api_key"] = "oauth"
    api_key: Optional[str] = None
    base_url: Optional[str] = None
    # Relay recovery marker captured at an OAuth transition:
    # ``{"provider_id": str, "base_url": str}`` recorded from the live
    # ``config.toml`` immediately BEFORE the OAuth cleanup clears the
    # provider pointer and drops the managed section (the only moment
    # the relay's identity is observable — Settings-created managed
    # relays and hand-rolled sections are both visible then). Consumed
    # verbatim, with no ambient-state inference, by the Settings read
    # and the next API-key save; cleared only by an explicit API-key
    # save or sign-out. Repeated OAuth transitions retain it. Older
    # configs load with ``None`` (unknown JSON keys are filtered), so
    # the field degrades safely across releases.
    oauth_relay_marker: Optional[dict] = None


@dataclass
class AVaultConfig:
    cli_path: str = "avault"


@dataclass
class AgentsConfig:
    default_backend: str = DEFAULT_AGENT_BACKEND
    opencode: OpenCodeConfig = field(default_factory=OpenCodeConfig)
    claude: ClaudeConfig = field(default_factory=ClaudeConfig)
    codex: CodexConfig = field(default_factory=CodexConfig)
    avault: AVaultConfig = field(default_factory=AVaultConfig)


_SettledItem = TypeVar("_SettledItem")


def _collapse_settled_duplicates(
    parsed: list[_SettledItem],
    identity: Callable[[_SettledItem], object],
    as_written: list,
    message: str,
    *,
    repairing: bool,
) -> list[_SettledItem]:
    """Keep a collection of model identifiers unique after spelling is settled.

    `normalized_model_id` is a many-to-one map applied inside the leaf validator,
    while the uniqueness check belongs to the parent holding the collection. So
    every such parent is checking pre-images while the object it builds carries
    post-images, and the difference is not cosmetic: the loaded config keeps both
    entries, `to_payload` writes one spelling for both, and the next load of what
    this one wrote raises. Loading a file must produce something loadable, and
    that round trip is what this restores.

    Duplicates **as written** are a malformed payload either way and raise.
    Duplicates that appear only once spelling is settled depend on where the
    payload came from, which is what `repairing` names:

    - Repairing a payload already on disk, the later entry collapses into the
      earlier. It was already unreachable — an inventory lookup and an exact hop
      comparison both find the first — and raising would fail exactly the load the
      persisted-shape rule requires to succeed.
    - Admitting a payload from a caller, the same pair is a request to name one
      model twice, and silently keeping one half answers with a collection the
      caller did not send. It raises, so the caller learns which spelling survived
      by being told rather than by reading the response.

    Required, and not defaulted, because the answer is a property of the caller
    rather than of the collection: a parser cannot infer whether it is repairing
    history or admitting a request, and a default would let the next call site
    inherit whichever guess this one made.
    """

    if len(set(as_written)) != len(as_written):
        raise ValueError(message)
    if not repairing:
        settled_ids = [identity(item) for item in parsed]
        if len(set(settled_ids)) != len(settled_ids):
            raise ValueError(message)
        return list(parsed)
    collapsed: list[_SettledItem] = []
    seen: set[object] = set()
    for item in parsed:
        settled = identity(item)
        if settled in seen:
            continue
        seen.add(settled)
        collapsed.append(item)
    return collapsed


@dataclass
class ModelHubModelConfig:
    id: str
    provenance: Literal["discovered", "manual"]
    reasoning_efforts: list[str] = field(default_factory=list)
    reasoning_efforts_source: Optional[
        Literal["upstream", "catalog", "user"]
    ] = None
    display_name: Optional[str] = None
    discovered_at: Optional[str] = None
    retired: Optional[bool] = None

    @classmethod
    def from_payload(cls, payload: dict) -> "ModelHubModelConfig":
        if not isinstance(payload, dict):
            raise ValueError("Config 'model_hub.sources.models' entries must be objects")
        if set(payload) - {
            "id",
            "display_name",
            "origin",
            "reasoning_efforts",
            "reasoning_efforts_source",
            "discovered_at",
            "retired",
        }:
            raise ValueError("Config 'model_hub.sources.models' contains unknown fields")
        model_id = payload.get("id")
        origin = payload.get("origin")
        if "reasoning_efforts" not in payload:
            raise ValueError("Config 'model_hub.sources.models.reasoning_efforts' is required")
        reasoning_efforts = payload["reasoning_efforts"]
        if "reasoning_efforts_source" in payload:
            reasoning_efforts_source = payload["reasoning_efforts_source"]
        else:
            reasoning_efforts_source = "user" if reasoning_efforts else None
        display_name = payload.get("display_name")
        discovered_at = payload.get("discovered_at")
        retired = payload.get("retired")
        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 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)
            or any(not isinstance(effort, str) or not effort for effort in reasoning_efforts)
            or len(set(reasoning_efforts)) != len(reasoning_efforts)
            or any(_contains_model_hub_credential_material(effort) for effort in reasoning_efforts)
        ):
            raise ValueError(
                "Config 'model_hub.sources.models.reasoning_efforts' must be a unique credential-free array of strings"
            )
        if reasoning_efforts_source is not None and (
            not isinstance(reasoning_efforts_source, str)
            or reasoning_efforts_source not in {"upstream", "catalog", "user"}
        ):
            raise ValueError(
                "Config 'model_hub.sources.models.reasoning_efforts_source' is invalid"
            )
        if reasoning_efforts and reasoning_efforts_source is None:
            raise ValueError(
                "Config non-empty reasoning efforts require a provenance source"
            )
        if not reasoning_efforts and reasoning_efforts_source in {"upstream", "user"}:
            raise ValueError(
                "Config empty reasoning efforts cannot use upstream or user provenance"
            )
        if display_name is not None and (
            not isinstance(display_name, str)
            or _contains_model_hub_credential_material(display_name)
        ):
            raise ValueError("Config 'model_hub.sources.models.display_name' must be a string or null")
        if origin == "manual" and discovered_at is not None:
            raise ValueError("Config manual model entries cannot carry discovered_at")
        if retired is not None and (
            not isinstance(retired, bool) or (origin == "manual" and retired)
        ):
            raise ValueError(
                "Config 'model_hub.sources.models.retired' must be false for manual models"
            )
        # Spelling is settled here, at the one place a payload becomes a model
        # config, so no admission path can invent a second spelling for one
        # model and split its usage across two ledger rows. New-admission checks
        # stay with callers: this constructor also reads older persisted files.
        from core.handlers.model_hub.identifiers import normalized_model_id

        return cls(
            id=normalized_model_id(model_id),
            provenance=origin,
            reasoning_efforts=list(reasoning_efforts),
            reasoning_efforts_source=reasoning_efforts_source,
            display_name=display_name,
            discovered_at=_validate_optional_datetime(
                discovered_at,
                "model_hub.sources.models.discovered_at",
            ),
            retired=retired,
        )

    def to_payload(self) -> dict:
        reasoning_efforts_source = self.reasoning_efforts_source
        if reasoning_efforts_source is None and self.reasoning_efforts:
            reasoning_efforts_source = "user"
        payload = {
            "id": self.id,
            "display_name": self.display_name,
            "origin": self.provenance,
            "reasoning_efforts": list(self.reasoning_efforts),
            "reasoning_efforts_source": reasoning_efforts_source,
            "discovered_at": self.discovered_at,
        }
        if self.retired is not None:
            payload["retired"] = self.retired
        return payload


@dataclass
class ModelHubSourceStateConfig:
    status: Literal["active", "standby", "cooldown", "needs_action", "error"] = "standby"
    retry_at: Optional[str] = None
    detail_key: Optional[str] = None

    @classmethod
    def from_payload(cls, payload: dict) -> "ModelHubSourceStateConfig":
        if not isinstance(payload, dict):
            raise ValueError("Config 'model_hub.sources.state' must be an object")
        if set(payload) - {"status", "retry_at", "detail_key"}:
            raise ValueError("Config 'model_hub.sources.state' contains unknown fields")
        status = payload.get("status")
        retry_at = payload.get("retry_at")
        detail_key = payload.get("detail_key")
        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")
        cooldown_keys = {
            None,
            "models.source.cooldown.network",
            "models.source.cooldown.timeout",
            "models.source.cooldown.rate_limited",
            "models.source.cooldown.quota_exhausted",
            "models.source.cooldown.server_error",
        }
        needs_action_keys = {
            "models.source.needs_action.oauth_expired",
            "models.source.needs_action.balance_exhausted",
            "models.source.needs_action.credential_revoked",
            "models.source.needs_action.account_banned",
            "models.source.needs_action.plan_excludes_product",
            "models.source.needs_action.spend_limit_reached",
        }
        if status in {"active", "standby"} and (retry_at is not None or detail_key is not None):
            raise ValueError(f"Config healthy source state '{status}' cannot carry blocker detail")
        if status == "cooldown" and (retry_at is None or detail_key not in cooldown_keys):
            raise ValueError("Config cooldown source state requires retry_at and a known detail key")
        if status == "needs_action" and (retry_at is not None or detail_key not in needs_action_keys):
            raise ValueError("Config needs_action source state requires a known detail key")
        if status == "error" and (retry_at is not None or detail_key != "models.source.error.unclassified"):
            raise ValueError("Config error source state requires the generic error detail key")
        return cls(
            status=status,
            retry_at=_validate_optional_datetime(retry_at, "model_hub.sources.state.retry_at"),
            detail_key=detail_key,
        )

    def to_payload(self) -> dict:
        return {"status": self.status, "retry_at": self.retry_at, "detail_key": self.detail_key}


@dataclass
class ModelHubSourceUsageConfig:
    cycle_used_pct: Optional[float] = None
    month_spend_cents: Optional[int] = None
    currency: Optional[str] = None
    projected_exhaust_at: Optional[str] = None

    @classmethod
    def from_payload(cls, payload: dict) -> "ModelHubSourceUsageConfig":
        if not isinstance(payload, dict):
            raise ValueError("Config 'model_hub.sources.usage' must be an object")
        if set(payload) - {
            "cycle_used_pct",
            "month_spend_cents",
            "currency",
            "projected_exhaust_at",
        }:
            raise ValueError("Config 'model_hub.sources.usage' contains unknown fields")
        cycle_used_pct = payload.get("cycle_used_pct")
        if cycle_used_pct is not None and (
            isinstance(cycle_used_pct, bool)
            or not isinstance(cycle_used_pct, (int, float))
            or not 0 <= cycle_used_pct <= 100
        ):
            raise ValueError("Config 'model_hub.sources.usage.cycle_used_pct' must be between 0 and 100")
        month_spend_cents = payload.get("month_spend_cents")
        currency = payload.get("currency")
        projected_exhaust_at = payload.get("projected_exhaust_at")
        if month_spend_cents is not None and (
            isinstance(month_spend_cents, bool) or not isinstance(month_spend_cents, int) or month_spend_cents < 0
        ):
            raise ValueError("Config 'model_hub.sources.usage.month_spend_cents' must be a non-negative integer")
        if currency is not None and not isinstance(currency, str):
            raise ValueError("Config 'model_hub.sources.usage.currency' must be a string or null")
        return cls(
            cycle_used_pct=cycle_used_pct,
            month_spend_cents=month_spend_cents,
            currency=currency,
            projected_exhaust_at=_validate_optional_datetime(
                projected_exhaust_at,
                "model_hub.sources.usage.projected_exhaust_at",
            ),
        )

    def to_payload(self) -> dict:
        return {
            "cycle_used_pct": self.cycle_used_pct,
            "month_spend_cents": self.month_spend_cents,
            "currency": self.currency,
            "projected_exhaust_at": self.projected_exhaust_at,
        }


@dataclass
class ModelHubSourceConfig:
    id: str
    kind: Literal["subscription", "api_key"]
    vendor: str
    display_name: str
    protocol: Literal["anthropic", "openai_responses", "openai_chat", "google", "search"]
    supply_channel: Literal["native_cli", "hub"]
    billing: Literal["monthly", "metered"]
    state: ModelHubSourceStateConfig
    models: list[ModelHubModelConfig]
    created_at: str = MODEL_HUB_LEGACY_CREATED_AT
    client_nonce: Optional[str] = None
    last_discovered_at: Optional[str] = None
    base_url: Optional[str] = None
    usage: Optional[ModelHubSourceUsageConfig] = None
    credential_ref: Optional[str] = None
    account_label: Optional[str] = None
    masked_credential: Optional[str] = None
    verification_pending: Optional[str] = None
    # The verification marker minted at the latest credential or endpoint change, kept when verification clears the
    # marker: the Source's identity follows it, so an identity never returns to one an earlier credential had, even
    # when OAuth reauthentication keeps the credential's handle. Absent until the first such change.
    credential_generation: Optional[str] = None

    def __post_init__(self) -> None:
        if self.credential_generation is None and self.verification_pending:
            # A release before the generation left a pending Source with only its marker, which named the change that
            # minted it: that marker is the change's generation, so the identity stays what it was.
            self.credential_generation = self.verification_pending

    @classmethod
    def from_payload(cls, payload: dict, *, repairing: bool = False) -> "ModelHubSourceConfig":
        if not isinstance(payload, dict):
            raise ValueError("Config 'model_hub.sources' entries must be objects")
        allowed_fields = {
            "id",
            "created_at",
            "client_nonce",
            "last_discovered_at",
            "kind",
            "vendor",
            "display_name",
            "protocol",
            "base_url",
            "supply_channel",
            "billing",
            "state",
            "usage",
            "models",
            "credential_ref",
            "account_label",
            "masked_credential",
            "verification_pending",
            "credential_generation",
        }
        if set(payload) - allowed_fields:
            raise ValueError("Config 'model_hub.sources' contains unknown fields")
        source_id = payload.get("id")
        kind = payload.get("kind")
        vendor = payload.get("vendor")
        display_name = payload.get("display_name")
        protocol = payload.get("protocol")
        supply_channel = payload.get("supply_channel")
        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 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 not isinstance(protocol, str) or protocol not in {
            "anthropic",
            "openai_responses",
            "openai_chat",
            "google",
            "search",
        }:
            raise ValueError("Config 'model_hub.sources.protocol' is invalid")
        validate_model_hub_protocol_vendor(vendor, protocol)
        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 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):
            raise ValueError("Config 'model_hub.sources.models' must be an array")
        model_ids = [model.get("id") for model in models_payload if isinstance(model, dict)]
        if len(model_ids) != len(models_payload):
            raise ValueError("Config 'model_hub.sources.models' entries must be objects")
        if any(not isinstance(model_id, str) for model_id in model_ids):
            raise ValueError("Config 'model_hub.sources.models.id' must be a non-empty string")
        models = _collapse_settled_duplicates(
            [ModelHubModelConfig.from_payload(model) for model in models_payload],
            lambda model: model.id,
            model_ids,
            "Config 'model_hub.sources.models' contains duplicate ids",
            repairing=repairing,
        )
        usage_payload = payload.get("usage")
        base_url = payload.get("base_url")
        credential_ref = payload.get("credential_ref")
        account_label = payload.get("account_label")
        masked_credential = payload.get("masked_credential")
        verification_pending = payload.get("verification_pending")
        if verification_pending is not None and (
            not isinstance(verification_pending, str)
            or re.fullmatch(r"vp_[0-9a-f]{32}", verification_pending) is None
        ):
            raise ValueError("Config 'model_hub.sources.verification_pending' must be a verification marker")
        credential_generation = payload.get("credential_generation")
        if credential_generation is not None and (
            not isinstance(credential_generation, str)
            or re.fullmatch(r"vp_[0-9a-f]{32}", credential_generation) is None
        ):
            raise ValueError("Config 'model_hub.sources.credential_generation' must be a verification marker")
        created_at = payload.get("created_at")
        client_nonce = (
            validate_model_hub_source_client_nonce(payload.get("client_nonce"))
            if "client_nonce" in payload
            else None
        )
        last_discovered_at = payload.get("last_discovered_at")
        base_url = _validate_model_hub_base_url(base_url)
        if credential_ref is not None and not isinstance(credential_ref, str):
            raise ValueError("Config 'model_hub.sources.credential_ref' is invalid")
        if account_label is not None and not isinstance(account_label, str):
            raise ValueError("Config 'model_hub.sources.account_label' is invalid")
        if masked_credential is not None and not isinstance(masked_credential, str):
            raise ValueError("Config 'model_hub.sources.masked_credential' is invalid")
        if protocol == "search" and (
            kind != "api_key" or supply_channel != "hub" or billing != "metered"
            or models or base_url is not None
        ):
            raise ValueError("Search Sources are tool-only metered hub API keys without a base URL")
        if kind == "subscription" and (base_url is not None or masked_credential is not None):
            raise ValueError("Config subscription Sources cannot carry API-key fields")
        if kind == "api_key" and supply_channel != "hub":
            raise ValueError("Config API-key Sources must use the hub channel")
        if supply_channel == "native_cli" and credential_ref is not None:
            raise ValueError("Config native Sources cannot carry an engine credential ref")
        if supply_channel == "hub" and (not isinstance(credential_ref, str) or not credential_ref):
            raise ValueError("Config hub Sources require an engine credential ref")
        if kind == "api_key" and usage_payload is not None:
            projected_exhaust_at = usage_payload.get("projected_exhaust_at") if isinstance(usage_payload, dict) else None
            if projected_exhaust_at is not None:
                raise ValueError("Config API-key Sources cannot carry projected exhaustion")
        return cls(
            id=source_id,
            kind=kind,
            vendor=vendor,
            display_name=display_name,
            protocol=protocol,
            supply_channel=supply_channel,
            billing=billing,
            state=ModelHubSourceStateConfig.from_payload(payload.get("state")),
            models=models,
            created_at=(
                _validate_optional_datetime(
                    created_at,
                    "model_hub.sources.created_at",
                )
                or MODEL_HUB_LEGACY_CREATED_AT
            ),
            client_nonce=client_nonce,
            last_discovered_at=_validate_optional_datetime(
                last_discovered_at,
                "model_hub.sources.last_discovered_at",
            ),
            base_url=base_url,
            usage=ModelHubSourceUsageConfig.from_payload(usage_payload) if usage_payload is not None else None,
            credential_ref=credential_ref,
            account_label=account_label,
            masked_credential=masked_credential,
            verification_pending=verification_pending,
            credential_generation=credential_generation,
        )

    def to_payload(self) -> dict:
        payload = {
            "id": self.id,
            "created_at": self.created_at,
            "last_discovered_at": self.last_discovered_at,
            "kind": self.kind,
            "vendor": self.vendor,
            "display_name": self.display_name,
            "protocol": self.protocol,
            "base_url": self.base_url,
            "supply_channel": self.supply_channel,
            "billing": self.billing,
            "state": self.state.to_payload(),
            "models": [model.to_payload() for model in self.models],
            "credential_ref": self.credential_ref,
            "account_label": self.account_label,
            "masked_credential": self.masked_credential,
        }
        if self.client_nonce is not None:
            payload["client_nonce"] = self.client_nonce
        if self.verification_pending:
            payload["verification_pending"] = self.verification_pending
        if self.credential_generation:
            payload["credential_generation"] = self.credential_generation
        if self.usage is not None:
            payload["usage"] = self.usage.to_payload()
        return payload


@dataclass(frozen=True)
class ModelHubRouteHopConfig:
    source_id: str
    model_id: str

    @classmethod
    def from_payload(cls, payload: object) -> "ModelHubRouteHopConfig":
        if not isinstance(payload, dict) or set(payload) != {"source_id", "model_id"}:
            raise ValueError("Config 'model_hub.agents.routes.hops' entries must contain source_id and model_id")
        source_id = payload.get("source_id")
        model_id = payload.get("model_id")
        if not isinstance(source_id, str) or re.fullmatch(r"src_[a-z0-9]{8,}", source_id) is None:
            raise ValueError("Config 'model_hub.agents.routes.hops.source_id' is invalid")
        if (
            not isinstance(model_id, str)
            or not model_id
            or _contains_model_hub_credential_material(model_id)
        ):
            raise ValueError("Config 'model_hub.agents.routes.hops.model_id' is invalid")
        # Keep saved targets in the same canonical namespace as inventory evidence.
        from core.handlers.model_hub.identifiers import normalized_model_id

        return cls(source_id=source_id, model_id=normalized_model_id(model_id))

    def to_payload(self) -> dict:
        return {"source_id": self.source_id, "model_id": self.model_id}


@dataclass
class ModelHubRouteConfig:
    hops: tuple[ModelHubRouteHopConfig, ...] = ()
    cache_ttl: Optional[Literal["5m", "30m", "1h", "12h"]] = None

    @classmethod
    def from_payload(cls, payload: object, *, repairing: bool = False) -> "ModelHubRouteConfig":
        if not isinstance(payload, dict) or set(payload) - {"hops", "cache_ttl"} or "hops" not in payload:
            raise ValueError("Config 'model_hub.agents.routes' entries must contain hops")
        hops = payload.get("hops")
        if not isinstance(hops, list):
            raise ValueError("Config 'model_hub.agents.routes.hops' must be an array")
        cache_ttl = payload.get("cache_ttl")
        if cache_ttl is not None and (
            not isinstance(cache_ttl, str)
            or cache_ttl not in {"5m", "30m", "1h", "12h"}
        ):
            raise ValueError("Config 'model_hub.agents.routes.cache_ttl' is invalid")
        return cls(
            hops=tuple(
                _collapse_settled_duplicates(
                    [ModelHubRouteHopConfig.from_payload(hop) for hop in hops],
                    lambda hop: (hop.source_id, hop.model_id),
                    [(hop["source_id"], hop["model_id"]) for hop in hops],
                    "Config 'model_hub.agents.routes.hops' must contain unique pairs",
                    repairing=repairing,
                )
            ),
            cache_ttl=cache_ttl,
        )

    def to_payload(self) -> dict:
        payload = {"hops": [hop.to_payload() for hop in self.hops]}
        if self.cache_ttl is not None:
            payload["cache_ttl"] = self.cache_ttl
        return payload


def normalized_model_hub_override(route: ModelHubRouteConfig | None) -> ModelHubRouteConfig | None:
    """Normalize validated intent: only a nonempty route is a manual override."""

    return route if route is not None and route.hops else None


@dataclass
class ModelHubMenuConfig:
    view: Literal["featured", "full"] = "featured"
    checked: list[str] = field(default_factory=list)

    @classmethod
    def from_payload(cls, payload: dict) -> "ModelHubMenuConfig":
        if not isinstance(payload, dict):
            raise ValueError("Config 'model_hub.agents.menu' must be an object")
        if set(payload) - {"view", "checked"}:
            raise ValueError("Config 'model_hub.agents.menu' contains unknown fields")
        view = payload.get("view")
        checked = payload.get("checked")
        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")
        if len(set(checked)) != len(checked):
            raise ValueError("Config 'model_hub.agents.menu.checked' must be unique")
        if any(_contains_model_hub_credential_material(item) for item in checked):
            raise ValueError("Config 'model_hub.agents.menu.checked' is invalid")
        return cls(view=view, checked=list(checked))

    def to_payload(self) -> dict:
        return {"view": self.view, "checked": list(self.checked)}


_BACKEND_MODEL_INPUT_MODALITIES = frozenset(
    {"text", "image", "audio", "video", "pdf"}
)
_BACKEND_MODEL_OUTPUT_MODALITIES = frozenset(
    {"text", "image", "audio", "video"}
)


@dataclass
class ModelHubBackendModelConfig:
    id: str
    origin: Literal["builtin", "provider", "models_dev", "manual"] = "manual"
    display_name: Optional[str] = None
    models_dev_id: Optional[str] = None
    context_window: Optional[int] = None
    max_output_tokens: Optional[int] = None
    input_modalities: list[str] = field(default_factory=list)
    output_modalities: list[str] = field(default_factory=list)
    supports_tools: Optional[bool] = None
    supports_reasoning: Optional[bool] = None
    reasoning_efforts: list[str] = field(default_factory=list)
    native_protocol: Optional[Literal["openai_responses", "anthropic"]] = None

    @classmethod
    def from_payload(cls, payload: object) -> "ModelHubBackendModelConfig":
        if not isinstance(payload, dict):
            raise ValueError("Config 'model_hub.agents.models' entries must be objects")
        allowed = {
            "id",
            "display_name",
            "origin",
            "models_dev_id",
            "context_window",
            "max_output_tokens",
            "input_modalities",
            "output_modalities",
            "supports_tools",
            "supports_reasoning",
            "reasoning_efforts",
            "native_protocol",
            # These are read-only API projection fields. Accepting and dropping
            # them lets a client submit the list it observed without turning
            # server-owned policy into persisted state.
            "locked",
            "routeable",
            "effort_menu",
            "fast_mode",
            "fast_mode_confirmed",
        }
        if set(payload) - allowed:
            raise ValueError("Config 'model_hub.agents.models' contains unknown fields")
        model_id = payload.get("id")
        origin = payload.get("origin", "manual")
        display_name = payload.get("display_name")
        models_dev_id = payload.get("models_dev_id")
        context_window = payload.get("context_window")
        max_output_tokens = payload.get("max_output_tokens")
        input_modalities = payload.get("input_modalities", [])
        output_modalities = payload.get("output_modalities", [])
        supports_tools = payload.get("supports_tools")
        supports_reasoning = payload.get("supports_reasoning")
        reasoning_efforts = payload.get("reasoning_efforts", [])
        native_protocol = payload.get("native_protocol")

        if (
            not isinstance(model_id, str)
            or not model_id.strip()
            or _contains_model_hub_credential_material(model_id)
        ):
            raise ValueError("Config 'model_hub.agents.models.id' is invalid")
        if origin not in {"builtin", "provider", "models_dev", "manual"}:
            raise ValueError("Config 'model_hub.agents.models.origin' is invalid")
        for name, value in (
            ("display_name", display_name),
            ("models_dev_id", models_dev_id),
        ):
            if value is not None and (
                not isinstance(value, str)
                or not value.strip()
                or _contains_model_hub_credential_material(value)
            ):
                raise ValueError(f"Config 'model_hub.agents.models.{name}' is invalid")
        for name, value in (
            ("context_window", context_window),
            ("max_output_tokens", max_output_tokens),
        ):
            if value is not None and (
                isinstance(value, bool) or not isinstance(value, int) or value <= 0
            ):
                raise ValueError(f"Config 'model_hub.agents.models.{name}' is invalid")
        for name, values, allowed_modalities in (
            (
                "input_modalities",
                input_modalities,
                _BACKEND_MODEL_INPUT_MODALITIES,
            ),
            (
                "output_modalities",
                output_modalities,
                _BACKEND_MODEL_OUTPUT_MODALITIES,
            ),
        ):
            if (
                not isinstance(values, list)
                or any(
                    not isinstance(value, str)
                    or value not in allowed_modalities
                    for value in values
                )
                or len(set(values)) != len(values)
            ):
                raise ValueError(f"Config 'model_hub.agents.models.{name}' is invalid")
        for name, value in (
            ("supports_tools", supports_tools),
            ("supports_reasoning", supports_reasoning),
        ):
            if value is not None and not isinstance(value, bool):
                raise ValueError(f"Config 'model_hub.agents.models.{name}' is invalid")
        if (
            not isinstance(reasoning_efforts, list)
            or any(
                not isinstance(value, str)
                or not value.strip()
                or len(value) > 64
                or _contains_model_hub_credential_material(value)
                for value in reasoning_efforts
            )
            or len(set(reasoning_efforts)) != len(reasoning_efforts)
        ):
            raise ValueError(
                "Config 'model_hub.agents.models.reasoning_efforts' is invalid"
            )
        if native_protocol is not None and native_protocol not in {
            "openai_responses",
            "anthropic",
        }:
            raise ValueError(
                "Config 'model_hub.agents.models.native_protocol' is invalid"
            )
        return cls(
            id=model_id.strip(),
            origin=origin,
            display_name=display_name.strip() if isinstance(display_name, str) else None,
            models_dev_id=models_dev_id.strip() if isinstance(models_dev_id, str) else None,
            context_window=context_window,
            max_output_tokens=max_output_tokens,
            input_modalities=list(input_modalities),
            output_modalities=list(output_modalities),
            supports_tools=supports_tools,
            supports_reasoning=supports_reasoning,
            reasoning_efforts=list(reasoning_efforts),
            native_protocol=native_protocol,
        )

    def to_payload(self) -> dict:
        payload = {
            "id": self.id,
            "display_name": self.display_name,
            "origin": self.origin,
            "models_dev_id": self.models_dev_id,
            "context_window": self.context_window,
            "max_output_tokens": self.max_output_tokens,
            "input_modalities": list(self.input_modalities),
            "output_modalities": list(self.output_modalities),
            "supports_tools": self.supports_tools,
            "supports_reasoning": self.supports_reasoning,
            "reasoning_efforts": list(self.reasoning_efforts),
        }
        if self.native_protocol is not None:
            payload["native_protocol"] = self.native_protocol
        return payload


def normalize_storable_backend_model_text(
    value: object,
    *,
    field_name: Literal["display_name", "reasoning_efforts"],
) -> Optional[str]:
    """Normalize one proposed metadata value through the persisted model contract."""

    if not isinstance(value, str):
        return None
    normalized = value.strip()
    candidate = {
        "id": "metadata-proposal",
        field_name: (
            normalized if field_name == "display_name" else [normalized]
        ),
    }
    try:
        model = ModelHubBackendModelConfig.from_payload(candidate)
    except (TypeError, ValueError):
        return None
    if field_name == "display_name":
        return model.display_name
    return model.reasoning_efforts[0]


def _default_backend_models(backend: str) -> list[ModelHubBackendModelConfig]:
    if backend not in {"claude", "codex"}:
        return []
    from vibe.backend_model_catalog import backend_model_entries, load_bundled_catalog

    return [
        ModelHubBackendModelConfig(
            id=entry["id"],
            origin="builtin",
            display_name=entry.get("label"),
            reasoning_efforts=list(entry.get("reasoning_efforts") or ()),
        )
        for entry in backend_model_entries(backend, load_bundled_catalog())
    ]


@dataclass
class ModelHubAgentSourcesConfig:
    order: list[str] = field(default_factory=list)

    @classmethod
    def from_payload(cls, payload: dict) -> "ModelHubAgentSourcesConfig":
        if not isinstance(payload, dict):
            raise ValueError("Config 'model_hub.agents.sources' must be an object")
        if set(payload) != {"order"}:
            raise ValueError("Config 'model_hub.agents.sources' must contain only order")
        order = payload.get("order")
        if not isinstance(order, list) or not all(isinstance(item, str) for item in order):
            raise ValueError("Config 'model_hub.agents.sources.order' must be an array of strings")
        if len(set(order)) != len(order):
            raise ValueError("Config 'model_hub.agents.sources.order' must be unique")
        return cls(order=list(order))

    def to_payload(self) -> dict:
        return {"order": list(self.order)}


@dataclass
class ModelHubAgentSupplyConfig:
    backend: AgentBackend
    mode: Literal["hub", "direct"]
    menu_kind: Literal["fixed", "open"]
    sources: ModelHubAgentSourcesConfig = field(default_factory=ModelHubAgentSourcesConfig)
    routes: dict[str, ModelHubRouteConfig] = field(default_factory=dict)
    menu: Optional[ModelHubMenuConfig] = None
    models: list[ModelHubBackendModelConfig] = field(default_factory=list)
    removed_model_ids: list[str] = field(default_factory=list)

    @classmethod
    def default(cls, backend: str, *, mode: Literal["hub", "direct"]) -> "ModelHubAgentSupplyConfig":
        if backend == "vibey":
            return cls(backend="vibey", mode="hub", menu_kind="fixed")
        if backend == "opencode":
            return cls(
                backend="opencode",
                mode=mode,
                menu_kind="open",
                menu=ModelHubMenuConfig(),
            )
        if backend not in {"claude", "codex"}:
            raise ValueError(f"Unsupported Model Hub backend: {backend}")
        return cls(
            backend=backend,
            mode=mode,
            menu_kind="fixed",
            models=_default_backend_models(backend),
        )

    @classmethod
    def from_payload(
        cls,
        payload: dict,
        *,
        expected_backend: Optional[str] = None,
        repairing: bool = False,
    ) -> "ModelHubAgentSupplyConfig":
        if not isinstance(payload, dict):
            raise ValueError("Config 'model_hub.agents' entries must be objects")
        if set(payload) - {
            "backend",
            "mode",
            "menu_kind",
            "sources",
            "routes",
            "menu",
            "models",
            "removed_model_ids",
        }:
            raise ValueError("Config 'model_hub.agents' contains unknown fields")
        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 not isinstance(backend, str) or backend not in MODEL_HUB_BACKENDS or (
            expected_backend is not None and backend != expected_backend
        ):
            raise ValueError("Config 'model_hub.agents.backend' is invalid")
        if not isinstance(mode, str) or mode not in {"hub", "direct"}:
            raise ValueError("Config 'model_hub.agents.mode' is invalid")
        if backend == "vibey" and mode != "hub":
            raise ValueError("Config 'model_hub.agents.vibey.mode' must be hub")
        expected_menu_kind = "open" if backend == "opencode" else "fixed"
        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):
            raise ValueError("Config 'model_hub.agents.routes' must be an object")
        if any(not isinstance(model_id, str) or not model_id for model_id in routes_payload):
            raise ValueError("Config 'model_hub.agents.routes' keys must be non-empty strings")
        menu_payload = payload.get("menu")
        sources_payload = payload.get("sources")
        if backend == "opencode" and menu_payload is None:
            raise ValueError("Config 'model_hub.agents.menu' is required for opencode")
        if backend != "opencode" and menu_payload is not None:
            raise ValueError("Config 'model_hub.agents.menu' is only valid for opencode")
        routes = {
            model_id: ModelHubRouteConfig.from_payload(route, repairing=repairing)
            for model_id, route in routes_payload.items()
        }
        menu = ModelHubMenuConfig.from_payload(menu_payload) if menu_payload is not None else None
        models_payload = payload.get("models")
        removed_model_ids = payload.get("removed_model_ids", [])
        if (
            not isinstance(removed_model_ids, list)
            or any(
                not isinstance(model_id, str)
                or not model_id
                or _contains_model_hub_credential_material(model_id)
                for model_id in removed_model_ids
            )
            or len(set(removed_model_ids)) != len(removed_model_ids)
        ):
            raise ValueError(
                "Config 'model_hub.agents.removed_model_ids' must be a unique array of strings"
            )
        if models_payload is None:
            if backend == "opencode":
                raise ValueError("Config 'model_hub.agents.models' is required for opencode")
            else:
                models = _default_backend_models(backend)
                known = {model.id for model in models}
                models.extend(
                    ModelHubBackendModelConfig(id=model_id, origin="manual")
                    for model_id in routes
                    if model_id not in known
                )
        else:
            if not isinstance(models_payload, list):
                raise ValueError("Config 'model_hub.agents.models' must be an array")
            models = [
                ModelHubBackendModelConfig.from_payload(item)
                for item in models_payload
            ]
        if len({model.id for model in models}) != len(models):
            raise ValueError("Config 'model_hub.agents.models' ids must be unique")
        if any(_contains_model_hub_credential_material(model_id) for model_id in routes):
            raise ValueError("Config 'model_hub.agents.routes' contains an invalid model id")
        if backend == "opencode":
            from core.handlers.model_hub.identifiers import normalized_model_id

            for identifier in (*routes, *(model.id for model in models)):
                if not identifier.strip() or normalized_model_id(identifier) != identifier:
                    raise ValueError("Config 'model_hub.agents.models.id' is invalid")
            if any(model.native_protocol is None for model in models):
                raise ValueError(
                    "Config 'model_hub.agents.models.native_protocol' is required for opencode"
                )
            menu = ModelHubMenuConfig(
                view=menu.view if menu else "featured",
                checked=[model.id for model in models],
            )
        elif any(
            isinstance(item, dict) and "native_protocol" in item
            for item in models_payload or ()
        ):
            raise ValueError(
                "Config 'model_hub.agents.models.native_protocol' is only valid for opencode"
            )
        # Validate original keys before omitting empties. Legacy fixed-menu
        # readers above may derive catalog identities from those same keys.
        menu_ids = {model.id for model in models}
        extra_route = next((model_id for model_id in routes if model_id not in menu_ids), None)
        # OpenCode retains dormant routes when a checked model is hidden.
        if extra_route is not None and backend != "opencode":
            raise ValueError(
                f"Config 'model_hub.agents.{backend}.routes' contains non-menu model '{extra_route}'"
            )
        return cls(
            backend=backend,
            mode=mode,
            menu_kind=menu_kind,
            sources=(
                ModelHubAgentSourcesConfig.from_payload(sources_payload)
                if sources_payload is not None
                else ModelHubAgentSourcesConfig()
            ),
            routes={model_id: route for model_id, route in routes.items() if normalized_model_hub_override(route) is not None},
            menu=menu,
            models=models,
            removed_model_ids=list(removed_model_ids),
        )

    def to_payload(self) -> dict:
        payload = {
            "backend": self.backend,
            "mode": self.mode,
            "menu_kind": self.menu_kind,
            "sources": self.sources.to_payload(),
            "routes": {
                model_id: route.to_payload()
                for model_id, route in self.routes.items()
                if normalized_model_hub_override(route) is not None
            },
            "menu": self.menu.to_payload() if self.menu else None,
        }
        payload["models"] = [model.to_payload() for model in self.models]
        payload["removed_model_ids"] = list(self.removed_model_ids)
        return payload

    def to_agent_supply_payload(self) -> dict:
        payload = self.to_payload()
        payload.pop("models")
        payload.pop("removed_model_ids")
        return payload


# Model Hub's hosted-tool catalog (vibey-hosted-tools.md §2): two search tools a hop may run natively or
# through the executor, and the direct image tool.
MODEL_HUB_SEARCH_TOOLS: tuple[str, ...] = ("web_search", "x_search")
MODEL_HUB_HOSTED_TOOLS: tuple[str, ...] = (*MODEL_HUB_SEARCH_TOOLS, "image_generate", "web_fetch")
# WF-3 enables read, declaration and producer together; coordinated release decision: docs/plans/web-fetch.md §8.
WEB_FETCH_ACTIVE = True


def _drop_vibey_client_presets(agent: "ModelHubAgentSupplyConfig") -> None:
    """Keep client presets (Codex ``ultra``) out of Vibey's model rows.

    A preset is a name another client maps before sending, never a wire tier,
    and Vibey is not that client. 3.2.0 saved Vibey rows carrying one (#2539),
    so every read drops them here, the single owner of those rows: the catalog
    payload, the picker, the launch and the API then agree, and the next save
    writes the clean list. No I/O: the preset index is read once per process.
    """

    from vibe.backend_model_catalog import without_client_presets

    agent.models = [
        replace(model, reasoning_efforts=without_client_presets((model.id,), model.reasoning_efforts))
        if model.reasoning_efforts
        else model
        for model in agent.models
    ]


def is_model_hub_source_id(value: object) -> bool:
    """A Source id as Model Hub mints it, whether or not that Source exists now."""

    return isinstance(value, str) and re.fullmatch(r"src_[a-z0-9]{8,}", value) is not None


def is_model_hub_model_id(value: object) -> bool:
    """A model id already in its canonical spelling, by the one admission rule (``canonical_model_id``)."""

    from core.handlers.model_hub.identifiers import canonical_model_id

    return isinstance(value, str) and canonical_model_id(value) == value


def model_hub_executor_order(value: object, *, tool: str) -> tuple[str, ...]:
    """A saved executor order: one or more distinct Source ids (automatic is its absence, never an empty list).

    The one grammar the config loader and the API share.
    """

    if (
        not isinstance(value, list)
        or not value
        or not all(is_model_hub_source_id(item) for item in value)
        or len(set(value)) != len(value)
    ):
        raise ValueError(f"Config 'model_hub.hosted_tools.{tool}.executor_order' must be distinct Source ids")
    return tuple(value)


def model_hub_service_order(value: object, *, tool: str) -> tuple[str, ...]:
    """A server-owned automatic order for tool-only search Sources."""

    if (
        not isinstance(value, list)
        or not all(is_model_hub_source_id(item) for item in value)
        or len(set(value)) != len(value)
    ):
        raise ValueError(f"Config 'model_hub.hosted_tools.{tool}.service_order' must be distinct Source ids")
    return tuple(value)


@dataclass(frozen=True)
class ModelHubImageModelChoice:
    """The image model a user chose as ``image_generate``'s default."""

    source_id: str
    model_id: str

    @classmethod
    def from_payload(cls, payload: object, *, tool: str) -> "ModelHubImageModelChoice":
        if (
            not isinstance(payload, dict)
            or set(payload) != {"source_id", "model_id"}
            or not is_model_hub_source_id(payload["source_id"])
            or not is_model_hub_model_id(payload["model_id"])
        ):
            raise ValueError(f"Config 'model_hub.hosted_tools.{tool}.default_model' must name a source_id and model_id")
        return cls(source_id=payload["source_id"], model_id=payload["model_id"])

    def to_payload(self) -> dict:
        return {"source_id": self.source_id, "model_id": self.model_id}


# Built-in keyless Exa is active by default. The reader and producer must use this
# one predicate together so the public Source cannot be read without its chain.
KEYLESS_EXA_ACTIVE = True
KEYLESS_EXA_SOURCE_ID = "src_exakeyless"
KEYLESS_EXA_VENDOR_ID = "exa-mcp"
KEYLESS_EXA_SERVICE_ID = "exa/mcp"
KEYLESS_EXA_DISPLAY_NAME = "Exa (free)"


def is_keyless_exa_source(source: "ModelHubSourceConfig") -> bool:
    """Whether ``source`` is the credential-free synthetic Exa identity."""

    return (
        source.id == KEYLESS_EXA_SOURCE_ID
        and source.vendor == KEYLESS_EXA_VENDOR_ID
        and source.protocol == "search"
        and source.supply_channel == "hub"
        and source.credential_ref is None
        and source.base_url is None
    )


def model_hub_keyless_exa_source() -> "ModelHubSourceConfig":
    """The in-memory Source shape used by readers; it is never persisted."""

    return model_hub_builtin_source(KEYLESS_EXA_SOURCE_ID)


def model_hub_builtin_source(source_id: str) -> "ModelHubSourceConfig | None":
    """Credential-free catalog identity, never a persisted Source or model supplier."""
    from vibe.model_hub_runtime.fetch_catalog import builtin_tool_identity

    entry = builtin_tool_identity(source_id)
    if entry is None:
        return None
    return ModelHubSourceConfig(
        id=entry["source_id"], kind="api_key", vendor=entry["vendor"], display_name=entry["label"],
        protocol="search", supply_channel="hub", billing="metered",
        state=ModelHubSourceStateConfig(status="active"), models=[],
    )


def model_hub_builtin_sources() -> list["ModelHubSourceConfig"]:
    from vibe.model_hub_runtime.fetch_catalog import builtin_tool_identities

    return [model_hub_builtin_source(entry["source_id"]) for entry in builtin_tool_identities()]


def is_keyless_exa_source_id(value: object) -> bool:
    return value == KEYLESS_EXA_SOURCE_ID




def model_hub_search_service(source: ModelHubSourceConfig) -> Optional[dict[str, Any]]:
    """Catalog capability, including the credential-free built-in Exa identity."""

    from vibe.model_hub_runtime.api_key_vendors import search_service

    if is_keyless_exa_source(source):
        return search_service(KEYLESS_EXA_VENDOR_ID, "search", None)
    if source.kind != "api_key" or source.supply_channel != "hub" or not source.credential_ref:
        return None
    return search_service(source.vendor, source.protocol, source.base_url)


@dataclass(frozen=True)
class ModelHubSearchServiceSettings:
    """Partial saved overrides, not resolved defaults (web-search-services.md §3.2)."""

    results: Optional[int] = None
    enabled: Optional[bool] = None

    @classmethod
    def from_payload(cls, payload: object) -> "ModelHubSearchServiceSettings":
        if not isinstance(payload, dict):
            raise ValueError("Config 'model_hub.hosted_tools.web_search.services' entries must be objects")
        unknown = set(payload) - {"results", "enabled"}
        if unknown:
            logger.warning("Config 'model_hub.hosted_tools.web_search.services' ignores unknown fields %s", sorted(unknown))
        if "results" in payload and (type(payload["results"]) is not int or payload["results"] < 1):
            raise ValueError("Config search service results must be a positive integer")
        if "enabled" in payload and not isinstance(payload["enabled"], bool):
            raise ValueError("Config search service enabled must be a boolean")
        return cls(**{key: payload[key] for key in ("results", "enabled") if key in payload})

    def clamped(self, service: Mapping[str, Any]) -> "ModelHubSearchServiceSettings":
        """Read an obsolete override safely; disk is unchanged until an authorized write."""

        return replace(
            self,
            results=min(self.results, service["limits"]["results_max"]) if self.results is not None else None,
        )

    def effective(self, service: Mapping[str, Any]) -> dict[str, Any]:
        saved = self.clamped(service)
        return {
            "results": saved.results if saved.results is not None else min(5, service["limits"]["results_max"]),
            "enabled": saved.enabled if saved.enabled is not None else bool(service["tool_only"] or service.get("auto_enroll")),
        }

    def to_payload(self) -> dict[str, Any]:
        return {key: value for key in ("results", "enabled") if (value := getattr(self, key)) is not None}


def _search_service_settings_from_payload(
    payload: object, sources: Optional[list[ModelHubSourceConfig]]
) -> dict[str, ModelHubSearchServiceSettings]:
    if not isinstance(payload, dict) or any(not is_model_hub_source_id(key) for key in payload):
        raise ValueError("Config 'model_hub.hosted_tools.web_search.services' must map Source ids to settings")
    live = {source.id: source for source in sources} if sources is not None else None
    settings = {}
    for source_id, raw in payload.items():
        # Removed Sources have no settings. Keep an extant but retargeted/retired Source's choices:
        # forgetting an opt-out would silently re-enrol it if its search capability returns later.
        if live is not None and source_id not in live and not is_keyless_exa_source_id(source_id):
            continue
        service = (
            model_hub_search_service(live[source_id])
            if live is not None and source_id in live
            else model_hub_search_service(model_hub_keyless_exa_source())
            if is_keyless_exa_source_id(source_id)
            else None
        )
        saved = ModelHubSearchServiceSettings.from_payload(raw)
        # Only the in-memory parse is normalized. V2Config.load never writes it back; an authorized
        # writer later serializes these clamped overrides without freezing any absent default.
        settings[source_id] = saved.clamped(service) if service is not None else saved
    return settings


@dataclass(frozen=True)
class ModelHubExecutorSettings:
    """A model executor Source's saved web-search choice (``vibey-hosted-tools.md`` §6): on unless turned off."""

    enabled: bool = True

    @classmethod
    def from_payload(cls, payload: object) -> "ModelHubExecutorSettings":
        if not isinstance(payload, dict):
            raise ValueError("Config 'model_hub.hosted_tools.web_search.executors' entries must be objects")
        if set(payload) - {"enabled"}:
            logger.warning("Config 'model_hub.hosted_tools.web_search.executors' ignores unknown fields")
        enabled = payload.get("enabled", True)
        if not isinstance(enabled, bool):
            raise ValueError("Config search executor enabled must be a boolean")
        return cls(enabled=enabled)

    def to_payload(self) -> dict[str, Any]:
        return {"enabled": self.enabled}


def _executor_settings_from_payload(
    payload: object, sources: Optional[list[ModelHubSourceConfig]]
) -> dict[str, ModelHubExecutorSettings]:
    if not isinstance(payload, dict) or any(not is_model_hub_source_id(key) for key in payload):
        raise ValueError("Config 'model_hub.hosted_tools.web_search.executors' must map Source ids to settings")
    live = {source.id for source in sources} if sources is not None else None
    # Removed Sources have no settings; an extant Source keeps its opt-out while it lists no executor model, so the
    # choice holds if it lists one again. Only an opt-out is a choice: on is the default.
    return {
        source_id: saved
        for source_id, raw in payload.items()
        if (live is None or source_id in live) and not (saved := ModelHubExecutorSettings.from_payload(raw)).enabled
    }


@dataclass(frozen=True)
class ModelHubFetchServiceSettings:
    """Fetch-only partial consent; search settings never authorize a page read."""

    enabled: Optional[bool] = None

    @classmethod
    def from_payload(cls, payload: object) -> "ModelHubFetchServiceSettings":
        if not isinstance(payload, dict):
            raise ValueError("Config web_fetch services entries must be objects")
        if set(payload) - {"enabled"}:
            logger.warning("Config web_fetch services ignores unknown fields")
        if "enabled" in payload and not isinstance(payload["enabled"], bool):
            raise ValueError("Config web_fetch service enabled must be a boolean")
        return cls(enabled=payload.get("enabled"))

    def effective(self, service: Mapping[str, Any]) -> dict[str, bool]:
        return {"enabled": self.enabled if self.enabled is not None else bool(service.get("auto_enroll"))}

    def to_payload(self) -> dict[str, bool]:
        return {"enabled": self.enabled} if self.enabled is not None else {}


def _fetch_service_settings_from_payload(payload: object, sources: Optional[list[ModelHubSourceConfig]]) -> dict:
    if not isinstance(payload, dict) or any(not is_model_hub_source_id(key) for key in payload):
        raise ValueError("Config web_fetch services must map Source ids to settings")
    live = {source.id for source in sources} if sources is not None else None
    return {
        sid: ModelHubFetchServiceSettings.from_payload(raw) for sid, raw in payload.items()
        if live is None or sid in live or model_hub_builtin_source(sid) is not None
    }


def _executor_order_kinds_from_payload(
    payload: object, order: Optional[tuple[str, ...]], sources: Optional[list[ModelHubSourceConfig]],
    *, tool: str = "web_search",
) -> Optional[dict[str, str]]:
    # This derived snapshot affects placement, not consent. Damage follows the released missing-map rule;
    # discarding the whole tool entry would erase service opt-outs on the next unrelated config write.
    if isinstance(payload, dict):
        live = {source.id for source in sources} if sources is not None else None
        named = {key: value for key, value in payload.items()
                 if key in (order or ()) and (live is None or key in live or (
                     model_hub_builtin_source(key) is not None if tool == "web_fetch" else is_keyless_exa_source_id(key)
                 ))}
        allowed = {"service", "local"} if tool == "web_fetch" else {"service", "model"}
        if all(isinstance(value, str) and value in allowed for value in named.values()):
            return named
    logger.warning("Config 'model_hub.hosted_tools.%s.executor_order_kinds': ignoring damaged role map", tool)
    return None


@dataclass(frozen=True)
class ModelHubHostedToolConfig:
    """One hosted tool's user settings (``vibey-hosted-tools.md`` §3.3).

    ``enabled`` defaults to on. ``executor_order`` (search tools) is the Source order the user wants executors
    tried in, None for automatic; ``service_order`` (``web_search``) is the server-owned automatic order of
    tool-only search Sources; ``default_image`` (``image_generate``, persisted as ``default_model``) is the
    chosen default image model, None for the catalog default. Both are saved values, never resolved ones.
    """

    enabled: bool = True
    executor_order: Optional[tuple[str, ...]] = None
    service_order: Optional[tuple[str, ...]] = None
    default_image: Optional[ModelHubImageModelChoice] = None
    prefer_native: bool = True
    services: Mapping[str, ModelHubSearchServiceSettings | ModelHubFetchServiceSettings] = field(default_factory=dict)
    executor_order_kinds: Optional[Mapping[str, str]] = None
    # ``web_search`` only: model executor Sources the user turned off (§6), by Source id.
    executors: Mapping[str, ModelHubExecutorSettings] = field(default_factory=dict)

    @classmethod
    def from_payload(
        cls, payload: object, *, tool: str, sources: Optional[list[ModelHubSourceConfig]] = None
    ) -> "ModelHubHostedToolConfig":
        """Read one entry; fields it does not know are ignored with a warning, the ones it knows are kept."""

        if not isinstance(payload, dict):
            raise ValueError(f"Config 'model_hub.hosted_tools.{tool}' must be an object")
        known = {"enabled"}
        if tool == "web_fetch":
            known |= {"executor_order", "services", "executor_order_kinds"}
        elif tool == "web_search":
            known |= {"executor_order", "service_order", "prefer_native", "services", "executor_order_kinds", "executors"}
        elif tool in MODEL_HUB_SEARCH_TOOLS:
            known.add("executor_order")
        else:
            known.add("default_model")
        unknown = set(payload) - known
        if unknown:
            logger.warning("Config 'model_hub.hosted_tools.%s' ignores unknown fields %s", tool, sorted(unknown))
        enabled = payload.get("enabled", True)
        if not isinstance(enabled, bool):
            raise ValueError(f"Config 'model_hub.hosted_tools.{tool}.enabled' must be a boolean")
        prefer_native = payload.get("prefer_native", True) if tool == "web_search" else True
        if not isinstance(prefer_native, bool):
            raise ValueError("Config 'model_hub.hosted_tools.web_search.prefer_native' must be a boolean")
        # Only the fields this tool knows are read; another tool's field was ignored above. A field is decided by its
        # presence: the writer omits an unset one, so a present null is damage and goes through the grammar.
        has_order = "executor_order" in known and "executor_order" in payload
        has_service_order = "service_order" in known and "service_order" in payload
        has_default = "default_model" in known and "default_model" in payload
        order = model_hub_executor_order(payload["executor_order"], tool=tool) if has_order else None
        return cls(
            enabled=enabled,
            executor_order=order,
            service_order=model_hub_service_order(payload["service_order"], tool=tool) if has_service_order else None,
            prefer_native=prefer_native,
            services=(
                _fetch_service_settings_from_payload(payload["services"], sources)
                if tool == "web_fetch" and "services" in payload else
                _search_service_settings_from_payload(payload["services"], sources)
                if tool == "web_search" and "services" in payload else {}
            ),
            executor_order_kinds=(
                _executor_order_kinds_from_payload(payload["executor_order_kinds"], order, sources, tool=tool)
                if tool in {"web_search", "web_fetch"} and "executor_order_kinds" in payload else None
            ),
            executors=(
                _executor_settings_from_payload(payload["executors"], sources)
                if tool == "web_search" and "executors" in payload else {}
            ),
            default_image=(
                ModelHubImageModelChoice.from_payload(payload["default_model"], tool=tool) if has_default else None
            ),
        )

    def to_payload(self) -> dict:
        out: dict[str, Any] = {"enabled": self.enabled}
        if self.executor_order is not None:
            out["executor_order"] = list(self.executor_order)
        if self.service_order is not None:
            out["service_order"] = list(self.service_order)
        if self.default_image is not None:
            out["default_model"] = self.default_image.to_payload()
        if not self.prefer_native:
            out["prefer_native"] = False
        if self.services:
            out["services"] = {source_id: saved.to_payload() for source_id, saved in self.services.items()}
        if self.executor_order_kinds is not None:
            out["executor_order_kinds"] = {
                source_id: kind for source_id, kind in self.executor_order_kinds.items()
                if source_id in (self.executor_order or ())
            }
        if self.executors:
            out["executors"] = {source_id: saved.to_payload() for source_id, saved in self.executors.items()}
        return out


def _hosted_tools_from_payload(
    section: Mapping[str, Any], sources: list[ModelHubSourceConfig]
) -> dict[str, ModelHubHostedToolConfig]:
    """Read ``model_hub.hosted_tools`` as an optional feature that degrades on its own.

    Absent means every tool takes its defaults (on). An unknown tool key, or an unknown field inside an entry, is
    ignored with a warning, and the fields the loader knows are kept, so a user's opt-out survives. A broken section
    or entry turns its tools off, with a warning: hosted tools reach third parties and cost money, so damage never
    turns one on. Sources and Agents still load.
    """

    if "hosted_tools" not in section:
        return {}
    payload = section["hosted_tools"]
    # Present but not an object, ``null`` included, is damage, never absence.
    if not isinstance(payload, dict):
        logger.warning("Config 'model_hub.hosted_tools' is not an object; hosted tools are off")
        return {tool: ModelHubHostedToolConfig(enabled=False) for tool in MODEL_HUB_HOSTED_TOOLS}
    tools: dict[str, ModelHubHostedToolConfig] = {}
    for tool, raw in payload.items():
        if tool not in MODEL_HUB_HOSTED_TOOLS:
            logger.warning("Config 'model_hub.hosted_tools' ignores an unknown tool %r", tool)
            continue
        try:
            tools[tool] = ModelHubHostedToolConfig.from_payload(raw, tool=tool, sources=sources)
        except ValueError as exc:
            logger.warning("%s; hosted tool %r is off", exc, tool)
            tools[tool] = ModelHubHostedToolConfig(enabled=False)
    return tools


def hosted_tool_setting(config: "ModelHubConfig", tool: str) -> ModelHubHostedToolConfig:
    """One tool's settings, its defaults when the config says nothing."""

    return config.hosted_tools.get(tool) or ModelHubHostedToolConfig()


@dataclass
class ModelHubConfig:
    # New installations enable the runtime. Disk loading promotes pre-marker
    # installations once; a later explicit stop remains a deliberate opt-out.
    enabled: bool = True
    sources: list[ModelHubSourceConfig] = field(default_factory=list)
    agents: dict[str, ModelHubAgentSupplyConfig] = field(
        default_factory=lambda: {
            backend: ModelHubAgentSupplyConfig.default(backend, mode="hub")
            for backend in MODEL_HUB_BACKENDS
            if backend != "vibey"
        }
    )
    # Fresh configs and explicit Start/Stop consume the default. Disk observers
    # retain a pending false marker until lock-owning startup commits promotion;
    # an unrelated save must not acknowledge an upgrade it did not perform.
    runtime_default_applied: bool = True
    # Absent on every released config: absence means every hosted tool takes its defaults (on).
    hosted_tools: dict[str, ModelHubHostedToolConfig] = field(default_factory=dict)
    # Not persisted, like ``V2Config.load_warnings``. True while the Vibey
    # entry was never supplied: a fresh install, or a file written before
    # Vibey existed. The empty entry standing in waits for its starting
    # supply (see ``ModelHubService._seed_vibey``), and until that seed, or any
    # other edit, touches it, ``to_payload`` keeps it absent, so an unrelated
    # write cannot record an empty supply as the user's choice.
    vibey_supply_pending: ClassVar[bool] = False

    def __post_init__(self) -> None:
        # Existing in-process config producers may still supply the released
        # three-backend shape, just like older on-disk configurations.
        if "vibey" not in self.agents:
            self.agents["vibey"] = ModelHubAgentSupplyConfig.default("vibey", mode="hub")
            self.vibey_supply_pending = True

    @staticmethod
    def source_eligible_for_backend(
        source: ModelHubSourceConfig,
        backend: str,
    ) -> bool:
        if backend not in MODEL_HUB_BACKENDS or source.protocol == "search":
            return False
        if source.supply_channel == "hub":
            return True
        if source.kind == "api_key":
            return False
        expected_backend = {"anthropic": "claude", "openai": "codex"}.get(source.vendor)
        return expected_backend == backend

    def recommended_source_order(self, backend: str) -> list[str]:
        def sort_key(source: ModelHubSourceConfig) -> tuple[object, ...]:
            if source.kind == "subscription":
                return (
                    0,
                    0 if source.supply_channel == "native_cli" else 1,
                    source.id,
                )
            created_at = datetime.fromisoformat(source.created_at.replace("Z", "+00:00"))
            return (1, created_at.timestamp(), source.id)

        return [
            source.id
            for source in sorted(self.sources, key=sort_key)
            if self.source_eligible_for_backend(source, backend)
        ]

    def effective_source_order(self, backend: str) -> list[str]:
        return list(self.agents[backend].sources.order)

    @classmethod
    def from_payload(cls, payload: dict, *, repairing: bool = False) -> "ModelHubConfig":
        if not isinstance(payload, dict):
            raise ValueError("Config 'model_hub' must be an object")
        if set(payload) - {"enabled", "sources", "agents", "runtime_default_applied", "hosted_tools"}:
            raise ValueError("Config 'model_hub' contains unknown fields")
        enabled = payload.get("enabled", True)
        if not isinstance(enabled, bool):
            raise ValueError("Config 'model_hub.enabled' must be a boolean")
        runtime_default_applied = payload.get("runtime_default_applied", True)
        if not isinstance(runtime_default_applied, bool):
            raise ValueError("Config 'model_hub.runtime_default_applied' must be a boolean")
        sources_payload = payload.get("sources") or []
        agents_payload = payload.get("agents") or {}
        if not isinstance(sources_payload, list):
            raise ValueError("Config 'model_hub.sources' must be an array")
        if not isinstance(agents_payload, dict):
            raise ValueError("Config 'model_hub.agents' must be an object")
        if set(agents_payload) - set(MODEL_HUB_BACKENDS):
            raise ValueError("Config 'model_hub.agents' contains unknown backends")
        sources = [
            ModelHubSourceConfig.from_payload(source, repairing=repairing)
            for source in sources_payload
        ]
        source_ids = [source.id for source in sources]
        if len(set(source_ids)) != len(source_ids):
            raise ValueError("Config 'model_hub.sources' contains duplicate ids")
        source_nonces = [
            source.client_nonce
            for source in sources
            if source.client_nonce is not None
        ]
        if len(set(source_nonces)) != len(source_nonces):
            raise ValueError("Config 'model_hub.sources' contains duplicate client nonces")
        for backend in MODEL_HUB_BACKENDS:
            native_sources = [
                source
                for source in sources
                if source.supply_channel == "native_cli"
                and cls.source_eligible_for_backend(source, backend)
            ]
            if len(native_sources) > 1:
                raise ValueError(
                    f"Config 'model_hub.sources' contains multiple native sources for '{backend}'"
                )
        agents = {}
        for backend in MODEL_HUB_BACKENDS:
            if backend == "vibey" and backend not in agents_payload:
                # Supplied by ``__post_init__``, which marks it pending.
                continue
            if backend not in agents_payload:
                # An omitted legacy backend is not consent to change its
                # working authentication. Fresh installs use the dataclass
                # defaults; the migration transaction adopts selected backends.
                raw_agent = ModelHubAgentSupplyConfig.default(backend, mode="direct").to_payload()
            else:
                raw_agent = agents_payload[backend]
                if not isinstance(raw_agent, dict):
                    raise ValueError(f"Config 'model_hub.agents.{backend}' must be an object")
                if "routes" not in raw_agent:
                    raise ValueError(f"Config 'model_hub.agents.{backend}.routes' is required")
            agents[backend] = ModelHubAgentSupplyConfig.from_payload(
                raw_agent,
                expected_backend=backend,
                repairing=repairing,
            )
        config = cls(
            enabled=enabled,
            sources=sources,
            agents=agents,
            runtime_default_applied=runtime_default_applied,
            hosted_tools=_hosted_tools_from_payload(payload, sources),
        )
        _drop_vibey_client_presets(config.agents["vibey"])
        agents = config.agents
        for backend in MODEL_HUB_BACKENDS:
            configured_sources = agents[backend].sources
            invalid_id = next(
                (
                    source_id
                    for source_id in configured_sources.order
                    if source_id not in source_ids
                    or not config.source_eligible_for_backend(
                        next(source for source in sources if source.id == source_id),
                        backend,
                    )
                ),
                None,
            )
            if invalid_id is not None:
                raise ValueError(
                    f"Config 'model_hub.agents.{backend}.sources.order' contains "
                    f"ineligible or missing source '{invalid_id}'"
                )
            for model_id, route in agents[backend].routes.items():
                for hop in route.hops:
                    source = next((item for item in sources if item.id == hop.source_id), None)
                    if source is None:
                        raise ValueError(
                            f"Config 'model_hub.agents.{backend}.routes.{model_id}' references missing source '{hop.source_id}'"
                        )
                    if not config.source_eligible_for_backend(source, backend):
                        raise ValueError(
                            f"Config 'model_hub.agents.{backend}.routes.{model_id}' references ineligible source '{hop.source_id}'"
                        )
        return config

    def to_payload(self) -> dict:
        unseeded = self.vibey_supply_pending and self.agents["vibey"] == ModelHubAgentSupplyConfig.default(
            "vibey", mode="hub"
        )
        payload = {
            "enabled": self.enabled,
            "runtime_default_applied": self.runtime_default_applied,
            "sources": [source.to_payload() for source in self.sources],
            "agents": {
                backend: self.agents[backend].to_payload()
                for backend in MODEL_HUB_BACKENDS
                if not (backend == "vibey" and unseeded)
            },
        }
        if self.hosted_tools:
            payload["hosted_tools"] = {
                tool: self.hosted_tools[tool].to_payload()
                for tool in MODEL_HUB_HOSTED_TOOLS
                if tool in self.hosted_tools
            }
        return payload


@dataclass
class UiConfig:
    setup_host: str = "127.0.0.1"
    setup_port: int = 5123
    open_browser: bool = True
    chat_message_font_size: int = DEFAULT_CHAT_MESSAGE_FONT_SIZE_PX
    # When true, the Web Chat renders each agent turn's intermediate activity
    # (interim ``assistant`` messages + ``tool_call`` summaries) as a collapsible
    # group, and the message mirror streams those rows live. Default off: a strict
    # no-op — the live stream and transcript stay exactly as they are today.
    show_agent_activity: bool = False
    # When true (default), the Activity panel renders tool-call rows; when false,
    # only assistant narration rows show. Pure display filter — step counts,
    # durations, and data collection are unaffected. Independent of
    # ``show_agent_activity`` (which gates the whole panel); this only filters rows
    # within it. Default on so the panel keeps today's full detail unless hidden.
    show_tool_calls: bool = True
    trusted_public_origins: List[str] = field(default_factory=list)
    # Display name appended to the browser tab title ("Avibe - <name>"). When
    # blank the UI falls back to the read-only ``default_instance_name`` field
    # in the /api/config payload (remote-access tunnel name when available,
    # otherwise the machine's system hostname).
    instance_name: str = ""

    def __post_init__(self) -> None:
        """Refuse a value that is not the kind this class declares.

        ``from_payload`` copies this section verbatim and an Editor may now
        persist part of it, so every field here is reachable from a stale
        client or a hand-edited file. Held to the declared kinds rather than to
        the two switches that had call-site checks, which is what closes
        ``open_browser`` and ``setup_port`` — a declared switch and a declared
        port that nothing on this path validated at all.

        The switches keep reading the spellings a hand-edited config may use
        (``"yes"``, ``"0"``, ``1``), which ``test_show_agent_activity_defaults_
        off_and_round_trips`` states; that is why the normalisation happens here
        rather than in a check that runs before it.
        """
        _refuse_values_naming_nothing("ui", self)


@dataclass
class VibeCloudRemoteAccessConfig:
    enabled: bool = False
    backend_url: str = "https://avibe.bot"
    public_url: str = ""
    instance_id: str = ""
    instance_kind: str = ""
    client_id: str = ""
    issuer: str = ""
    authorization_endpoint: str = ""
    token_endpoint: str = ""
    jwks_uri: str = ""
    redirect_uri: str = ""
    tunnel_token: str = ""
    instance_secret: str = ""
    session_secret: str = ""
    cloudflared_path: str = ""
    transport_protocol: str = "auto"
    auto_recovery: bool = True
    optimization_profile: str = "balanced"
    edge_ip_version: str = "4"
    edge_bind_address: str = ""
    dev_login_hint: str = ""

    def __post_init__(self) -> None:
        """Refuse a value that is not the kind this class declares.

        ``from_payload`` copies this section's free-form fields verbatim, so a
        hand-edited, migrated, or stale-client payload can hold a number where
        a URL or credential belongs. Stated over the declared fields rather
        than over the three the pairing predicate happens to read: any of them
        can reach code that does string work, and ``is_runtime_paired`` is now
        consulted on every ``/api/config`` response, which would turn one
        malformed field into a 500 on every configuration read.

        Refused rather than emptied. Emptying is a repair, and a repair here
        writes a credential the operator never stored: clearing
        ``session_secret`` logs every remote session out, and clearing
        ``instance_secret`` unpairs the instance — answered ``200``, on a route
        an Editor can now reach. Refusing sends a disk load through
        ``V2Config.load``'s recovery instead, which backs the file up, restores
        this section, and warns; the "degrade to not paired" outcome is
        unchanged and now leaves evidence. Enforced here rather than in
        ``from_payload`` so every construction path holds the invariant.

        ``instance_kind`` is the one field exempt from that, because for it
        "unreadable" and "unknown" are the same answer and ``""`` already means
        unknown — the value a pairing this build does not recognise is meant to
        carry. It is server-set at pairing and absent from every write surface,
        so nothing an operator types reaches it.
        """
        if self.instance_kind not in ("personal", "organization"):
            self.instance_kind = ""
        _refuse_values_naming_nothing("remote_access.vibe_cloud", self)

    def runtime_credentials(self) -> tuple[str, str, str] | None:
        """Return ``(backend_url, instance_id, instance_secret)``, or ``None``.

        The single definition of "this pairing can actually reach Avibe
        Cloud". A recovered, migrated, or partially configured instance can
        carry ``enabled`` and an ``instance_id`` while the secret every cloud
        call needs is gone, so identifiers alone are not a readiness signal.
        Runtime services call this to build their client; config projections
        call ``is_runtime_paired`` to decide whether to offer the matching
        control. One predicate, so a surface cannot promise what the runtime
        will refuse.
        """
        if not self.enabled:
            return None
        backend_url = (self.backend_url or "").strip().rstrip("/")
        instance_id = (self.instance_id or "").strip()
        instance_secret = (self.instance_secret or "").strip()
        if not backend_url or not instance_id or not instance_secret:
            return None
        return backend_url, instance_id, instance_secret

    def is_runtime_paired(self) -> bool:
        """Whether cloud-backed features can run against this pairing."""
        return self.runtime_credentials() is not None


@dataclass
class RemoteAccessConfig:
    provider: str = "vibe_cloud"
    vibe_cloud: VibeCloudRemoteAccessConfig = field(default_factory=VibeCloudRemoteAccessConfig)


@dataclass
class UpdateConfig:
    """Configuration for automatic update checking and installation."""

    auto_update: bool = True  # Auto-install updates when idle
    check_interval_minutes: int = 60  # How often to check for updates (0 = disable)
    idle_minutes: int = 30  # Minutes of inactivity before auto-update
    notify_admins: bool = True  # Send update notification to admins when update is available


@dataclass
class PlatformsConfig:
    """Multi-platform enablement metadata.

    ``primary`` remains the compatibility anchor for legacy single-platform
    code paths while ``enabled`` is the new source of truth.
    """

    enabled: list[str] = field(default_factory=lambda: ["slack"])
    primary: str = "slack"

    def validate(self) -> None:
        supported = supported_platform_set()
        normalized: list[str] = []
        for platform in self.enabled:
            if platform not in supported:
                raise ValueError(f"Unsupported enabled platform: {platform}")
            # The in-process workbench is never an enabled IM transport — the
            # controller wires it directly. Strip it from ``enabled`` so a
            # legacy/hand-edited config can't crash the IM factory or strand the
            # primary when a real IM is also enabled.
            if is_workbench_platform(platform):
                continue
            if platform not in normalized:
                normalized.append(platform)
        if not normalized:
            # Workbench-only install: no external IM platform is enabled. The
            # Avibe Workbench (in-process Web UI) is the sole inbound surface,
            # so anchor ``primary`` to it instead of force-inserting a real IM.
            # ``avibe`` is a registered platform but is intentionally NOT added
            # to ``enabled`` — it has no remote runtime and the controller wires
            # it as the in-process client directly (see ``_init_modules``).
            self.primary = WORKBENCH_PLATFORM_ID
            self.enabled = []
            return
        if is_workbench_platform(self.primary):
            # Real IM platforms are enabled, so the workbench can't be the
            # primary transport — retarget to the first real platform.
            self.primary = normalized[0]
        elif self.primary not in supported:
            supported_text = "', '".join(supported_platform_ids())
            raise ValueError(f"Config 'platforms.primary' must be one of: '{supported_text}'")
        elif self.primary not in normalized:
            # ``enabled`` is the source of truth and ``primary`` is now an
            # internal default with no user-facing control. A primary that is
            # not in the enabled set (e.g. a stale value surviving a deep config
            # merge after the platform was disabled) must FOLLOW enabled, not
            # resurrect a removed platform by forcing itself back into the list.
            self.primary = normalized[0]
        self.enabled = normalized


@dataclass
class V2Config:
    mode: str
    version: str
    slack: SlackConfig
    runtime: RuntimeConfig
    agents: AgentsConfig
    model_hub: ModelHubConfig = field(default_factory=ModelHubConfig)
    platform: str = "slack"
    platforms: PlatformsConfig = field(default_factory=PlatformsConfig)
    discord: Optional[DiscordConfig] = None
    telegram: Optional[TelegramConfig] = None
    lark: Optional[LarkConfig] = None
    wechat: Optional[WeChatConfig] = None
    # Always present: Avibe is in-process and has no credentials, so legacy
    # configs that pre-date the platform still get a usable adapter.
    avibe: AvibeConfig = field(default_factory=AvibeConfig)
    platform_configs: dict[str, BaseIMConfig] = field(default_factory=dict)
    gateway: Optional[GatewayConfig] = None
    ui: UiConfig = field(default_factory=UiConfig)
    remote_access: RemoteAccessConfig = field(default_factory=RemoteAccessConfig)
    audio_asr: AudioAsrConfig = field(default_factory=AudioAsrConfig)
    update: UpdateConfig = field(default_factory=UpdateConfig)
    ack_mode: str = "typing"
    show_duration: bool = False  # Show task duration in result messages
    include_time_info: bool = True  # Prepend current local time to agent messages
    include_user_info: bool = True  # Prepend user identity to agent messages
    reply_enhancements: bool = True  # Enable quick-reply buttons
    language: str = "en"  # Global language setting (see vibe/i18n)
    # Progress UX for editing platforms (Slack/Discord):
    #   "off" (default) no process bubble, "concise" one self-updating bubble,
    #   "verbose" legacy append/split process log.
    agent_progress_style: str = DEFAULT_AGENT_PROGRESS_STYLE
    agent_status_heartbeat_ms: int = 8000  # status-bubble elapsed-timer heartbeat
    agent_status_no_output_ms: int = 180000  # "no output for N min" hint threshold
    # True once the user has finished the setup wizard. This is the explicit
    # gate for ``setup_state().needs_setup`` — it replaces the old heuristic
    # that inferred "setup done" from having a mode plus configured platform
    # credentials (which forced credential-less / workbench-only installs back
    # 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, ...]] = ()
    recovered_sections: ClassVar[tuple[str, ...]] = ()
    whole_config_recovery: ClassVar[bool] = False
    # Where section recovery rewrote the stored document, and the write fence
    # built from it by ``load``. Both are non-persisted, like the diagnostics.
    _recovered_regions: ClassVar[tuple[tuple[tuple[str, ...], tuple[str, ...]], ...]] = ()
    _recovery_guard: ClassVar[Optional[_RecoveredSectionGuard]] = None

    @classmethod
    def default(cls) -> "V2Config":
        """Return the minimal safe config used for first-run."""

        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 _recovery_default(cls) -> "V2Config":
        """Unreadable installations must not acquire fresh-install Hub modes."""
        config = cls.default()
        config.model_hub = ModelHubConfig.from_payload({"enabled": False})
        return config

    @classmethod
    def load(
        cls,
        config_path: Optional[Path] = None,
        *,
        persist_migrations: bool = False,
        _migration_reload_depth: int = 0,
    ) -> "V2Config":
        """Read/project config without implicitly upgrading the shared file.

        A newly installed CLI can coexist with a still-running older service.
        Only the replacement service's lock-owning startup opts into migration
        persistence; incidental reads must not invalidate that older reader.
        Explicit saves remain writes, and recovery keeps its backup evidence.

        A plain load (``persist_migrations=False``) never writes config.json and
        takes no config lock. Its only disk effects are data-dir bootstrap and
        uniquely named, append-only evidence backups, both outside the config
        lock. Every writer publishes the file with an atomic replace, so the read
        sees one whole snapshot: the old file or the new one. The read takes no
        lock in either mode: migration persistence re-reads the file under the
        config lock and replaces it only if it still holds these bytes. A lock
        here would also invert the canonical order (config lock, then SQLite
        writer) for every caller that reads config inside an open SQLite write
        transaction, while a config writer waits for that SQLite writer.
        """
        paths.ensure_data_dirs()
        path = config_path or paths.get_config_path()
        if not path.exists():
            raise FileNotFoundError(f"Config not found: {path}")
        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._recovery_default()
            config.load_warnings = (warning,)
            config.recovered_sections = ()
            config.whole_config_recovery = True
            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._recovery_default()
            config.load_warnings = (warning,)
            config.recovered_sections = ()
            config.whole_config_recovery = True
            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._recovery_default()
            config.load_warnings = (warning,)
            config.recovered_sections = ()
            config.whole_config_recovery = True
            return config

        migrated_payload, migrated, migration_warnings = _migrate_config_payload_on_load(payload)
        config = cls._recover_payload(migrated_payload)
        recovery_warnings = config.load_warnings
        recovered_sections = config.recovered_sections
        whole_config_recovery = config.whole_config_recovery
        # Use raw marker presence, not the current writer's dataclass default.
        # Only a fully valid installation qualifies; recovery must never make
        # an old runtime opt-in look like a successful upgrade.
        runtime_default_pending = (
            not migration_warnings
            and not recovery_warnings
            and (migrated_payload.get("model_hub") or {}).get("runtime_default_applied") is not True
        )
        stored_hub = payload.get("model_hub")
        previous_runtime_enabled = isinstance(stored_hub, dict) and stored_hub.get("enabled") is True
        if runtime_default_pending:
            # Reading an old file is not permission to activate its pending
            # default. In particular, a store reload after a failed startup
            # backup/CAS must not undo the failure's disabled-runtime result.
            config.model_hub.enabled = True if persist_migrations else previous_runtime_enabled
            config.model_hub.runtime_default_applied = persist_migrations
            migrated = True
        elif migration_warnings or recovery_warnings:
            # Do not materialize a new runtime default while recovering an
            # unrelated malformed section. Preserve an already enabled Hub
            # only when its own config could be parsed safely.
            config.model_hub.enabled = config.model_hub.enabled and previous_runtime_enabled
            if (
                "model_hub" not in recovered_sections
                and not whole_config_recovery
                and not (
                    isinstance(migrated_payload.get("model_hub"), dict)
                    and migrated_payload["model_hub"].get("runtime_default_applied") is True
                )
            ):
                # Section recovery permits unrelated saves, and like a clean
                # read-only load they must not acknowledge an upgrade no one
                # performed.
                config.model_hub.runtime_default_applied = False
        all_warnings = tuple(dict.fromkeys((*migration_warnings, *recovery_warnings)))
        if (
            persist_migrations
            and (migrated or "memory" in payload)
            and not migration_warnings
            and not recovery_warnings
        ):
            persisted_payload = copy.deepcopy(payload)
            persisted_payload.pop("memory", None)
            if migrated:
                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:
                if runtime_default_pending:
                    # A failed backup/CAS must not activate an uncommitted
                    # default. A future successful load may retry the upgrade.
                    config.model_hub.enabled = previous_runtime_enabled
                    config.model_hub.runtime_default_applied = False
                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,
                        persist_migrations=persist_migrations,
                        _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,
            )
            if config._recovered_regions and not migration_warnings:
                config._recovery_guard = _RecoveredSectionGuard.capture(
                    config, all_warnings, config._recovered_regions, backup
                )
        config.load_warnings = all_warnings
        config.recovered_sections = tuple(sorted(recovered_sections))
        config.whole_config_recovery = whole_config_recovery
        return config

    @classmethod
    def _recover_payload(cls, candidate: dict) -> "V2Config":
        """Parse stored data with recovery defaults, without file IO or locks."""
        recovery_warnings: list[str] = []
        recovered_sections: set[str] = set()
        rewritten: dict[tuple[str, ...], set[str]] = {}
        whole_config_recovery = False
        while True:
            try:
                config = cls.from_payload(candidate)
                break
            except (TypeError, ValueError) as exc:
                section = _recovery_section_for_error(exc)
                field_name = _recovery_field_for_error(section, exc)
                # Keyed by whatever this pass will actually repair, so the
                # dedupe that stops the loop cannot mistake a second unreadable
                # field of a field-scoped section for no progress and discard
                # the whole file.
                recovered = section if field_name is None else f"{section}.{field_name}"
                if section is None or recovered in recovered_sections:
                    warning = f"Config could not be loaded; using recovery defaults: {exc}"
                    logger.error("%s", warning)
                    config = cls._recovery_default()
                    recovery_warnings.append(warning)
                    whole_config_recovery = True
                    break
                before_reset = copy.deepcopy(candidate)
                if not _reset_recoverable_config_section(candidate, section, field_name):
                    warning = f"Config section '{section}' could not be recovered; using recovery defaults: {exc}"
                    logger.error("%s", warning)
                    config = cls._recovery_default()
                    recovery_warnings.append(warning)
                    whole_config_recovery = True
                    break
                # Diff each reset on its own: ``from_payload`` normalizes a few
                # stored values in place, and those are not recovery's rewrites.
                for path in {
                    tuple(recovered.split(".")[:_RECOVERY_REGION_DEPTH]),
                    *_changed_config_paths(before_reset, candidate),
                }:
                    rewritten.setdefault(path, set()).add(recovered)
                recovered_sections.add(recovered)
                recovery_warnings.append(f"Recovered invalid config section '{recovered}': {exc}")

        config.load_warnings = tuple(recovery_warnings)
        config.recovered_sections = tuple(sorted(recovered_sections))
        config.whole_config_recovery = whole_config_recovery
        if rewritten and not whole_config_recovery:
            config._recovered_regions = _recovered_write_regions(rewritten, candidate)
        return config

    @classmethod
    def from_payload(cls, payload: dict) -> "V2Config":
        if not isinstance(payload, dict):
            raise ValueError("Config payload must be an object")

        mode = payload.get("mode")
        if not isinstance(mode, str) or mode not in {"self_host", "saas"}:
            raise ValueError("Config 'mode' must be 'self_host' or 'saas'")

        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(enabled_payload or []),
                primary=primary_payload or platform,
            )
        else:
            platforms = PlatformsConfig(enabled=[platform], primary=platform)
        # When the caller explicitly set 'platform' but did not provide
        # 'platforms', treat it as a legacy single-platform update and
        # sync the new structure so that the old field is not silently
        # overridden by a stale 'platforms' value from a prior merge.
        if "platform" in payload and "platforms" not in payload:
            platforms = PlatformsConfig(enabled=[platform], primary=platform)
        platforms.validate()
        platform = platforms.primary

        platform_configs: dict[str, Optional[BaseIMConfig]] = {}
        for descriptor in platform_descriptors():
            platform_payload = payload.get(descriptor.config_key)
            if descriptor.id == "slack":
                platform_payload = platform_payload or {}
                if isinstance(platform_payload, dict) and "require_mention" not in platform_payload:
                    platform_payload = dict(platform_payload)
                    platform_payload["require_mention"] = False
            if platform_payload is not None and not isinstance(platform_payload, dict):
                raise ValueError(f"Config '{descriptor.config_key}' must be an object")
            if platform_payload is None:
                platform_configs[descriptor.id] = None
                continue

            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
        # mention "avibe" don't trip the validation loop below.
        if platform_configs.get("avibe") is None:
            platform_configs["avibe"] = AvibeConfig()

        # Validate that every enabled platform has its config section present.
        for _ep in platforms.enabled:
            descriptor = get_platform_descriptor(_ep)
            if platform_configs[descriptor.id] is None:
                raise ValueError(f"Config '{descriptor.config_key}' must be provided when {_ep} is enabled")

        gateway_payload = payload.get("gateway")
        if gateway_payload is not None and not isinstance(gateway_payload, dict):
            raise ValueError("Config 'gateway' must be an object")
        gateway = GatewayConfig(**_filter_dataclass_fields(GatewayConfig, gateway_payload)) if gateway_payload else None

        runtime_payload = payload.get("runtime")
        if not isinstance(runtime_payload, dict):
            raise ValueError("Config 'runtime' must be an object")
        runtime = RuntimeConfig(**_filter_dataclass_fields(RuntimeConfig, runtime_payload))

        agents_payload = payload.get("agents")
        if not isinstance(agents_payload, dict):
            raise ValueError("Config 'agents' must be an object")

        opencode_payload = agents_payload.get("opencode") or {}
        if not isinstance(opencode_payload, dict):
            raise ValueError("Config 'agents.opencode' must be an object")

        claude_payload = agents_payload.get("claude") or {}
        if not isinstance(claude_payload, dict):
            raise ValueError("Config 'agents.claude' must be an object")

        codex_payload = agents_payload.get("codex") or {}
        if not isinstance(codex_payload, dict):
            raise ValueError("Config 'agents.codex' must be an object")

        avault_payload = agents_payload.get("avault") or {}
        if not isinstance(avault_payload, dict):
            raise ValueError("Config 'agents.avault' must be an object")

        opencode = OpenCodeConfig(**_filter_dataclass_fields(OpenCodeConfig, opencode_payload))
        claude = ClaudeConfig(**_filter_dataclass_fields(ClaudeConfig, claude_payload))
        codex = CodexConfig(**_filter_dataclass_fields(CodexConfig, codex_payload))
        for backend_name, backend_config in (("opencode", opencode), ("claude", claude), ("codex", codex)):
            # Unattended upgrades run on this switch, so ``"false"`` must read as off.
            backend_config.auto_update = _named_bool(
                f"agents.{backend_name}.auto_update", backend_config.auto_update
            )
        avault = AVaultConfig(**_filter_dataclass_fields(AVaultConfig, avault_payload))

        agents = AgentsConfig(
            opencode=opencode,
            claude=claude,
            codex=codex,
            avault=avault,
        )

        model_hub_payload = payload.get("model_hub")
        if model_hub_payload is None:
            # Enable the gateway runtime on upgrade without changing the
            # authentication owner of existing native CLI installations.
            model_hub = ModelHubConfig.from_payload({})
        else:
            # The one repairing door, because this is the one caller parsing a
            # document a previous release wrote. Every other entry into these
            # constructors is either a request from a client — which must be told
            # it named a model twice rather than answered with half of what it
            # sent — or a round trip of objects this process already settled. The
            # save paths reach here too, but never with this subtree: the config
            # API drops ``model_hub`` from what the client sends, so the payload
            # under this key is always what was last read off disk.
            model_hub = ModelHubConfig.from_payload(model_hub_payload, repairing=True)

        ui_payload = payload.get("ui") or {}
        if not isinstance(ui_payload, dict):
            raise ValueError("Config 'ui' must be an object")
        ui = UiConfig(**_filter_dataclass_fields(UiConfig, ui_payload))
        # ``UiConfig.__post_init__`` has already held every field to its declared
        # kind, so this is only the range policy: clamping an out-of-range size
        # still honours what the caller asked for.
        ui.chat_message_font_size = max(
            MIN_CHAT_MESSAGE_FONT_SIZE_PX,
            min(MAX_CHAT_MESSAGE_FONT_SIZE_PX, ui.chat_message_font_size),
        )

        remote_access_payload = payload.get("remote_access") or {}
        if not isinstance(remote_access_payload, dict):
            raise ValueError("Config 'remote_access' must be an object")
        remote_access_provider = remote_access_payload.get("provider") or "vibe_cloud"
        if remote_access_provider != "vibe_cloud":
            raise ValueError("Config 'remote_access.provider' must be 'vibe_cloud'")
        vibe_cloud_payload = remote_access_payload.get("vibe_cloud") or {}
        if not isinstance(vibe_cloud_payload, dict):
            raise ValueError("Config 'remote_access.vibe_cloud' must be an object")
        remote_access = RemoteAccessConfig(
            provider=remote_access_provider,
            vibe_cloud=VibeCloudRemoteAccessConfig(
                **_filter_dataclass_fields(VibeCloudRemoteAccessConfig, vibe_cloud_payload)
            ),
        )
        remote_access.vibe_cloud.transport_protocol = str(
            remote_access.vibe_cloud.transport_protocol or "auto"
        ).strip().lower()
        if remote_access.vibe_cloud.transport_protocol not in {"auto", "quic", "http2"}:
            raise ValueError(
                "Config 'remote_access.vibe_cloud.transport_protocol' must be 'auto', 'quic', or 'http2'"
            )
        # ``auto_recovery`` reads the same spellings every other switch does;
        # ``VibeCloudRemoteAccessConfig.__post_init__`` has already resolved it,
        # where the truthy/else it used to have would have read ``"garbage"`` as
        # off and a stale client's ``[1]`` as on.
        remote_access.vibe_cloud.optimization_profile = str(
            remote_access.vibe_cloud.optimization_profile or "balanced"
        ).strip().lower()
        if remote_access.vibe_cloud.optimization_profile not in {
            "stable",
            "balanced",
            "low_latency",
        }:
            raise ValueError(
                "Config 'remote_access.vibe_cloud.optimization_profile' must be "
                "'stable', 'balanced', or 'low_latency'"
            )
        remote_access.vibe_cloud.edge_ip_version = str(
            remote_access.vibe_cloud.edge_ip_version or "4"
        ).strip().lower()
        if remote_access.vibe_cloud.edge_ip_version not in {"auto", "4", "6"}:
            raise ValueError(
                "Config 'remote_access.vibe_cloud.edge_ip_version' must be 'auto', '4', or '6'"
            )
        remote_access.vibe_cloud.edge_bind_address = str(
            remote_access.vibe_cloud.edge_bind_address or ""
        ).strip()
        if remote_access.vibe_cloud.edge_bind_address:
            try:
                remote_access.vibe_cloud.edge_bind_address = str(
                    ipaddress.ip_address(remote_access.vibe_cloud.edge_bind_address)
                )
            except ValueError as exc:
                raise ValueError(
                    "Config 'remote_access.vibe_cloud.edge_bind_address' must be an IP address"
                ) from exc

        audio_asr_payload = payload.get("audio_asr") or {}
        if not isinstance(audio_asr_payload, dict):
            raise ValueError("Config 'audio_asr' must be an object")
        audio_asr_enabled_present = "enabled" in audio_asr_payload
        audio_asr = AudioAsrConfig(**_filter_dataclass_fields(AudioAsrConfig, audio_asr_payload))
        if audio_asr_enabled_present and audio_asr.enabled is False and not audio_asr.enabled_configured:
            audio_asr.enabled_configured = True
        # ``AudioAsrConfig.__post_init__`` has already held every field to its
        # declared kind, so what is left here is range and format policy: a
        # value that names a legal setting is clamped to the nearest legal one.
        audio_asr.timeout_seconds = max(0.1, audio_asr.timeout_seconds)
        if audio_asr.max_file_bytes is not None:
            audio_asr.max_file_bytes = max(1, audio_asr.max_file_bytes)
        if not audio_asr.endpoint_path.startswith("/"):
            raise ValueError("Config 'audio_asr.endpoint_path' must be a path starting with '/'")
        if not audio_asr.model.strip():
            raise ValueError("Config 'audio_asr.model' must be a non-empty string")

        update_payload = payload.get("update") or {}
        if not isinstance(update_payload, dict):
            raise ValueError("Config 'update' must be an object")
        # Backward compat: rename legacy "notify_slack" → "notify_admins"
        if "notify_slack" in update_payload and "notify_admins" not in update_payload:
            update_payload["notify_admins"] = update_payload.pop("notify_slack")
        update = UpdateConfig(**_filter_dataclass_fields(UpdateConfig, update_payload))

        ack_mode = payload.get("ack_mode", "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'")

        # Every preference below answers a wrong-typed value the way
        # ``ack_mode`` above already does — by raising. This module's split is
        # that ``from_payload`` validates and only disk loading recovers (see
        # ``_reset_recoverable_config_section``), so a preference that quietly
        # substituted its default broke the split in both directions: over HTTP
        # the route answered 200 having stored a value the caller never sent
        # (turning an enabled preference off on a request that asked to turn it
        # on), and on disk the recovery entries written for these very fields
        # were unreachable, so a hand-edit degraded with no warning.
        def _declared_bool(name: str, default: bool) -> bool:
            value = payload.get(name, default)
            if not isinstance(value, bool):
                raise ValueError(f"Config '{name}' must be a boolean")
            return value

        show_duration = _declared_bool("show_duration", False)
        include_user_info = _declared_bool("include_user_info", True)
        include_time_info = _declared_bool("include_time_info", True)
        reply_enhancements = _declared_bool("reply_enhancements", True)

        language = normalize_language(payload.get("language"), default="en")

        agent_progress_style = payload.get("agent_progress_style", DEFAULT_AGENT_PROGRESS_STYLE)
        if agent_progress_style not in ("concise", "verbose", "off"):
            raise ValueError("Config 'agent_progress_style' must be 'concise', 'verbose', or 'off'")

        def _positive_int(value, default, maximum):
            if isinstance(value, bool) or not isinstance(value, int) or value <= 0 or value > maximum:
                return default
            return value

        # Cap to sane upper bounds so a fat-fingered value can't silence the
        # heartbeat (heartbeat ≤ 1h, no-output hint ≤ 24h); out-of-range → default.
        # These two keep the fallback the settings above give up: they are not on
        # the Settings write surface, and ``test_status_bubble_settings`` states
        # the tolerance as a contract rather than as an accident.
        agent_status_heartbeat_ms = _positive_int(payload.get("agent_status_heartbeat_ms"), 8000, 3_600_000)
        agent_status_no_output_ms = _positive_int(payload.get("agent_status_no_output_ms"), 180000, 86_400_000)

        # ``setup_completed`` is the explicit setup gate. Read the stored value
        # when present; otherwise leave it ``None`` here and derive it below
        # from the legacy "setup done" heuristic so installs configured before
        # this flag existed are not bounced back into the wizard.
        setup_completed = payload.get("setup_completed")
        if setup_completed is not None and not isinstance(setup_completed, bool):
            raise ValueError("Config 'setup_completed' must be a boolean")

        config = cls(
            platform=platform,
            platforms=platforms,
            mode=mode,
            version=payload.get("version", "v2"),
            slack=platform_configs["slack"],
            discord=platform_configs["discord"],
            telegram=platform_configs["telegram"],
            lark=platform_configs["lark"],
            wechat=platform_configs["wechat"],
            # Default Avibe to an enabled instance when the payload is missing
            # the section — legacy configs predate the platform.
            avibe=platform_configs.get("avibe") or AvibeConfig(),
            platform_configs={key: value for key, value in platform_configs.items() if value is not None},
            runtime=runtime,
            agents=agents,
            model_hub=model_hub,
            gateway=gateway,
            ui=ui,
            remote_access=remote_access,
            audio_asr=audio_asr,
            update=update,
            ack_mode=ack_mode,
            show_duration=show_duration,
            include_time_info=include_time_info,
            include_user_info=include_user_info,
            reply_enhancements=reply_enhancements,
            language=language,
            agent_progress_style=agent_progress_style,
            agent_status_heartbeat_ms=agent_status_heartbeat_ms,
            agent_status_no_output_ms=agent_status_no_output_ms,
        )

        # Migration: when the payload predates ``setup_completed``, derive it
        # from the legacy heuristic (a mode plus at least one configured
        # platform). Only derive when the key is absent; an explicitly stored
        # value always wins.
        if setup_completed is None:
            setup_completed = bool(config.mode) and bool(config.configured_platforms())
        config.setup_completed = setup_completed

        return config

    def save(self, config_path: Optional[Path] = None) -> None:
        """Persist the configuration snapshot.

        WARNING — cross-process lost updates: this writes the object's
        FULL snapshot. If this ``V2Config`` was loaded earlier (another
        request, minutes ago) while a different process (UI API server
        vs controller, both write this file) committed changes since,
        saving here silently reverts them. UI/controller writers must
        instead declare their change through ``update_config_fields``
        (see docs/plans/config-cross-process-write-serialization.md),
        which loads fresh inside the cross-process file lock and only
        applies the caller's fields. Direct load → mutate → ``save()``
        cycles are only acceptable in single-writer contexts.

        A config loaded with section recovery saves only while every recovered
        region still holds what was loaded; those regions are written from the
        file as it stands, never from the recovery defaults in memory. Any other
        load warning refuses the save.
        """

        refusal = self.pending_write_refusal()
        if refusal is not None:
            raise ValueError(refusal)
        paths.ensure_data_dirs()
        path = config_path or paths.get_config_path()
        with config_file_lock(path):
            self._write_locked(path)

    def pending_write_refusal(self) -> Optional[str]:
        """Why saving this snapshot would be refused, before anything runs."""

        if not self.load_warnings:
            return None
        guard = _active_recovery_guard(self)
        if guard is None:
            return _RECOVERY_SAVE_REFUSAL
        return guard.change_refusal(self._persisted_document())

    def inherit_load_diagnostics(self, loaded: "V2Config") -> None:
        """Hold a snapshot derived from ``loaded`` to that load's recovery state."""

        self.load_warnings = loaded.load_warnings
        self.recovered_sections = loaded.recovered_sections
        self.whole_config_recovery = loaded.whole_config_recovery
        self._recovery_guard = loaded._recovery_guard

    def _write_locked(self, path: Path) -> None:
        """Write an exact snapshot while the config transaction is held."""

        self.platforms.validate()
        self.platform = self.platforms.primary
        guard = _active_recovery_guard(self)
        if guard is None:
            _write_config_payload(path, self._persisted_payload())
            return
        _write_config_payload(
            path, guard.preserve_stored_regions(path, self._persisted_document())
        )

    def _persisted_document(self) -> dict:
        """The saved form as plain JSON values, detached from this object."""

        return json.loads(json.dumps(self._persisted_payload()))

    def _persisted_payload(self) -> dict:
        platform_payload = {}
        for descriptor in platform_descriptors():
            descriptor_config = descriptor.get_config(self)
            config_payload = descriptor_config.__dict__.copy() if descriptor_config else None
            if descriptor.id == "discord" and isinstance(config_payload, dict):
                if not config_payload.get("guild_allowlist") and not config_payload.get("guild_denylist"):
                    config_payload.pop("guild_allowlist", None)
                    config_payload.pop("guild_denylist", None)
            platform_payload[descriptor.config_key] = config_payload
        payload = {
            "platform": self.platforms.primary,
            "platforms": {
                "enabled": self.platforms.enabled,
                "primary": self.platforms.primary,
            },
            "mode": self.mode,
            "version": self.version,
            **platform_payload,
            "runtime": {
                "default_cwd": self.runtime.default_cwd,
                "log_level": self.runtime.log_level,
                "show_page_api_timeout_seconds": self.runtime.show_page_api_timeout_seconds,
                "resource_governance": self.runtime.resource_governance,
                "harness_run_sweep_interval_seconds": self.runtime.harness_run_sweep_interval_seconds,
                "harness_run_orphan_grace_seconds": self.runtime.harness_run_orphan_grace_seconds,
                "harness_run_queued_ttl_seconds": self.runtime.harness_run_queued_ttl_seconds,
                "harness_run_hold_ttl_seconds": self.runtime.harness_run_hold_ttl_seconds,
                "harness_prompt_echo": self.runtime.harness_prompt_echo,
                "agent_events_trace_retention_enabled": self.runtime.agent_events_trace_retention_enabled,
                "agent_events_trace_retention_days": self.runtime.agent_events_trace_retention_days,
                "skill_observability_enabled": self.runtime.skill_observability_enabled,
            },
            "agents": {
                "opencode": self.agents.opencode.__dict__,
                "claude": self.agents.claude.__dict__,
                "codex": self.agents.codex.__dict__,
                "avault": self.agents.avault.__dict__,
            },
            "model_hub": self.model_hub.to_payload(),
            "gateway": self.gateway.__dict__ if self.gateway else None,
            "ui": self.ui.__dict__,
            "remote_access": {
                "provider": self.remote_access.provider,
                "vibe_cloud": self.remote_access.vibe_cloud.__dict__,
            },
            "audio_asr": self.audio_asr.__dict__,
            "update": self.update.__dict__,
            "ack_mode": self.ack_mode,
            "show_duration": self.show_duration,
            "include_time_info": self.include_time_info,
            "include_user_info": self.include_user_info,
            "reply_enhancements": self.reply_enhancements,
            "language": self.language,
            "agent_progress_style": self.agent_progress_style,
            "agent_status_heartbeat_ms": self.agent_status_heartbeat_ms,
            "agent_status_no_output_ms": self.agent_status_no_output_ms,
            "setup_completed": self.setup_completed,
        }
        return payload

    def enabled_platforms(self) -> list[str]:
        return list(self.platforms.enabled)

    def platform_has_credentials(self, platform: str) -> bool:
        return get_platform_descriptor(platform).has_credentials(self)

    def configured_platforms(self) -> list[str]:
        return [platform for platform in self.enabled_platforms() if self.platform_has_credentials(platform)]

    def missing_platform_credentials(self) -> list[str]:
        return [platform for platform in self.enabled_platforms() if not self.platform_has_credentials(platform)]

    def has_configured_platform_credentials(self) -> bool:
        return bool(self.configured_platforms())

    def platform_catalog(self) -> list[dict]:
        return platform_catalog_payload()

    def setup_state(self) -> dict:
        configured = self.configured_platforms()
        missing = self.missing_platform_credentials()
        return {
            "needs_setup": not self.setup_completed,
            "configured_platforms": configured,
            "missing_credentials": missing,
        }