Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
refactor(settings): retire per-backend routing model aliases (#3054)
Call White976130f11f7f
diff --git a/config/v2_settings.py b/config/v2_settings.pyindex 3984a0ee5..c2cb5e69e 100644--- a/config/v2_settings.py+++ b/config/v2_settings.py@@ -5,7 +5,7 @@ import hmacimport secretsimport stringimport threading-from dataclasses import dataclass, field+from dataclasses import asdict, dataclass, field, fieldsfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Callable, Dict, List, Optional, Tuple@@ -137,23 +137,25 @@ class RoutingSettings:# Scope-level overrides applied on top of the selected Vibe Agent.model: Optional[str] = Nonereasoning_effort: Optional[str] = None- # OpenCode settings+ # The native agent each CLI backend runs for this scope.opencode_agent: Optional[str] = None- opencode_model: Optional[str] = None- opencode_reasoning_effort: Optional[str] = None- # Claude Code settingsclaude_agent: Optional[str] = None- claude_model: Optional[str] = None- claude_reasoning_effort: Optional[str] = None- # Codex settingscodex_agent: Optional[str] = None- codex_model: Optional[str] = None- codex_reasoning_effort: Optional[str] = None-def _backend_specific_value(routing: RoutingSettings, backend: Optional[str], field: str) -> Optional[str]:- if backend not in NATIVE_CLI_BACKENDS:++# Retired per-backend spellings of a scope's model and effort (``claude_model``,+# ``codex_reasoning_effort``, ...). Older releases stored them, and API callers may+# still send them; they are read only to fill ``model`` / ``reasoning_effort`` for a+# route on that built-in backend's Agent, and are never stored or returned.+LEGACY_ROUTING_ALIASES = frozenset(+ f"{backend}_{kind}" for backend in NATIVE_CLI_BACKENDS for kind in ("model", "reasoning_effort")+)+++def _legacy_routing_alias(payload: dict, agent_name: Optional[str], kind: str) -> Optional[str]:+ if agent_name not in NATIVE_CLI_BACKENDS:return None- return getattr(routing, f"{backend}_{field}", None)+ return payload.get(f"{agent_name}_{kind}")def _payload_value(payload: dict, key: str, fallback_key: str) -> Optional[str]:@@ -163,27 +165,31 @@ def _payload_value(payload: dict, key: str, fallback_key: str) -> Optional[str]:def normalize_routing_settings(routing: Optional[RoutingSettings]) -> RoutingSettings:- """Normalize scope routing without consulting deprecated backend routing."""+ """A copy of a scope route, or the empty route."""if routing is None:return RoutingSettings()- agent_name = getattr(routing, "agent_name", None)- builtin_agent_backend = agent_name if agent_name in NATIVE_CLI_BACKENDS else None- model = getattr(routing, "model", None)- reasoning_effort = getattr(routing, "reasoning_effort", None)+ return RoutingSettings(**{item.name: getattr(routing, item.name, None) for item in fields(RoutingSettings)})+++def routing_from_stored_payload(payload: Optional[dict]) -> RoutingSettings:+ """A route as stored in a scope's settings, from this or an older release.++ An empty canonical value falls back to its retired per-backend alias, as the+ rows older releases wrote can carry only that.+ """+ payload = payload if isinstance(payload, dict) else {}+ agent_name = payload.get("agent_name") or payload.get("agent")return RoutingSettings(agent_name=agent_name,- model=model or _backend_specific_value(routing, builtin_agent_backend, "model"),- reasoning_effort=reasoning_effort- or _backend_specific_value(routing, builtin_agent_backend, "reasoning_effort"),- opencode_agent=getattr(routing, "opencode_agent", None),- opencode_model=getattr(routing, "opencode_model", None),- opencode_reasoning_effort=getattr(routing, "opencode_reasoning_effort", None),- claude_agent=getattr(routing, "claude_agent", None),- claude_model=getattr(routing, "claude_model", None),- claude_reasoning_effort=getattr(routing, "claude_reasoning_effort", None),- codex_agent=getattr(routing, "codex_agent", None),- codex_model=getattr(routing, "codex_model", None),- codex_reasoning_effort=getattr(routing, "codex_reasoning_effort", None),+ model=payload.get("model")+ or payload.get("model_override")+ or _legacy_routing_alias(payload, agent_name, "model"),+ reasoning_effort=payload.get("reasoning_effort")+ or payload.get("reasoning_effort_override")+ or _legacy_routing_alias(payload, agent_name, "reasoning_effort"),+ opencode_agent=payload.get("opencode_agent"),+ claude_agent=payload.get("claude_agent"),+ codex_agent=payload.get("codex_agent"),)@@ -271,53 +277,43 @@ class SettingsState:bind_codes: List[BindCode] = field(default_factory=list)+def lift_legacy_routing_aliases(payload: dict, agent_name: Optional[str]) -> dict:+ """``payload`` with its retired per-backend aliases folded into the canonical keys.++ An alias fills only a canonical key the payload does not state, and only+ for a route on that built-in backend's own Agent; every alias is dropped.+ """+ lifted = {key: value for key, value in payload.items() if key not in LEGACY_ROUTING_ALIASES}+ for kind in ("model", "reasoning_effort"):+ alias = _legacy_routing_alias(payload, agent_name, kind)+ if alias is not None and kind not in lifted and f"{kind}_override" not in lifted:+ lifted[kind] = alias+ return lifted++def _parse_routing(payload: dict) -> RoutingSettings:- """Parse a routing settings dict into a RoutingSettings dataclass."""+ """A route as an API caller or settings file states it.++ A canonical key that is present wins, even as an explicit clear; only an+ absent one is filled from its retired per-backend alias.+ """if not isinstance(payload, dict):payload = {}- model_key_present = "model" in payload or "model_override" in payload- reasoning_key_present = "reasoning_effort" in payload or "reasoning_effort_override" in payload- return normalize_routing_settings(- RoutingSettings(- agent_name=payload.get("agent_name") or payload.get("agent"),- model=_payload_value(payload, "model", "model_override"),- reasoning_effort=_payload_value(payload, "reasoning_effort", "reasoning_effort_override"),- opencode_agent=payload.get("opencode_agent"),- opencode_model=None if model_key_present else payload.get("opencode_model"),- opencode_reasoning_effort=None if reasoning_key_present else payload.get("opencode_reasoning_effort"),- claude_agent=payload.get("claude_agent"),- claude_model=None if model_key_present else payload.get("claude_model"),- claude_reasoning_effort=None if reasoning_key_present else payload.get("claude_reasoning_effort"),- codex_agent=payload.get("codex_agent"),- codex_model=None if model_key_present else payload.get("codex_model"),- codex_reasoning_effort=None if reasoning_key_present else payload.get("codex_reasoning_effort"),- )+ agent_name = payload.get("agent_name") or payload.get("agent")+ payload = lift_legacy_routing_aliases(payload, agent_name)+ return RoutingSettings(+ agent_name=agent_name,+ model=_payload_value(payload, "model", "model_override"),+ reasoning_effort=_payload_value(payload, "reasoning_effort", "reasoning_effort_override"),+ opencode_agent=payload.get("opencode_agent"),+ claude_agent=payload.get("claude_agent"),+ codex_agent=payload.get("codex_agent"),)-def _routing_to_dict(routing: RoutingSettings) -> dict:- """Serialize a RoutingSettings to dict."""- routing = normalize_routing_settings(routing)- return {- "agent_name": routing.agent_name,- "model": routing.model,- "reasoning_effort": routing.reasoning_effort,- "opencode_agent": routing.opencode_agent,- "opencode_model": routing.opencode_model,- "opencode_reasoning_effort": routing.opencode_reasoning_effort,- "claude_agent": routing.claude_agent,- "claude_model": routing.claude_model,- "claude_reasoning_effort": routing.claude_reasoning_effort,- "codex_agent": routing.codex_agent,- "codex_model": routing.codex_model,- "codex_reasoning_effort": routing.codex_reasoning_effort,- }---def routing_to_compat_dict(routing: RoutingSettings) -> dict:- """Serialize routing with legacy read-only aliases derived from canonical fields."""- routing = normalize_routing_settings(routing)- return _routing_to_dict(routing)+def routing_to_dict(routing: Optional[RoutingSettings]) -> dict:+ """A scope route as the settings API and storage spell it."""+ return asdict(normalize_routing_settings(routing))def parse_settings_payload(payload: dict) -> tuple[SettingsState, bool]:diff --git a/core/services/scope_settings.py b/core/services/scope_settings.pyindex 28925d521..3c108ebac 100644--- a/core/services/scope_settings.py+++ b/core/services/scope_settings.py@@ -25,11 +25,11 @@ from config.v2_settings import (_UNSET_AGENT_BINDING,_make_scoped_key,_parse_routing,- _routing_to_dict,+ lift_legacy_routing_aliases,make_thread_native_id,normalize_routing_settings,normalize_show_message_types,- routing_to_compat_dict,+ routing_to_dict,)logger = logging.getLogger(__name__)@@ -113,7 +113,7 @@ def normalize_scope_routing(routing_payload: dict) -> dict:routing.reasoning_effort,catalog_efforts,)- return _routing_to_dict(routing)+ return routing_to_dict(routing)def _stored_agent_name(settings: ChannelSettings | UserSettings) -> Optional[str]:@@ -181,7 +181,11 @@ def apply_scope_change(# Agent and model catalogs, which must not hold other writers up.routing_changes: Optional[dict] = Noneif routing_patch is not None:- stored_routing = routing_to_compat_dict(source_of(store.settings).routing)+ stored_routing = routing_to_dict(source_of(store.settings).routing)+ # A browser tab from an older release may still send retired aliases.+ routing_patch = lift_legacy_routing_aliases(+ routing_patch, routing_patch.get("agent_name", stored_routing["agent_name"])+ )normalized = normalize_scope_routing({**stored_routing, **routing_patch})routing_changes = {name: value@@ -216,7 +220,7 @@ def apply_scope_change(value = normalize_scope_message_types(value, platform)setattr(updated, name, value)if routing_changes:- merged = {**_routing_to_dict(updated.routing), **routing_changes}+ merged = {**routing_to_dict(updated.routing), **routing_changes}updated.routing = normalize_routing_settings(RoutingSettings(**merged))if kind == "thread" and existing is None and updated.require_mention is None:# An inheriting topic's first override keeps the gate it showed.diff --git a/docs/plans/scope-settings-patch.md b/docs/plans/scope-settings-patch.mdindex 4137cf126..a63c0d479 100644--- a/docs/plans/scope-settings-patch.md+++ b/docs/plans/scope-settings-patch.md@@ -103,8 +103,20 @@ reaches it through `SettingsManager.change_scope_settings`:message (a flat DM or chat), as the IM routing form says. `null` when thecontroller cannot answer. The row then says to send `/new` there.-## Out of scope--- Removing the legacy per-backend `<backend>_model` / `<backend>_reasoning_effort`- routing fields from the API, the Web types, and the stored routing JSON. They- are read-only aliases today; removing them is a separate contract cleanup.+## Routing fields++A scope route is `agent_name`, `model`, `reasoning_effort`, and each CLI+backend's native agent (`opencode_agent`, `claude_agent`, `codex_agent`).+The per-backend spellings of the model and effort that older releases wrote+(`<backend>_model`, `<backend>_reasoning_effort`) are retired:++- They are never stored or returned; a route written again drops them.+- A stored row still carrying them is read with the alias filling an empty+ `model` or `reasoning_effort`, after the payload's canonical value and the+ row's columns, and only when the route's Agent is that built-in backend+ (`claude_model` on a `claude` route). Any other alias applies to nothing.+- API input, including `PATCH /api/settings/scope` from a page an older release+ served, may still send them. An alias fills only a canonical key the request+ does not name, by the same rule; a request never fails for naming one.+- The Model Hub credential-address repair still rewrites them in stored rows,+ where they persist until the row is next saved.diff --git a/modules/settings_manager.py b/modules/settings_manager.pyindex fcd1478b8..69d02ea85 100644--- a/modules/settings_manager.py+++ b/modules/settings_manager.py@@ -8,7 +8,8 @@ from config import pathsfrom config.platform_registry import get_platform_descriptorfrom config.v2_sessions import SessionsStorefrom config.v2_settings import SettingsStore, ChannelSettings, GuildSettings, RoutingSettings, SCOPED_KEY_SEP-from config.v2_settings import normalize_routing_settings, split_thread_settings_key+from config.v2_settings import normalize_routing_settings, routing_from_stored_payload, routing_to_dict+from config.v2_settings import split_thread_settings_keyfrom config.v2_settings import UserSettings as BoundUserSettingsfrom core.services import scope_settingsfrom modules.sessions_facade import SessionsFacade@@ -23,34 +24,6 @@ DEFAULT_SHOW_MESSAGE_TYPES: List[str] = ["assistant"]ChannelRouting = RoutingSettings-def _routing_to_dict(routing: Optional[RoutingSettings]) -> dict:- if routing is None:- return {}- return asdict(normalize_routing_settings(routing))---def _routing_from_dict(payload: Optional[dict]) -> RoutingSettings:- data = payload or {}- return normalize_routing_settings(RoutingSettings(- agent_name=data.get("agent_name") or data.get("agent"),- model=data.get("model") or data.get("model_override"),- reasoning_effort=data.get("reasoning_effort") or data.get("reasoning_effort_override"),- opencode_agent=data.get("opencode_agent"),- opencode_model=data.get("opencode_model"),- opencode_reasoning_effort=data.get("opencode_reasoning_effort"),- claude_agent=data.get("claude_agent"),- claude_model=data.get("claude_model"),- claude_reasoning_effort=data.get("claude_reasoning_effort"),- codex_agent=data.get("codex_agent"),- codex_model=data.get("codex_model"),- codex_reasoning_effort=data.get("codex_reasoning_effort"),- ))---def _clone_routing(routing: Optional[RoutingSettings]) -> RoutingSettings:- return _routing_from_dict(_routing_to_dict(routing))--@dataclassclass UserSettings:show_message_types: List[str] = field(default_factory=lambda: DEFAULT_SHOW_MESSAGE_TYPES.copy())@@ -65,7 +38,7 @@ class UserSettings:"custom_cwd": self.custom_cwd,}if self.channel_routing is not None:- result["routing"] = _routing_to_dict(self.channel_routing)+ result["routing"] = routing_to_dict(self.channel_routing)return result@classmethod@@ -83,7 +56,7 @@ class UserSettings:custom_cwd=payload.get("custom_cwd"),)if routing_data is not None:- settings.channel_routing = _routing_from_dict(routing_data)+ settings.channel_routing = routing_from_stored_payload(routing_data)return settings@@ -175,7 +148,7 @@ class SettingsManager:return UserSettings(show_message_types=self._normalize_show_message_types(channel_settings.show_message_types),custom_cwd=channel_settings.custom_cwd,- channel_routing=_clone_routing(channel_settings.routing),+ channel_routing=normalize_routing_settings(channel_settings.routing),enabled=channel_settings.enabled,)@@ -184,7 +157,7 @@ class SettingsManager:return UserSettings(show_message_types=self._normalize_show_message_types(bound_user.show_message_types),custom_cwd=bound_user.custom_cwd,- channel_routing=_clone_routing(bound_user.routing),+ channel_routing=normalize_routing_settings(bound_user.routing),enabled=bound_user.enabled,)@@ -488,7 +461,7 @@ class SettingsManager:current = self.get_channel_routing(settings_key)saved = self.change_scope_settings(settings_key,- {"routing": asdict(normalize_routing_settings(routing))},+ {"routing": routing_to_dict(routing)},expected_agent_name=current.agent_name if current else None,)logger.info(@@ -498,7 +471,7 @@ class SettingsManager:saved.routing.model,saved.routing.reasoning_effort,)- return _clone_routing(saved.routing)+ return normalize_routing_settings(saved.routing)# ---------------------------------------------# Per-channel require_mention managementdiff --git a/scripts/prepare_regression.py b/scripts/prepare_regression.pyindex 48f34dd53..0037b2266 100755--- a/scripts/prepare_regression.py+++ b/scripts/prepare_regression.py@@ -110,16 +110,16 @@ def _build_routing(name: str) -> dict:allowed = ", ".join(sorted(SUPPORTED_BACKENDS))raise SystemExit(f"{prefix}_BACKEND must be one of: {allowed}")+ # The scope's model and effort apply to the Agent it routes to, so only+ # that backend's variables can set them.+ backend_prefix = f"{prefix}_{backend.upper()}" if backend else Nonereturn {"agent_name": backend or None,+ "model": _optional(f"{backend_prefix}_MODEL") if backend_prefix else None,+ "reasoning_effort": _optional(f"{backend_prefix}_REASONING_EFFORT") if backend_prefix else None,"opencode_agent": _optional(f"{prefix}_OPENCODE_AGENT"),- "opencode_model": _optional(f"{prefix}_OPENCODE_MODEL"),- "opencode_reasoning_effort": _optional(f"{prefix}_OPENCODE_REASONING_EFFORT"),"claude_agent": _optional(f"{prefix}_CLAUDE_AGENT"),- "claude_model": _optional(f"{prefix}_CLAUDE_MODEL"),"codex_agent": _optional(f"{prefix}_CODEX_AGENT"),- "codex_model": _optional(f"{prefix}_CODEX_MODEL"),- "codex_reasoning_effort": _optional(f"{prefix}_CODEX_REASONING_EFFORT"),}diff --git a/skills/use-avibe/SKILL.md b/skills/use-avibe/SKILL.mdindex eb95e76ce..2ec9b4984 100644--- a/skills/use-avibe/SKILL.md+++ b/skills/use-avibe/SKILL.md@@ -2,7 +2,7 @@name: use-avibeslug: use-avibedescription: Safely inspect and modify local Avibe configuration, routing, runtime settings, watches, scheduled tasks, Avibe Cloud remote access, and operational state. Also use it to report an Avibe bug, send product feedback, or file a feature request from the current conversation.-version: 0.8.0+version: 0.9.0---# Use Avibe@@ -36,8 +36,8 @@ Follow this skill as an operations playbook for agents, not as end-user marketin3. Preserve unrelated scopes, platforms, users, and secrets.4. Treat secrets as opaque. Do not print, invent, rotate, or overwrite tokens unless the user explicitly provides replacements.5. Use the smallest viable API call and verify by reading back the API response.-6. For `POST /settings`, preserve every existing channel for that platform; the endpoint replaces the platform's channel map.-7. For `POST /api/users`, merge each edited user with its current user payload first; missing user fields are not a patch.+6. Change one channel, topic, or DM user with `PATCH /api/settings/scope`, which writes only the named fields; `POST /api/settings` replaces the platform's whole channel map.+7. Change a bound DM user's fields with `PATCH /api/settings/scope` (`"scope": "user"`); `POST /api/users` writes each included user as a whole row.8. Make every persistent-state change through the Web UI API or the `vibe` CLI. Avibe's internal storage is opaque — do not read, query, or hand-edit it.9. `POST /config` persists the new payload but does not restart running platform adapters by itself. When the change is platform credentials, `proxy_url`, or other transport-level settings, plan an explicit restart afterwards; prefer the delayed CLI form (`vibe restart --delay-seconds 60`) when triggering it from inside an active conversation. The only credential save that restarts on its own is the WeChat QR-login completion through `POST /wechat/qr_login/poll`.10. Do not restart the service by default. Use `POST /doctor`, `GET /status`, and read-back checks first.@@ -56,7 +56,7 @@ Use this order when changing Avibe configuration:- Check liveness with `GET /health` or `GET /status`.2. Decide whether the request belongs in:- `POST /config` for global defaults, platform credentials, runtime config, agent defaults, UI config, remote-access provider settings, update policy, or global display toggles- - `POST /settings` for channel-level routing, working directory, visibility, enablement, and mention policy+ - `PATCH /api/settings/scope` for one channel's, topic's, or DM user's routing, working directory, visibility, enablement, and mention policy- `/api/users` and `/api/bind-codes` for DM user binding and user-scope settings- `/remote-access/*` for Avibe Cloud pairing and tunnel control- host backend config instead of Avibe when the request is OpenCode, Claude Code, or Codex native behaviordiff --git a/skills/use-avibe/references/api-client.md b/skills/use-avibe/references/api-client.mdindex a17c421ef..896cf2391 100644--- a/skills/use-avibe/references/api-client.md+++ b/skills/use-avibe/references/api-client.md@@ -44,7 +44,7 @@ Usage examples:export VIBE_UI_BASE="http://127.0.0.1:5123"python3 skills/use-avibe/scripts/vibe_api.py GET /health-python3 skills/use-avibe/scripts/vibe_api.py GET '/settings?platform=slack'+python3 skills/use-avibe/scripts/vibe_api.py GET '/api/settings?platform=slack'python3 skills/use-avibe/scripts/vibe_api.py POST /doctor '{}'python3 skills/use-avibe/scripts/vibe_api.py POST /config '{"show_duration":true}'python3 skills/use-avibe/scripts/vibe_api.py DELETE '/api/users/U123?platform=slack'@@ -52,35 +52,15 @@ python3 skills/use-avibe/scripts/vibe_api.py DELETE '/api/users/U123?platform=slPayload can be passed as inline JSON, as `@payload.json`, or as `-` to read JSON from stdin.-For scope updates, still fetch and merge first:+For a scope update, read the scope's `expected_agent_name`, then patch only the fields that change:```bashAPI_HELPER="skills/use-avibe/scripts/vibe_api.py"--python3 "$API_HELPER" GET '/settings?platform=slack' > /tmp/slack_settings.json-python3 - <<'PY'-import json-from pathlib import Path--settings = json.loads(Path("/tmp/slack_settings.json").read_text())-channels = settings.get("channels") or {}-channels["C123"] = {- **channels.get("C123", {}),- "enabled": True,- "show_message_types": channels.get("C123", {}).get("show_message_types") or ["assistant"],- "custom_cwd": channels.get("C123", {}).get("custom_cwd"),- "require_mention": channels.get("C123", {}).get("require_mention"),- "routing": {- **(channels.get("C123", {}).get("routing") or {}),- "agent_name": "codex",- "model": "gpt-5.4",- "reasoning_effort": "high",- "codex_model": "gpt-5.4",- "codex_reasoning_effort": "high",- },-}-Path("/tmp/slack_payload.json").write_text(json.dumps({"platform": "slack", "channels": channels}))-PY-python3 "$API_HELPER" POST /settings @/tmp/slack_payload.json-python3 "$API_HELPER" GET '/settings?platform=slack'+EXPECTED="$(python3 "$API_HELPER" GET '/api/settings?platform=slack' \+ | python3 -c 'import json,sys; print(json.dumps(((json.load(sys.stdin).get("channels") or {}).get("C123") or {}).get("expected_agent_name")))')"+python3 "$API_HELPER" PATCH /api/settings/scope "{+ \"platform\": \"slack\", \"scope\": \"channel\", \"id\": \"C123\",+ \"changes\": {\"enabled\": true, \"routing\": {\"agent_name\": \"codex\", \"model\": \"gpt-5.4\", \"reasoning_effort\": \"high\"}},+ \"expected_agent_name\": $EXPECTED+}"```diff --git a/skills/use-avibe/references/backends.md b/skills/use-avibe/references/backends.mdindex bd7c35b1a..23b0fcfaa 100644--- a/skills/use-avibe/references/backends.md+++ b/skills/use-avibe/references/backends.md@@ -33,7 +33,7 @@ Behavior notes:- OpenCode subagents are selected through `routing.opencode_agent` or through prefix routing such as `reviewer: ...`.- Claude subagents are selected through `routing.claude_agent` or prefix routing.- Codex subagents are selected through `routing.codex_agent` or prefix routing.-- Claude reasoning is selected through `routing.claude_reasoning_effort`; common values are `low`, `medium`, and `high`, and some models also allow `max`.+- A scope's model and reasoning are `routing.model` and `routing.reasoning_effort`, for whichever backend its Agent runs; Claude's common efforts are `low`, `medium`, and `high`, and some models also allow `max`.- If a Claude reasoning value is invalid for the chosen model, the API normalizes or drops that override and falls back to the backend default.## Subagent and Prefix Routingdiff --git a/skills/use-avibe/references/scopes-and-routing.md b/skills/use-avibe/references/scopes-and-routing.mdindex b39eb8661..279cab942 100644--- a/skills/use-avibe/references/scopes-and-routing.md+++ b/skills/use-avibe/references/scopes-and-routing.md@@ -1,20 +1,34 @@# Channels, Users, and Routing+### Changing one scope++`PATCH /api/settings/scope` changes only the fields it names on one channel, Telegram topic, or bound DM user. Use it for every single-scope edit:++```json+{+ "platform": "slack",+ "scope": "channel",+ "id": "C123",+ "changes": {+ "enabled": true,+ "routing": {"agent_name": "codex", "model": "gpt-5.4", "reasoning_effort": "high"}+ },+ "expected_agent_name": "<the scope's current expected_agent_name>"+}+```++- `scope` is `channel`, `thread` (Telegram topics only; add `"thread_id"`), or `user` (the user must already be bound).+- Channels and topics take `enabled`, `show_message_types`, `custom_cwd`, `require_mention`, `require_bind`, `routing`; users take `display_name`, `enabled`, `show_message_types`, `custom_cwd`, `routing`. Admin rights keep `POST /api/users/<user_id>/admin`.+- `routing` merges key by key into the stored route. A request with `routing` must carry `expected_agent_name`: copy it from the scope's latest read (`null` for a scope inheriting the default Agent). If another writer changed the scope's Agent since, the request fails with `settings_conflict` (409); read again and retry.+- The response's `settings` is the stored row; verify from it.+### Channel settings-- `GET /settings?platform=<platform>`+- `GET /api/settings?platform=<platform>`- returns channel settings, user settings, and bind codes for one platform-- `POST /settings`+- `POST /api/settings`- payload: `{"platform": "<platform>", "channels": {...}}`- - validates message visibility and routing, normalizes Claude reasoning, persists the full channel map for that platform--Important: `POST /settings` replaces the entire `channels` map for the selected platform. To change one channel:--1. `GET /settings?platform=<platform>`-2. copy `response.channels`-3. merge or add one channel entry-4. `POST /settings` with the full merged `channels` object-5. `GET /settings?platform=<platform>` again and verify+ - replaces the entire `channels` map for that platform; keep it for bulk imports and use `PATCH /api/settings/scope` for anything elseChannel entry shape:@@ -30,15 +44,10 @@ Channel entry shape:"model": "gpt-5.4","reasoning_effort": "high","opencode_agent": null,- "opencode_model": null,- "opencode_reasoning_effort": null,"claude_agent": null,- "claude_model": null,- "claude_reasoning_effort": null,- "codex_agent": "reviewer",- "codex_model": "gpt-5.4",- "codex_reasoning_effort": "high"- }+ "codex_agent": "reviewer"+ },+ "expected_agent_name": "codex"}```@@ -50,10 +59,11 @@ Field meanings:- `require_mention`: `null` inherits the platform default, `true` requires mention, `false` disables mention gating for that channel- `require_bind`: `null`/`false` lets any channel member use the bot (current default); `true` gates the channel to bound users only — messages from unbound senders are silently ignored (no denial reply), while the bot's own replies stay visible to everyone. Enforced in the shared auth pipeline, so it applies on every platform. Bind is platform-wide, so `require_bind` means "is this sender a bound user", not a per-channel allowlist.- `routing.agent_name`: Vibe Agent name for this scope, or `null` to inherit the default Agent-- `routing.model`: canonical scope-level model override for the selected Agent backend-- `routing.reasoning_effort`: canonical scope-level reasoning override for the selected Agent backend-- `routing.<backend>_agent`: backend-specific subagent-- `routing.<backend>_model` / `routing.<backend>_reasoning_effort`: legacy aliases accepted on input and derived on read-back; do not treat them as independent state+- `routing.model`: scope-level model override for the selected Agent; `null` uses the Agent's own model+- `routing.reasoning_effort`: scope-level reasoning override for the selected Agent; `null` uses the Agent's own+- `routing.<backend>_agent`: the native subagent that backend runs for this scope+- `expected_agent_name` (read-only): the Agent this view of the route is based on; send it back with routing changes+- Older releases also used `routing.<backend>_model` / `routing.<backend>_reasoning_effort`. They are retired: never returned or stored, and only read to fill an unset `model` / `reasoning_effort` on that built-in backend's route. Do not send them.### DM users and bind codes@@ -61,7 +71,7 @@ Field meanings:- returns bound DM users for one platform- `POST /api/users`- payload: `{"platform": "<platform>", "users": {...}}`- - merges included users into existing users and preserves each existing user's `dm_chat_id`+ - writes each included user as a whole row and keeps the others; use `PATCH /api/settings/scope` with `"scope": "user"` to change a user's fields- `POST /api/users/<user_id>/admin`- payload: `{"platform": "<platform>", "is_admin": true}`- `DELETE /api/users/<user_id>?platform=<platform>`@@ -75,7 +85,7 @@ Field meanings:- `GET /api/setup/first-bind-code`- returns an existing valid setup bind code or creates a new one-time code-Important: user updates are not field patches. Before changing a user's routing, cwd, visibility, or enabled flag, read the current user object and send the merged full user entry.+Change a user's routing, cwd, visibility, or enabled flag with `PATCH /api/settings/scope` (`"scope": "user"`); `POST /api/users` is not a field patch.User entry shape:@@ -92,15 +102,10 @@ User entry shape:"model": "claude-sonnet-4-6","reasoning_effort": "high","opencode_agent": null,- "opencode_model": null,- "opencode_reasoning_effort": null,"claude_agent": "reviewer",- "claude_model": "claude-sonnet-4-6",- "claude_reasoning_effort": "high",- "codex_agent": null,- "codex_model": null,- "codex_reasoning_effort": null- }+ "codex_agent": null+ },+ "expected_agent_name": "claude"}```@@ -113,7 +118,7 @@ DM caveat: current DM authorization checks whether the user is bound, not whetheAgent resolution priority is:1. existing Agent Session backend snapshot, when the message belongs to an existing session/thread-2. scope-level `routing.agent_name` from `/settings` or `/api/users`, for new sessions+2. scope-level `routing.agent_name` of the channel, topic, or DM user, for new sessions3. global default Vibe Agent from the Agent catalog4. registered backend compatibility fallback, only when no enabled default Agent is available@@ -154,39 +159,32 @@ Goal:API flow:-1. `GET /settings?platform=slack`-2. merge `channels.C123`-3. `POST /settings` with all Slack channels-4. read back `GET /settings?platform=slack`--Merged channel entry:+1. `GET /api/settings?platform=slack` and note `channels.C123.expected_agent_name` (`null` when the channel has no row yet)+2. `PATCH /api/settings/scope` with that `expected_agent_name`:```json{- "enabled": true,- "show_message_types": ["assistant"],- "custom_cwd": null,- "require_mention": null,- "routing": {- "agent_name": "codex",- "model": "gpt-5.4",- "reasoning_effort": "high",- "opencode_agent": null,- "opencode_model": null,- "opencode_reasoning_effort": null,- "claude_agent": null,- "claude_model": null,- "claude_reasoning_effort": null,- "codex_agent": "reviewer",- "codex_model": "gpt-5.4",- "codex_reasoning_effort": "high"- }+ "platform": "slack",+ "scope": "channel",+ "id": "C123",+ "changes": {+ "enabled": true,+ "routing": {+ "agent_name": "codex",+ "codex_agent": "reviewer",+ "model": "gpt-5.4",+ "reasoning_effort": "high"+ }+ },+ "expected_agent_name": null}```+3. verify the response's `settings.routing`+### Route one channel to OpenCode with a subagent-Use `/settings` and set:+Use `PATCH /api/settings/scope` and set:- `routing.agent_name = "opencode"`- `routing.opencode_agent = "<agent>"`@@ -197,7 +195,7 @@ If the user wants OpenCode-native defaults, providers, MCP servers, skills, plug### Route one scope to Claude with model and reasoning-Use `/settings` for a channel or `/api/users` for a DM user and set:+Use `PATCH /api/settings/scope` (`"scope": "channel"` or `"user"`) and set:- `routing.agent_name = "claude"`- `routing.claude_agent = "<agent>"` if requested@@ -208,7 +206,7 @@ The API normalizes Claude reasoning for incompatible model combinations; verify### Show tool execution messages in one channel-Use `/settings` and add `toolcall` to the target channel's `show_message_types`.+Use `PATCH /api/settings/scope` with the target channel's `show_message_types` plus `toolcall`.Preserve existing `system` and `assistant` values unless the user asked for a full replacement.diff --git a/storage/settings_service.py b/storage/settings_service.pyindex 0fd59bede..69d014af6 100644--- a/storage/settings_service.py+++ b/storage/settings_service.py@@ -21,8 +21,10 @@ from config.v2_settings import (_make_scoped_key,_split_scoped_key,make_thread_native_id,+ LEGACY_ROUTING_ALIASES,normalize_routing_settings,normalize_show_message_types,+ routing_from_stored_payload,split_thread_native_id,)from storage.agent_session_rows import reserve_write_lock@@ -693,19 +695,9 @@ def _active_routing_variant(routing: RoutingSettings) -> str | None:def _routing_from_row(row: dict[str, Any], payload: dict[str, Any]) -> RoutingSettings:routing_payload = payload.get("routing") or {}- routing = RoutingSettings(- agent_name=routing_payload.get("agent_name") or routing_payload.get("agent"),- model=routing_payload.get("model") or routing_payload.get("model_override"),- reasoning_effort=routing_payload.get("reasoning_effort") or routing_payload.get("reasoning_effort_override"),- opencode_agent=routing_payload.get("opencode_agent"),- opencode_model=routing_payload.get("opencode_model"),- opencode_reasoning_effort=routing_payload.get("opencode_reasoning_effort"),- claude_agent=routing_payload.get("claude_agent"),- claude_model=routing_payload.get("claude_model"),- claude_reasoning_effort=routing_payload.get("claude_reasoning_effort"),- codex_agent=routing_payload.get("codex_agent"),- codex_model=routing_payload.get("codex_model"),- codex_reasoning_effort=routing_payload.get("codex_reasoning_effort"),+ aliases = {key: value for key, value in routing_payload.items() if key in LEGACY_ROUTING_ALIASES}+ routing = routing_from_stored_payload(+ {key: value for key, value in routing_payload.items() if key not in LEGACY_ROUTING_ALIASES})stored_agent_name = row.get("agent_name")if stored_agent_name:@@ -722,6 +714,11 @@ def _routing_from_row(row: dict[str, Any], payload: dict[str, Any]) -> RoutingSerouting.claude_agent = routing.claude_agent or variantelif routing.agent_name == "opencode":routing.opencode_agent = routing.opencode_agent or variant+ # A row an older release wrote may carry its model or effort only in a+ # retired per-backend alias; the payload and the columns come first.+ lifted = routing_from_stored_payload({**aliases, "agent_name": routing.agent_name})+ routing.model = routing.model or lifted.model+ routing.reasoning_effort = routing.reasoning_effort or lifted.reasoning_effortreturn routingdiff --git a/tests/test_controller_vibe_agent_routing.py b/tests/test_controller_vibe_agent_routing.pyindex 1bcc72f61..ad489e0a3 100644--- a/tests/test_controller_vibe_agent_routing.py+++ b/tests/test_controller_vibe_agent_routing.py@@ -113,14 +113,12 @@ def test_resolve_agent_for_context_reports_unregistered_default_agent_backend()assert controller.resolve_agent_for_context(_context()) == "opencode"-def test_codex_overrides_prefer_scope_level_model_and_reasoning() -> None:+def test_codex_overrides_use_the_scope_level_model_and_reasoning() -> None:controller = _StubController()controller.primary_platform = "slack"controller._get_settings_key = lambda context: context.channel_idrouting = SimpleNamespace(codex_agent=None,- codex_model="gpt-5.4",- codex_reasoning_effort="high",model="gpt-5.5",reasoning_effort="xhigh",)diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex 4c03b9d09..494b13bfa 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -811,8 +811,6 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):"reasoning_effort": "max","opencode_agent": None,"claude_agent": None,- "claude_model": None,- "claude_reasoning_effort": None,"codex_agent": None,},)()diff --git a/tests/test_prepare_regression.py b/tests/test_prepare_regression.pyindex 10e1a8bb5..45d241e12 100644--- a/tests/test_prepare_regression.py+++ b/tests/test_prepare_regression.py@@ -128,6 +128,23 @@ def test_prepare_generates_unified_state(tmp_path: Path, monkeypatch: pytest.Monassert opencode_config["provider"]["openai"]["options"]["baseURL"] == "https://ai-relay.example/v1"+def test_prepare_routes_a_scope_model_only_for_its_own_backend(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ module = _load_module()+ _set_required_env(monkeypatch)+ monkeypatch.setenv("REGRESSION_DISCORD_CODEX_MODEL", "gpt-5.5")+ monkeypatch.setenv("REGRESSION_DISCORD_CODEX_REASONING_EFFORT", "high")+ monkeypatch.setenv("REGRESSION_DISCORD_CLAUDE_MODEL", "claude-opus-4-8")++ module.prepare(tmp_path)++ settings = json.loads((tmp_path / "home" / ".avibe" / "state" / "settings.json").read_text(encoding="utf-8"))+ routing = settings["scopes"]["channel"]["discord"]["123456789012345678"]["routing"]+ assert routing["agent_name"] == "codex"+ assert routing["model"] == "gpt-5.5"+ assert routing["reasoning_effort"] == "high"+ assert not {"codex_model", "codex_reasoning_effort", "claude_model"} & set(routing)++def test_prepare_derives_openai_relay_base_from_anthropic_base(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/test_prompt_studio_catalog.py b/tests/test_prompt_studio_catalog.pyindex 35a47fba5..bfee44ad3 100644--- a/tests/test_prompt_studio_catalog.py+++ b/tests/test_prompt_studio_catalog.py@@ -171,7 +171,13 @@ def test_use_avibe_entry_routes_to_all_bundled_references() -> None:assert set(targets) == {path.relative_to(directory).as_posix() for path in (directory / "references").glob("*.md")}assert all((directory / target).is_file() for target in targets)assert (directory / "scripts/vibe_api.py").is_file()- for rule in ("preserve every existing channel", "missing user fields are not a patch", "Do not restart", "Treat secrets as opaque"):+ for rule in (+ "`PATCH /api/settings/scope`, which writes only the named fields",+ "replaces the platform's whole channel map",+ "writes each included user as a whole row",+ "Do not restart",+ "Treat secrets as opaque",+ ):assert rule in entrydiff --git a/tests/test_route_menu.py b/tests/test_route_menu.pyindex 1e18b9adf..fef0849dc 100644--- a/tests/test_route_menu.py+++ b/tests/test_route_menu.py@@ -88,9 +88,6 @@ def test_the_stored_route_shows_only_on_its_own_agent():assert data.stored_draft("a-reviewer") == RouteDraft("builder", None, None)assert data.stored_draft("a-claude") == RouteDraft("helper", None, None)assert data.stored_draft("a-vibey") == RouteDraft()- # A route saved by an older release with backend-specific fields reads the same.- legacy = RoutingSettings(agent_name="codex", codex_model="gpt-5.6", codex_reasoning_effort="high")- assert RoutingModalData(_agents(), "a-codex", legacy).stored_draft("a-codex") == RouteDraft(None, "gpt-5.6", "high")def test_default_options_inherit_the_chosen_agents_own_model_and_effort():diff --git a/tests/test_scope_settings_patch.py b/tests/test_scope_settings_patch.pyindex c368ef5e7..fb71c5346 100644--- a/tests/test_scope_settings_patch.py+++ b/tests/test_scope_settings_patch.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport pytest-from config.v2_settings import ChannelSettings, RoutingSettings, SettingsStore, UserSettings+from config.v2_settings import LEGACY_ROUTING_ALIASES, ChannelSettings, RoutingSettings, SettingsStore, UserSettingsfrom core.vibe_agents import VibeAgentStorefrom storage.settings_service import ScopeAgentUnavailableError, StaleScopeAgentBindingErrorfrom vibe import api@@ -91,6 +91,37 @@ def test_a_routing_edit_names_the_agent_its_view_was_based_on(store, stored_agenassert result["expected_agent_name"] == outcome[0]+ ("routing", "outcome"),+ [+ # A page from an older release clears every retired alias beside its edit.+ ({"model": "m1", "reasoning_effort": None, "codex_model": None, "claude_reasoning_effort": None},+ ("m1", None)),+ # An older API caller names the model only by the route's own alias...+ ({"codex_model": "m2", "codex_reasoning_effort": "high"}, ("m2", "high")),+ # ...which never overrides a canonical field the edit names.+ ({"model": "m1", "codex_model": "m2"}, ("m1", None)),+ # Another backend's alias applies to no field of this route.+ ({"claude_model": "m2"}, ("m0", None)),+ ],+)+def test_a_routing_edit_still_reads_retired_aliases_but_never_stores_them(store, routing, outcome):+ agents = VibeAgentStore()+ agents.create(name="codex", backend="codex")+ agents.close()+ store.set_channels_for_platform("slack", {+ "A": ChannelSettings(enabled=True, routing=RoutingSettings(agent_name="codex", model="m0")),+ })+ store.save()++ result = _patch("channel", "A", {"routing": routing}, expected_agent_name="codex")["settings"]["routing"]++ assert (result["agent_name"], result["model"], result["reasoning_effort"]) == ("codex", *outcome)+ assert not LEGACY_ROUTING_ALIASES & set(result)+ saved = SettingsStore.get_instance().find_channel("A", platform="slack").routing+ assert (saved.model, saved.reasoning_effort) == outcome++def test_a_topic_override_starts_from_its_channel(store, monkeypatch):monkeypatch.setattr(api, "_stored_platform_config", lambda _platform: type("Config", (), {"require_mention": False}))store.set_channels_for_platform("telegram", {diff --git a/tests/test_settings_handler.py b/tests/test_settings_handler.pyindex 67485b6b2..eb81084b1 100644--- a/tests/test_settings_handler.py+++ b/tests/test_settings_handler.py@@ -184,8 +184,8 @@ def test_handle_routing_update_preserves_existing_codex_agent_when_omitted() ->RoutingSettings(agent_name="codex",codex_agent="reviewer",- codex_model="gpt-5.4-mini",- codex_reasoning_effort="low",+ model="gpt-5.4-mini",+ reasoning_effort="low",))handler, send_message = _make_handler(settings_manager)@@ -206,8 +206,6 @@ def test_handle_routing_update_preserves_existing_codex_agent_when_omitted() ->assert settings_manager.saved_routing.codex_agent == "reviewer"assert settings_manager.saved_routing.model == "gpt-5.4"assert settings_manager.saved_routing.reasoning_effort == "high"- assert settings_manager.saved_routing.codex_model is None- assert settings_manager.saved_routing.codex_reasoning_effort is Nonesend_message.assert_not_awaited()@@ -216,8 +214,8 @@ def test_handle_routing_update_allows_explicit_codex_agent_clear() -> None:RoutingSettings(agent_name="codex",codex_agent="reviewer",- codex_model="gpt-5.4-mini",- codex_reasoning_effort="low",+ model="gpt-5.4-mini",+ reasoning_effort="low",))handler, _ = _make_handler(settings_manager)@@ -239,8 +237,6 @@ def test_handle_routing_update_allows_explicit_codex_agent_clear() -> None:assert settings_manager.saved_routing.codex_agent is Noneassert settings_manager.saved_routing.model == "gpt-5.4"assert settings_manager.saved_routing.reasoning_effort == "high"- assert settings_manager.saved_routing.codex_model is None- assert settings_manager.saved_routing.codex_reasoning_effort is Nonedef test_handle_routing_update_handles_first_codex_save_without_existing_routing() -> None:@@ -264,8 +260,6 @@ def test_handle_routing_update_handles_first_codex_save_without_existing_routingassert settings_manager.saved_routing.codex_agent is Noneassert settings_manager.saved_routing.model == "gpt-5.4"assert settings_manager.saved_routing.reasoning_effort == "high"- assert settings_manager.saved_routing.codex_model is None- assert settings_manager.saved_routing.codex_reasoning_effort is Nonesend_message.assert_not_awaited()diff --git a/tests/test_sqlite_settings_store.py b/tests/test_sqlite_settings_store.pyindex 98db09f09..64bc915f1 100644--- a/tests/test_sqlite_settings_store.py+++ b/tests/test_sqlite_settings_store.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport jsonfrom concurrent.futures import ThreadPoolExecutor+from dataclasses import fieldsfrom pathlib import Pathimport pytest@@ -983,69 +984,56 @@ def test_settings_save_preserves_observed_scope_metadata(tmp_path: Path) -> Noneassert json.loads(row["metadata_json"]) == {"username": "general"}-def test_settings_save_does_not_migrate_legacy_model_fields_without_backend(tmp_path: Path) -> None:+ ("agent_name", "payload", "columns", "expected"),+ [+ # Only the retired alias holds the selection: it fills the route.+ ("claude", {"claude_model": "claude-opus-4-8", "claude_reasoning_effort": "max"}, (None, None),+ ("claude-opus-4-8", "max")),+ # The canonical payload value wins over a stale alias.+ ("claude", {"model": "claude-sonnet-4-6", "claude_model": "claude-opus-4-8"}, (None, None),+ ("claude-sonnet-4-6", None)),+ # So do the columns, which every release since the aliases wrote.+ ("claude", {"claude_model": "claude-opus-4-8"}, ("claude-sonnet-4-6", "high"),+ ("claude-sonnet-4-6", "high")),+ # Another backend's alias, or one on an inheriting route, applies to no Agent.+ ("codex", {"claude_model": "claude-opus-4-8"}, (None, None), (None, None)),+ (None, {"codex_model": "gpt-5.5", "codex_reasoning_effort": "high"}, (None, None), (None, None)),+ ],+)+def test_settings_load_lifts_a_retired_alias_only_for_its_own_agent(+ tmp_path: Path,+ agent_name: str | None,+ payload: dict,+ columns: tuple[str | None, str | None],+ expected: tuple[str | None, str | None],+) -> None:db_path = tmp_path / "vibe.sqlite"run_migrations(db_path)service = SQLiteSettingsService(db_path)try:service.save_state(SettingsState(- channels={- "slack::C123": ChannelSettings(- enabled=True,- routing=RoutingSettings(- agent_name=None,- codex_model="gpt-stale-codex",- claude_model="claude-stale",- opencode_model="openai/stale",- codex_reasoning_effort="high",- claude_reasoning_effort="medium",- opencode_reasoning_effort="low",- ),- ),- }+ channels={"slack::C123": ChannelSettings(enabled=True, routing=RoutingSettings(agent_name=agent_name))}))-- state = service.load_state()- finally:- service.close()-- routing = state.channels["slack::C123"].routing- assert routing.model is None- assert routing.reasoning_effort is None- assert routing.codex_model == "gpt-stale-codex"- assert routing.claude_model == "claude-stale"- assert routing.opencode_model == "openai/stale"---def test_settings_save_lifts_backend_aliases_for_builtin_agent_name(tmp_path: Path) -> None:- db_path = tmp_path / "vibe.sqlite"- run_migrations(db_path)- service = SQLiteSettingsService(db_path)- try:- service.save_state(- SettingsState(- channels={- "slack::C123": ChannelSettings(- enabled=True,- routing=RoutingSettings(- agent_name="claude",- claude_model="claude-opus-4-8",- claude_reasoning_effort="max",- ),- ),- }+ with service.engine.begin() as conn:+ conn.execute(+ scope_settings.update()+ .where(scope_settings.c.scope_id == "slack::channel::C123")+ .values(+ settings_json=json.dumps({"routing": {"agent_name": agent_name, **payload}}),+ model=columns[0],+ reasoning_effort=columns[1],+ ))- )- state = service.load_state()+ routing = service.load_state().channels["slack::C123"].routingfinally:service.close()- routing = state.channels["slack::C123"].routing- assert routing.model == "claude-opus-4-8"- assert routing.reasoning_effort == "max"+ assert (routing.model, routing.reasoning_effort) == expected+ assert v2_settings.routing_to_dict(routing).keys() == {field.name for field in fields(RoutingSettings)}def test_settings_save_stores_only_active_builtin_agent_variant(tmp_path: Path) -> None:diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex fcdd46c8a..0b98d6310 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -23,7 +23,13 @@ from sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.schema import CreateIndexfrom config import paths-from config.v2_settings import ChannelSettings, RoutingSettings, SettingsState, SettingsStore+from config.v2_settings import (+ LEGACY_ROUTING_ALIASES,+ ChannelSettings,+ RoutingSettings,+ SettingsState,+ SettingsStore,+)from storage.db import SqliteInvalidationProbe, create_sqlite_enginefrom storage.importer import JSON_IMPORT_MARKER, ensure_sqlite_state, reset_ensured_sqlite_statefrom storage.lock import migration_lock_path_for@@ -6448,7 +6454,19 @@ def test_ensure_sqlite_state_import_skips_agent_name_conflict(tmp_path: Path) ->assert codex_rows == 1-def test_ensure_sqlite_state_preserves_backend_aliases_without_deprecated_backend(tmp_path: Path) -> None:+ ("agent_name", "expected"),+ [+ # The retired alias of the route's own built-in Agent fills the empty+ # canonical fields.+ ("claude", ("claude-opus-4-8", "max")),+ # Inheriting the default Agent: no backend owns the alias.+ (None, (None, None)),+ ],+)+def test_a_stored_route_with_retired_aliases_loads_canonical_and_saves_without_them(+ tmp_path: Path, agent_name: str | None, expected: tuple[str | None, str | None]+) -> None:state_dir = tmp_path / "state"state_dir.mkdir()db_path = state_dir / "vibe.sqlite"@@ -6459,77 +6477,28 @@ def test_ensure_sqlite_state_preserves_backend_aliases_without_deprecated_backenservice.save_state(SettingsState(channels={- "slack::C123": ChannelSettings(- enabled=True,- routing=RoutingSettings(- claude_model="claude-opus-4-8",- claude_reasoning_effort="max",- ),- ),+ "slack::C123": ChannelSettings(enabled=True, routing=RoutingSettings(agent_name=agent_name)),}))finally:service.close()+ # The row an older release wrote: canonical fields empty, the selection+ # only in its per-backend alias.+ legacy_routing = {+ "agent_name": agent_name,+ "model": None,+ "reasoning_effort": None,+ "claude_model": "claude-opus-4-8",+ "claude_reasoning_effort": "max",+ "codex_model": "gpt-5.5",+ }with sqlite3.connect(db_path) as conn:conn.execute(- "insert into state_meta (key, value_json, updated_at) values (?, ?, ?)",- (JSON_IMPORT_MARKER, '"2026-05-01T00:00:00+00:00"', "2026-05-01T00:00:00+00:00"),+ "update scope_settings set settings_json = ? where scope_id = ?",+ (json.dumps({"routing": legacy_routing}), "slack::channel::C123"),)- conn.commit()-- first = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")- # Drop the process-local "already ensured" result so the second call really- # replays the pipeline against the migrated database, the way the next- # process to start will. Without the reset this would assert the- # short-circuit (covered separately) instead of re-run idempotence.- reset_ensured_sqlite_state()- second = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")-- with sqlite3.connect(db_path) as conn:- row = conn.execute(- "select agent_backend, model, reasoning_effort, settings_json from scope_settings where scope_id = ?",- ("slack::channel::C123",),- ).fetchone()-- routing = json.loads(row[3])["routing"]- assert row[:3] == (None, None, None)- assert routing["model"] is None- assert routing["reasoning_effort"] is None- assert routing["claude_model"] == "claude-opus-4-8"- assert routing["claude_reasoning_effort"] == "max"- assert "routing_scope_settings_migrated" not in first.counts- assert "routing_scope_settings_migrated" not in second.counts---def test_ensure_sqlite_state_keeps_canonical_scope_routing_with_stale_alias(tmp_path: Path) -> None:- state_dir = tmp_path / "state"- state_dir.mkdir()- db_path = state_dir / "vibe.sqlite"- run_migrations(db_path)-- service = SQLiteSettingsService(db_path)- try:- service.save_state(- SettingsState(- channels={- "slack::C123": ChannelSettings(- enabled=True,- routing=RoutingSettings(- model="claude-sonnet-4-6",- reasoning_effort="high",- claude_model="claude-opus-4-8",- claude_reasoning_effort="max",- ),- ),- }- )- )- finally:- service.close()-- with sqlite3.connect(db_path) as conn:conn.execute("insert into state_meta (key, value_json, updated_at) values (?, ?, ?)",(JSON_IMPORT_MARKER, '"2026-05-01T00:00:00+00:00"', "2026-05-01T00:00:00+00:00"),@@ -6538,91 +6507,28 @@ def test_ensure_sqlite_state_keeps_canonical_scope_routing_with_stale_alias(tmp_ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")- with sqlite3.connect(db_path) as conn:- row = conn.execute(- "select model, reasoning_effort, settings_json from scope_settings where scope_id = ?",- ("slack::channel::C123",),- ).fetchone()-- routing = json.loads(row[2])["routing"]- assert row[:2] == ("claude-sonnet-4-6", "high")- assert routing["model"] == "claude-sonnet-4-6"- assert routing["reasoning_effort"] == "high"- assert routing["claude_model"] == "claude-opus-4-8"- assert routing["claude_reasoning_effort"] == "max"---def test_ensure_sqlite_state_preserves_legacy_routing_without_backend(tmp_path: Path) -> None:- state_dir = tmp_path / "state"- state_dir.mkdir()- db_path = state_dir / "vibe.sqlite"- run_migrations(db_path)-- service = SQLiteSettingsService(db_path)- try:- service.save_state(- SettingsState(- channels={- "slack::C123": ChannelSettings(- enabled=True,- routing=RoutingSettings(- claude_model="claude-opus-4-8",- claude_reasoning_effort="max",- ),- ),- }- )- )- finally:- service.close()-- with sqlite3.connect(db_path) as conn:- conn.execute(- "insert into state_meta (key, value_json, updated_at) values (?, ?, ?)",- (JSON_IMPORT_MARKER, '"2026-05-01T00:00:00+00:00"', "2026-05-01T00:00:00+00:00"),- )- conn.commit()-- result = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")-- with sqlite3.connect(db_path) as conn:- row = conn.execute(- "select agent_backend, model, reasoning_effort, settings_json from scope_settings where scope_id = ?",- ("slack::channel::C123",),- ).fetchone()-- routing = json.loads(row[3])["routing"]- assert row[:3] == (None, None, None)- assert routing["model"] is None- assert routing["reasoning_effort"] is None- assert routing["claude_model"] == "claude-opus-4-8"- assert routing["claude_reasoning_effort"] == "max"- assert "routing_scope_settings_migrated" not in result.counts-store = SettingsStore(state_dir / "settings.json")try:channel = store.find_channel("C123", platform="slack")assert channel is not None- assert channel.routing.model is None- assert channel.routing.reasoning_effort is None- assert channel.routing.claude_model == "claude-opus-4-8"- assert channel.routing.claude_reasoning_effort == "max"- store.update_channel("C999", ChannelSettings(enabled=True), platform="slack")+ assert (channel.routing.model, channel.routing.reasoning_effort) == expected+ assert not any(hasattr(channel.routing, alias) for alias in LEGACY_ROUTING_ALIASES)+ channel.custom_cwd = "/repo"+ store.update_channel("C123", channel, platform="slack")finally:store.close()with sqlite3.connect(db_path) as conn:- roundtrip_row = conn.execute(- "select agent_backend, model, reasoning_effort, settings_json from scope_settings where scope_id = ?",+ row = conn.execute(+ "select model, reasoning_effort, settings_json from scope_settings where scope_id = ?",("slack::channel::C123",),).fetchone()- roundtrip_routing = json.loads(roundtrip_row[3])["routing"]- assert roundtrip_row[:3] == (None, None, None)- assert roundtrip_routing["model"] is None- assert roundtrip_routing["reasoning_effort"] is None- assert roundtrip_routing["claude_model"] == "claude-opus-4-8"- assert roundtrip_routing["claude_reasoning_effort"] == "max"+ routing = json.loads(row[2])["routing"]+ assert (routing["model"], routing["reasoning_effort"]) == expected+ assert not LEGACY_ROUTING_ALIASES & set(routing)+ if agent_name:+ assert row[:2] == expecteddef test_ensure_sqlite_state_imports_background_json(tmp_path: Path) -> None:diff --git a/tests/test_ui_api.py b/tests/test_ui_api.pyindex 4df46dced..e9b0e5507 100644--- a/tests/test_ui_api.py+++ b/tests/test_ui_api.py@@ -24,7 +24,7 @@ from config.v2_config import (V2Config,)from config import paths-from config.v2_settings import ChannelSettings, SettingsStore+from config.v2_settings import LEGACY_ROUTING_ALIASES, ChannelSettings, SettingsStorefrom core.vibe_agents import VibeAgentStorefrom core import chat_discoveryfrom core.services import scope_settings@@ -1450,8 +1450,7 @@ def test_normalize_scope_routing_prefers_canonical_claude_overrides() -> None:assert result["model"] == "claude-opus-4-8"assert result["reasoning_effort"] == "high"- assert result["claude_model"] is None- assert result["claude_reasoning_effort"] is None+ assert not LEGACY_ROUTING_ALIASES & set(result)def test_normalize_scope_routing_prefers_canonical_over_round_trip_aliases() -> None:@@ -1467,8 +1466,7 @@ def test_normalize_scope_routing_prefers_canonical_over_round_trip_aliases() ->assert result["model"] == "claude-sonnet-4-6"assert result["reasoning_effort"] == "high"- assert result["claude_model"] is None- assert result["claude_reasoning_effort"] is None+ assert not LEGACY_ROUTING_ALIASES & set(result)def test_normalize_scope_routing_lifts_aliases_for_builtin_agent_name() -> None:@@ -1482,6 +1480,7 @@ def test_normalize_scope_routing_lifts_aliases_for_builtin_agent_name() -> None:assert result["model"] == "claude-opus-4-8"assert result["reasoning_effort"] == "max"+ assert not LEGACY_ROUTING_ALIASES & set(result)def test_normalize_scope_routing_preserves_explicit_canonical_clears() -> None:@@ -1497,37 +1496,26 @@ def test_normalize_scope_routing_preserves_explicit_canonical_clears() -> None:assert result["model"] is Noneassert result["reasoning_effort"] is None- assert result["claude_model"] is None- assert result["claude_reasoning_effort"] is None+ assert not LEGACY_ROUTING_ALIASES & set(result)-def test_normalize_scope_routing_ignores_deprecated_backend_for_alias_lifting() -> None:- result = scope_settings.normalize_scope_routing(- {- "agent_backend": "claude",- "claude_model": "claude-opus-4-8",- "claude_reasoning_effort": "max",- }- )-- assert result["model"] is None- assert result["reasoning_effort"] is None- assert result["claude_model"] == "claude-opus-4-8"- assert result["claude_reasoning_effort"] == "max"---def test_normalize_scope_routing_preserves_legacy_overrides_without_backend() -> None:- result = scope_settings.normalize_scope_routing(- {- "claude_model": "claude-opus-4-8",- "claude_reasoning_effort": "max",- }- )+ "routing",+ [+ # A deprecated backend key is not an Agent the alias could apply to.+ {"agent_backend": "claude", "claude_model": "claude-opus-4-8", "claude_reasoning_effort": "max"},+ # Inheriting the default Agent: no backend owns the alias.+ {"claude_model": "claude-opus-4-8", "claude_reasoning_effort": "max"},+ # Another backend's alias.+ {"agent_name": "codex", "claude_model": "claude-opus-4-8", "claude_reasoning_effort": "max"},+ ],+)+def test_normalize_scope_routing_drops_aliases_the_route_cannot_apply(routing: dict) -> None:+ result = scope_settings.normalize_scope_routing(routing)assert result["model"] is Noneassert result["reasoning_effort"] is None- assert result["claude_model"] == "claude-opus-4-8"- assert result["claude_reasoning_effort"] == "max"+ assert not LEGACY_ROUTING_ALIASES & set(result)@pytest.mark.parametrize("surface", ["channel", "user", "thread", "im"])diff --git a/ui/src/components/shared/RoutingConfigPanel.tsx b/ui/src/components/shared/RoutingConfigPanel.tsxindex b96a0b841..50c5f4b58 100644--- a/ui/src/components/shared/RoutingConfigPanel.tsx+++ b/ui/src/components/shared/RoutingConfigPanel.tsx@@ -24,14 +24,8 @@ export interface RoutingConfigValue {model?: string | null;reasoning_effort?: string | null;opencode_agent?: string | null;- opencode_model?: string | null;- opencode_reasoning_effort?: string | null;claude_agent?: string | null;- claude_model?: string | null;- claude_reasoning_effort?: string | null;codex_agent?: string | null;- codex_model?: string | null;- codex_reasoning_effort?: string | null;};show_message_types: string[];require_mention?: boolean | null;@@ -101,18 +95,6 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({const selectedVibeAgent = vibeAgents.find((agent) => agent.name === value.routing.agent_name) || null;const defaultVibeAgent = vibeAgents.find((agent) => agent.name === defaultAgentName) || null;- // Picking an agent re-seeds model/effort, so always clear the deprecated- // per-backend overrides on any route change (kept for back-compat on read).- const clearLegacyOverrides = (routing: RoutingConfigValue['routing']) => ({- ...routing,- opencode_model: null,- opencode_reasoning_effort: null,- claude_model: null,- claude_reasoning_effort: null,- codex_model: null,- codex_reasoning_effort: null,- });-// Access row: working dir (+ optional require_mention / require_bind for// channels). The Agent route picker lives in the row below.const accessGridCols = showRequireMention ? 'md:grid-cols-3' : 'md:grid-cols-1';@@ -224,7 +206,7 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({if ('agent_name' in patch) next.agent_name = patch.agent_name ?? null;if ('model' in patch) next.model = patch.model ?? null;if ('reasoning_effort' in patch) next.reasoning_effort = patch.reasoning_effort ?? null;- onChange({ routing: clearLegacyOverrides(next) });+ onChange({ routing: next });}}defaultLabel={defaultVibeAgent ? `${t('common.default')} · ${defaultVibeAgent.name}` : t('common.default')diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsxindex 82048d2ca..858f1bb93 100644--- a/ui/src/components/steps/ChannelList.tsx+++ b/ui/src/components/steps/ChannelList.tsx@@ -67,14 +67,8 @@ export interface ChannelConfig {model?: string | null;reasoning_effort?: string | null;opencode_agent?: string | null;- opencode_model?: string | null;- opencode_reasoning_effort?: string | null;claude_agent?: string | null;- claude_model?: string | null;- claude_reasoning_effort?: string | null;codex_agent?: string | null;- codex_model?: string | null;- codex_reasoning_effort?: string | null;};require_mention?: boolean | null; // null=use global default, true=require, false=don't requirerequire_bind?: boolean | null; // null/false=off, true=only bound users may use this channel@@ -683,14 +677,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBmodel: null,reasoning_effort: null,opencode_agent: null,- opencode_model: null,- opencode_reasoning_effort: null,claude_agent: null,- claude_model: null,- claude_reasoning_effort: null,codex_agent: null,- codex_model: null,- codex_reasoning_effort: null,},require_mention: null,require_bind: null,diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsxindex 67acc6b14..f419774c1 100644--- a/ui/src/components/steps/UserList.tsx+++ b/ui/src/components/steps/UserList.tsx@@ -44,14 +44,8 @@ interface UserConfig {model?: string | null;reasoning_effort?: string | null;opencode_agent?: string | null;- opencode_model?: string | null;- opencode_reasoning_effort?: string | null;claude_agent?: string | null;- claude_model?: string | null;- claude_reasoning_effort?: string | null;codex_agent?: string | null;- codex_model?: string | null;- codex_reasoning_effort?: string | null;};}@@ -617,14 +611,8 @@ export const UserList: React.FC = () => {model: null,reasoning_effort: null,opencode_agent: null,- opencode_model: null,- opencode_reasoning_effort: null,claude_agent: null,- claude_model: null,- claude_reasoning_effort: null,codex_agent: null,- codex_model: null,- codex_reasoning_effort: null,},});diff --git a/vibe/api.py b/vibe/api.pyindex 53e2ea016..dc1368a60 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -44,10 +44,10 @@ from config.v2_settings import (UserSettings,RoutingSettings,_UNSET_AGENT_BINDING,+ LEGACY_ROUTING_ALIASES,normalize_show_message_types,_parse_routing,- _routing_to_dict,- routing_to_compat_dict,+ routing_to_dict,)from config.v2_sessions import SessionsStorefrom config.platform_registry import get_platform_descriptor@@ -5848,7 +5848,8 @@ def _scope_patch_value_error(name: str, value: Any) -> Optional[str]:if name == "routing":if not isinstance(value, dict):return "must be an object"- unknown = sorted(set(value) - scope_settings.ROUTING_FIELDS)+ # Retired per-backend aliases are still accepted from older browser tabs.+ unknown = sorted(set(value) - scope_settings.ROUTING_FIELDS - LEGACY_ROUTING_ALIASES)if unknown:return f"has unknown fields: {', '.join(unknown)}"if any(item is not None and not isinstance(item, str) for item in value.values()):@@ -6807,7 +6808,7 @@ def _scope_settings_payload(settings: ChannelSettings, platform: str) -> dict:"custom_cwd": settings.custom_cwd,"require_mention": settings.require_mention,"require_bind": settings.require_bind,- "routing": routing_to_compat_dict(settings.routing),+ "routing": routing_to_dict(settings.routing),"expected_agent_name": _agent_binding_expectation(settings),}@@ -6820,7 +6821,7 @@ def _user_settings_payload(settings: UserSettings, platform: str) -> dict:"enabled": settings.enabled,"show_message_types": scope_settings.normalize_scope_message_types(settings.show_message_types, platform),"custom_cwd": settings.custom_cwd,- "routing": routing_to_compat_dict(settings.routing),+ "routing": routing_to_dict(settings.routing),"expected_agent_name": _agent_binding_expectation(settings),}diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex bea053dc3..163b19f2d 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -13941,12 +13941,14 @@ if os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):ch.routing = RoutingSettings(agent_name=_routing_name_for_backend(modal_values.get("backend", "opencode")),model=(- modal_values.get("opencode_model")+ modal_values.get("model")+ or modal_values.get("opencode_model")or modal_values.get("claude_model")or modal_values.get("codex_model")),reasoning_effort=(- modal_values.get("opencode_reasoning_effort")+ modal_values.get("reasoning_effort")+ or modal_values.get("opencode_reasoning_effort")or modal_values.get("claude_reasoning_effort")or modal_values.get("codex_reasoning_effort")),@@ -13970,49 +13972,6 @@ if os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):)return jsonify({"ok": True, "action": action})- elif action == "routing_submit":- # Write routing config for a specific channel/user- channel_id = modal_values.get("channel_id") or modal_values.get("settings_key")- if not channel_id:- return jsonify({"ok": False, "error": "channel_id required in modal_values"}), 400-- from core.services import settings as settings_service-- store = settings_service.reload_settings_store()- from vibe.api import _current_platform-- platform = _current_platform()- ch = store.find_channel(channel_id, platform=platform)- if ch:- from config.v2_settings import RoutingSettings-- ch.routing = RoutingSettings(- agent_name=_routing_name_for_backend(modal_values.get("backend", "opencode")),- model=(- modal_values.get("opencode_model")- or modal_values.get("claude_model")- or modal_values.get("codex_model")- ),- reasoning_effort=(- modal_values.get("opencode_reasoning_effort")- or modal_values.get("claude_reasoning_effort")- or modal_values.get("codex_reasoning_effort")- ),- opencode_agent=modal_values.get("opencode_agent"),- claude_agent=modal_values.get("claude_agent"),- codex_agent=modal_values.get("codex_agent"),- )- store.save()- return jsonify({"ok": True, "action": action})- else:- return jsonify({"ok": False, "error": f"channel {channel_id} not found in settings"}), 404-- elif action == "cwd_submit":- # Update CWD via config API- new_cwd = modal_values.get("cwd", "/tmp")- result = vibe_api.save_config({"runtime": {"default_cwd": new_cwd}})- return jsonify({"ok": True, "action": action, "result": result})-else:return jsonify({"ok": False, "error": f"unknown action: {action}"}), 400