Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(model_hub): move the id everywhere it is a selection, not just in the hub

cyhc0a00c208a15
diff --git a/core/controller.py b/core/controller.py
index 46e0dfe0d..f0d134a50 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -689,6 +689,19 @@ class Controller:
raise RuntimeError("Backend restart coordinator is unavailable")
await coordinator.request_restart(backend)
+ async def repair_model_selections(addresses: frozenset[str]) -> int:
+ # A Vibe Agent's model, a channel's routing override, and a
+ # session's pin are each a copy of an id the Model Hub menu once
+ # offered. The hub proves which addresses are addresses; this
+ # process owns the rows that copied them.
+ from storage.model_selection_addresses import (
+ remove_credential_addresses_from_selections,
+ )
+
+ return await asyncio.to_thread(
+ remove_credential_addresses_from_selections, addresses
+ )
+
self.model_hub_service = create_default_service(
adapter=self.model_hub_engine_adapter,
requested_model_override=default_vibe_agent_model,
@@ -697,6 +710,7 @@ class Controller:
cli_present_override=cli_present,
cli_presence_refresh=refresh_cli_presence,
backend_catalog_changed=backend_catalog_changed,
+ repair_model_selections=repair_model_selections,
)
set_remote_catalog_refresh_completed(
self._model_hub_snapshot_refresh_completed
diff --git a/core/handlers/model_hub/address_repair.py b/core/handlers/model_hub/address_repair.py
index 1ad58d6f0..a54985530 100644
--- a/core/handlers/model_hub/address_repair.py
+++ b/core/handlers/model_hub/address_repair.py
@@ -92,6 +92,10 @@ class AddressRepair:
hops: int = 0
routes: int = 0
menu_entries: int = 0
+ # The backends whose menu, routes, or hops moved. A running backend holds
+ # the catalog it was started with, so the caller has to know which ones now
+ # disagree with disk — reconciling the engine says nothing about them.
+ backends: tuple[str, ...] = ()
@property
def changed(self) -> bool:
@@ -144,10 +148,12 @@ def repair_credential_addresses(
models=models_moved,
)
healed_agents: dict[str, Any] = {}
+ moved_backends: list[str] = []
for backend, agent in payload["agents"].items():
if not isinstance(agent, dict):
healed_agents[backend] = agent
continue
+ before = hops_moved + routes_moved + menu_entries_moved
healed_agent = dict(agent)
# A menu id, a route key, a hidden-model entry and a checked entry each
@@ -214,6 +220,10 @@ def repair_credential_addresses(
healed_agent["routes"] = healed_routes
healed_agents[backend] = healed_agent
+ if hops_moved + routes_moved + menu_entries_moved > before and isinstance(
+ backend, str
+ ):
+ moved_backends.append(backend)
healed["agents"] = healed_agents
return AddressRepair(
@@ -222,6 +232,7 @@ def repair_credential_addresses(
hops=hops_moved,
routes=routes_moved,
menu_entries=menu_entries_moved,
+ backends=tuple(moved_backends),
)
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 9c56ef555..d0b3a433e 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -875,6 +875,9 @@ class ModelHubService:
backend_catalog_changed: Optional[
Callable[[BackendName], Awaitable[None]]
] = None,
+ repair_model_selections: Optional[
+ Callable[[frozenset[str]], Awaitable[int]]
+ ] = None,
now: Callable[[], datetime] = _utc_now,
recovery: RecoveryPolicy | None = None,
):
@@ -916,6 +919,7 @@ class ModelHubService:
self.cli_present_override = cli_present_override
self.cli_presence_refresh = cli_presence_refresh
self.backend_catalog_changed = backend_catalog_changed
+ self.repair_model_selections = repair_model_selections
self.now = now
self.recovery = recovery or RecoveryPolicy(now=lambda: self.now())
self.native_source_ready: Callable[[BackendName, ModelHubSourceConfig], bool] = (
@@ -1220,6 +1224,13 @@ class ModelHubService:
something gone. Persisting goes through the same projection owner as
any other mutation, so the engine is reconciled with what was written.
+ A stored id reaches past this config, too. A Vibe Agent's model, a
+ channel's routing override, and a session's pin are each a copy of an
+ id the menu once offered, and each is read back to decide what a turn
+ asks for — repairing only the catalog would leave them naming a model
+ that no longer exists under that name. The owner of those rows repairs
+ them through ``repair_model_selections``, against this same proof.
+
Best effort by design: an id left alone is exactly the state the
previous release was already in, which is not worth failing a demand
over. The next demand tries again.
@@ -1251,6 +1262,15 @@ class ModelHubService:
repair = repair_credential_addresses(payload, addresses)
if not repair.changed:
return
+ # Selections move before the config is committed, because the
+ # config is the witness that anything needs repairing at all.
+ # Committing it first would clear that witness while a copy of
+ # one of its ids is still stored as somebody's selection; this
+ # order retries the whole pass instead, and both halves are
+ # idempotent.
+ selections = await self._repair_selections(
+ frozenset(addresses.values())
+ )
await self._commit_synced(
config,
ModelHubConfig.from_payload(repair.payload),
@@ -1263,12 +1283,33 @@ class ModelHubService:
return
logger.info(
"model hub: removed credential addresses from stored ids "
- "(%d source models, %d route hops, %d routes, %d agent menu entries)",
+ "(%d source models, %d route hops, %d routes, %d agent menu "
+ "entries, %d model selections)",
repair.models,
repair.hops,
repair.routes,
repair.menu_entries,
+ selections,
)
+ # A running backend answers from the catalog it was started with, so
+ # reconciling the engine leaves it offering the ids that were just
+ # renamed. Same follow-up any other catalog mutation makes.
+ for backend in repair.backends:
+ try:
+ await self._refresh_backend_catalog(cast(BackendName, backend))
+ except Exception:
+ logger.warning(
+ "model hub: could not refresh %s after an address repair",
+ backend,
+ exc_info=True,
+ )
+
+ async def _repair_selections(self, addresses: frozenset[str]) -> int:
+ """Hand the proven addresses to the owner of persisted selections."""
+
+ if self.repair_model_selections is None or not addresses:
+ return 0
+ return await self.repair_model_selections(addresses)
async def _sync_sources(self, config: ModelHubConfig, *, force_empty: bool = False) -> None:
bindings = self._bindings(config)
@@ -7816,6 +7857,9 @@ def create_default_service(
backend_catalog_changed: Optional[
Callable[[BackendName], Awaitable[None]]
] = None,
+ repair_model_selections: Optional[
+ Callable[[frozenset[str]], Awaitable[int]]
+ ] = None,
) -> ModelHubService:
if adapter is None:
from vibe.model_hub_runtime import get_model_hub_engine_adapter
@@ -7869,4 +7913,5 @@ def create_default_service(
cli_present_override=cli_present_override,
cli_presence_refresh=cli_presence_refresh,
backend_catalog_changed=backend_catalog_changed,
+ repair_model_selections=repair_model_selections,
)
diff --git a/docs/plans/model-hub-credential-address-repair.md b/docs/plans/model-hub-credential-address-repair.md
index 30ff4b47f..692bc346e 100644
--- a/docs/plans/model-hub-credential-address-repair.md
+++ b/docs/plans/model-hub-credential-address-repair.md
@@ -107,6 +107,50 @@ write:
Everything is computed first and written once, so a partial rename cannot be
persisted.
+### The same id outside this config
+
+An id also leaves the Model Hub. A user picks one from the menu, and the value
+is copied into whichever row records that choice. A turn then reads those rows
+back, in this precedence, to decide what it asks for
+(`message_handler.py:505`):
+
+| Position | Read as | Rule |
+| --- | --- | --- |
+| `agent_sessions.model` | The session's pin, highest precedence | Renamed |
+| `scope_settings.settings_json` → `routing.{model,model_override,opencode_model,claude_model,codex_model}` | A channel's routing override; read **before** the column | Renamed |
+| `scope_settings.model` | The same override, column form | Renamed |
+| `agents.model` | The Vibe Agent's own model | Renamed |
+| `agent_runs.model` | A record of a call that was made | **Not** renamed |
+| `skill_usage_daily.model` | A metering key | **Not** renamed |
+
+The split is selection versus record. The first four decide a future request;
+leaving one addressed keeps the Agent broken after the catalog is repaired —
+the failure only changes from a double-addressed `model_not_found` to a
+`mapping_target_unavailable`. The last two describe calls already made, and
+rewriting them would restate history.
+
+`run_definitions` has no model column at all: a scheduled run resolves its
+model live through its Agent, so it inherits the repair for free.
+
+The hub proves which addresses are addresses; it does not own these rows. It
+hands the proven set to `repair_model_selections`, which the controller wires
+to `storage/model_selection_addresses.py`. Selections move **before** the
+config is committed, because the config is the witness that anything needed
+repairing at all — committing it first would clear that witness while a copy of
+one of its ids was still stored as somebody's selection, and the retry the next
+demand schedules would never fire. Both halves are idempotent, so the retry
+costs nothing.
+
+### A backend already running
+
+Reconciling the engine projection says nothing about a backend process that is
+already up: it answers from the catalog it was started with and keeps offering
+the ids that were just renamed. Every backend whose menu, routes, or hops moved
+is therefore handed to `_refresh_backend_catalog` after the commit — the same
+follow-up `set_agent_models` makes. A refresh that fails is logged, not raised:
+the repair has already landed on disk, and a stale in-memory catalog is not
+worth failing the demand that triggered it.
+
Every one of these collections is uniqueness-checked on load, so a rename that
creates a collision it does not absorb would turn a loadable file into one that
fails config load — strictly worse than the addressed id it set out to fix. Two
@@ -148,7 +192,8 @@ at the config layer.
### Reporting
One log line with the counts moved — source models, route hops, routes, agent
-menu entries. A Source whose credential cannot be resolved is logged at debug
+menu entries, and persisted model selections. A Source whose credential cannot
+be resolved is logged at debug
and skipped whole; its unreachable credential is already surfaced through the
Source's own state, and the repair declining to touch it leaves exactly the
state the previous release was in.
@@ -177,7 +222,20 @@ tries again.
prefix for a bound credential and `None` for one it has no record of;
- end to end through `_prepare_engine_for_demand`: the stored file is repaired
and the engine is sent the bare names, and with no provable address the file
- is left byte-for-byte as the previous release left it.
+ is left byte-for-byte as the previous release left it;
+- the proof reaches the owner of persisted selections before the config is
+ committed, a selection repair that raises leaves the config unwritten so the
+ next demand repairs both halves, and a backend whose catalog moved is
+ refreshed — while a refresh that fails does not fail the demand.
+
+`tests/test_model_selection_addresses.py`:
+
+- all three selections a turn resolves lose the address, including every key a
+ scope's routing payload can spell one under;
+- an identity no address proves is left alone, including a foreign minted
+ address and the upstream slashes;
+- a second pass finds nothing left to move, an empty proof set touches nothing,
+ and one unreadable routing payload does not stop the rest.
Still to do before close-out: a local Incus regression on a snapshot of an
affected `config.json` + `sources.json`, confirming the subscription models
diff --git a/storage/model_selection_addresses.py b/storage/model_selection_addresses.py
new file mode 100644
index 000000000..0933c6478
--- /dev/null
+++ b/storage/model_selection_addresses.py
@@ -0,0 +1,141 @@
+"""Take a credential's address out of persisted model selections.
+
+A model id is a *selection* in these tables, not a record of one: a turn reads
+them back to decide what it asks for. The precedence a turn resolves is the
+session's pin, then the channel's routing override, then the Vibe Agent's own
+model, so all three are selections and all three can hold an id an older
+release offered — the menu is where a user picked one, and every one of these
+rows is a copy of what the menu said at the time.
+
+Repairing the Model Hub catalog alone would leave them naming a model that no
+longer exists under that name. Repairing them is the other half of the same
+write: one id, every place it is a key.
+
+A run's recorded model and a usage ledger's key are deliberately *not* here.
+Those are records of a call that was made, not inputs to one that will be, and
+rewriting them would restate history.
+
+Ownership is proven by the caller, never guessed: only an address the engine
+actually mints for a bound credential is removed, so an upstream identity that
+happens to be spelled like one is untouched.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from collections.abc import Collection
+from typing import Any
+
+from sqlalchemy import select, update
+from sqlalchemy.engine import Engine
+
+from core.handlers.model_hub.identifiers import model_id_without_credential_addresses
+from storage.db import get_cached_sqlite_engine
+from storage.models import agent_sessions, agents, scope_settings
+
+logger = logging.getLogger(__name__)
+
+# Every key a scope's routing payload can spell a model selection under. The
+# payload is read before the column (``_routing_from_row``), so repairing the
+# column alone would leave the value a turn actually resolves.
+_ROUTING_MODEL_KEYS = (
+ "model",
+ "model_override",
+ "opencode_model",
+ "claude_model",
+ "codex_model",
+)
+
+# Table, primary key, and the column holding the selection.
+_SELECTION_COLUMNS = (
+ (agents, agents.c.id, agents.c.model),
+ (scope_settings, scope_settings.c.scope_id, scope_settings.c.model),
+ (agent_sessions, agent_sessions.c.id, agent_sessions.c.model),
+)
+
+
+def remove_credential_addresses_from_selections(
+ addresses: Collection[str],
+ *,
+ engine: Engine | None = None,
+) -> int:
+ """Rewrite every persisted selection carrying one of these addresses.
+
+ ``addresses`` is the set the Model Hub repair proved for its Sources. An
+ address absent from it is not an address as far as this call is concerned.
+
+ Returns how many stored values were rewritten. Idempotent: a second call
+ with the same set finds nothing left to move.
+ """
+
+ known = frozenset(value for value in addresses if value)
+ if not known:
+ return 0
+ engine = engine or get_cached_sqlite_engine()
+ moved = 0
+ with engine.begin() as connection:
+ for table, key, column in _SELECTION_COLUMNS:
+ rows = connection.execute(
+ select(key, column).where(column.is_not(None))
+ ).all()
+ for row_key, value in rows:
+ if not isinstance(value, str):
+ continue
+ identity = model_id_without_credential_addresses(value, known)
+ if identity == value:
+ continue
+ connection.execute(
+ update(table).where(key == row_key).values({column.key: identity})
+ )
+ moved += 1
+ moved += _repaired_routing_payloads(connection, known)
+ return moved
+
+
+def _repaired_routing_payloads(connection: Any, known: frozenset[str]) -> int:
+ """Rewrite the model a scope's routing payload spells, under any of its keys."""
+
+ rows = connection.execute(
+ select(scope_settings.c.scope_id, scope_settings.c.settings_json)
+ ).all()
+ moved = 0
+ for scope_id, raw in rows:
+ if not isinstance(raw, str) or not raw:
+ continue
+ try:
+ payload = json.loads(raw)
+ except (TypeError, ValueError):
+ # A payload this call cannot read is one it cannot repair. Leaving
+ # it is exactly the state the previous release was already in.
+ logger.debug("model hub: unreadable routing payload for scope %s", scope_id)
+ continue
+ routing = payload.get("routing") if isinstance(payload, dict) else None
+ if not isinstance(routing, dict):
+ continue
+ repaired = dict(routing)
+ changed = 0
+ for routing_key in _ROUTING_MODEL_KEYS:
+ value = routing.get(routing_key)
+ if not isinstance(value, str) or not value:
+ continue
+ identity = model_id_without_credential_addresses(value, known)
+ if identity == value:
+ continue
+ repaired[routing_key] = identity
+ changed += 1
+ if not changed:
+ continue
+ connection.execute(
+ update(scope_settings)
+ .where(scope_settings.c.scope_id == scope_id)
+ .values(
+ settings_json=json.dumps(
+ {**payload, "routing": repaired},
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ )
+ )
+ moved += changed
+ return moved
diff --git a/tests/test_model_hub_credential_address.py b/tests/test_model_hub_credential_address.py
index 889c0beb1..adcdcf718 100644
--- a/tests/test_model_hub_credential_address.py
+++ b/tests/test_model_hub_credential_address.py
@@ -916,3 +916,104 @@ def test_the_runtime_leaves_an_id_alone_when_the_address_is_unprovable(tmp_path)
"x-ai/grok-4.6-latest",
]
assert list(store.config.agents["claude"].routes) == [f"{ADDRESS}/gpt-5.5"]
+
+
+def test_the_repair_hands_its_proof_to_the_owner_of_persisted_selections(
+ tmp_path,
+) -> None:
+ """A Vibe Agent's model is a copy of a menu id, and it is read back as one.
+
+ The hub can prove which addresses are addresses; it does not own the rows
+ that copied them. It passes the proof to whoever does, and it does so
+ before committing the config, because the config is the witness that
+ anything needed repairing at all — clearing it first would end the retry
+ that a failed selection repair depends on.
+ """
+
+ service, store, adapter = _addressed_service(tmp_path, {"cred_fixture123": ADDRESS})
+ proven: list[frozenset[str]] = []
+ committed_when_called: list[list[str]] = []
+
+ async def repair_selections(addresses):
+ proven.append(addresses)
+ committed_when_called.append(
+ [model.id for model in store.config.sources[0].models]
+ )
+ return 3
+
+ service.repair_model_selections = repair_selections
+
+ asyncio.run(service._prepare_engine_for_demand())
+
+ assert proven == [frozenset({ADDRESS})]
+ # Still the addressed spelling: selections move first.
+ assert committed_when_called == [[f"{ADDRESS}/gpt-5.5", "x-ai/grok-4.6-latest"]]
+ assert [model.id for model in store.config.sources[0].models] == [
+ "gpt-5.5",
+ "x-ai/grok-4.6-latest",
+ ]
+
+
+def test_a_failed_selection_repair_leaves_the_witness_standing(tmp_path) -> None:
+ """Nothing is committed, so the next demand repairs both halves again."""
+
+ service, store, adapter = _addressed_service(tmp_path, {"cred_fixture123": ADDRESS})
+
+ async def repair_selections(addresses):
+ raise RuntimeError("selection store unavailable")
+
+ service.repair_model_selections = repair_selections
+
+ asyncio.run(service._prepare_engine_for_demand())
+
+ assert [model.id for model in store.config.sources[0].models] == [
+ f"{ADDRESS}/gpt-5.5",
+ "x-ai/grok-4.6-latest",
+ ]
+
+ service.repair_model_selections = None
+ asyncio.run(service._prepare_engine_for_demand())
+
+ assert [model.id for model in store.config.sources[0].models] == [
+ "gpt-5.5",
+ "x-ai/grok-4.6-latest",
+ ]
+
+
+def test_a_backend_whose_catalog_moved_is_refreshed(tmp_path) -> None:
+ """A running backend answers from the catalog it started with.
+
+ Reconciling the engine projection says nothing about a backend already up:
+ it keeps offering the ids that were just renamed until something reloads
+ it. This is the same follow-up every other catalog mutation makes.
+ """
+
+ service, store, adapter = _addressed_service(tmp_path, {"cred_fixture123": ADDRESS})
+ refreshed: list[str] = []
+
+ async def backend_catalog_changed(backend):
+ refreshed.append(backend)
+
+ service.backend_catalog_changed = backend_catalog_changed
+
+ asyncio.run(service._prepare_engine_for_demand())
+
+ assert refreshed == ["claude"]
+
+
+def test_a_refresh_that_fails_does_not_fail_the_demand(tmp_path) -> None:
+ """The repair already landed; a stale in-memory catalog is not worth a 503."""
+
+ service, store, adapter = _addressed_service(tmp_path, {"cred_fixture123": ADDRESS})
+
+ async def backend_catalog_changed(backend):
+ raise RuntimeError("coordinator unavailable")
+
+ service.backend_catalog_changed = backend_catalog_changed
+
+ asyncio.run(service._prepare_engine_for_demand())
+
+ assert [model.id for model in store.config.sources[0].models] == [
+ "gpt-5.5",
+ "x-ai/grok-4.6-latest",
+ ]
diff --git a/tests/test_model_selection_addresses.py b/tests/test_model_selection_addresses.py
new file mode 100644
index 000000000..16f724688
--- /dev/null
+++ b/tests/test_model_selection_addresses.py
@@ -0,0 +1,230 @@
+"""A credential's address must not survive in a persisted model selection.
+
+The Model Hub catalog repair renames ids inside ``config.json``. Three SQLite
+columns hold a *copy* of one of those ids — the Vibe Agent's model, a channel's
+routing override, and a session's pin — and a turn reads them back in that
+precedence to decide what it asks for. Repairing only the catalog would leave
+them naming a model that no longer exists under that name.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from sqlalchemy import insert, select
+
+from storage.db import get_cached_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.model_selection_addresses import (
+ remove_credential_addresses_from_selections,
+)
+from storage.models import agent_sessions, agents, scope_settings, scopes
+
+ADDRESS = "avibe-dc0395a1b2c3d4e5f60718"
+OTHER_ADDRESS = "avibe-0123456789abcdef01234567"
+NOW = "2026-01-01T00:00:00Z"
+
+
+def engine():
+ ensure_sqlite_state()
+ return get_cached_sqlite_engine()
+
+
+def _add_agent(connection, agent_id: str, model: str | None) -> None:
+ connection.execute(
+ insert(agents).values(
+ id=agent_id,
+ name=agent_id,
+ normalized_name=agent_id,
+ backend="claude",
+ model=model,
+ enabled=1,
+ source="user",
+ metadata_json="{}",
+ created_at=NOW,
+ updated_at=NOW,
+ )
+ )
+
+
+def _add_scope(connection, scope_id: str, *, model: str | None, routing: dict) -> None:
+ connection.execute(
+ insert(scopes).values(
+ id=scope_id,
+ platform="slack",
+ scope_type="channel",
+ native_id=scope_id,
+ is_private=0,
+ supports_threads=1,
+ metadata_json="{}",
+ first_seen_at=NOW,
+ last_seen_at=NOW,
+ updated_at=NOW,
+ )
+ )
+ connection.execute(
+ insert(scope_settings).values(
+ scope_id=scope_id,
+ enabled=1,
+ model=model,
+ settings_version=1,
+ settings_json=json.dumps({"routing": routing}),
+ created_at=NOW,
+ updated_at=NOW,
+ )
+ )
+
+
+def _add_session(connection, session_id: str, model: str | None) -> None:
+ connection.execute(
+ insert(agent_sessions).values(
+ id=session_id,
+ agent_backend="claude",
+ agent_variant="default",
+ model=model,
+ session_anchor=session_id,
+ native_session_id=session_id,
+ status="active",
+ visibility="foreground",
+ pinned=0,
+ agent_status="idle",
+ metadata_json="{}",
+ created_at=NOW,
+ updated_at=NOW,
+ )
+ )
+
+
+def test_every_selection_a_turn_resolves_loses_the_address(engine) -> None:
+ """The Agent's model, the channel override, and the session pin all move.
+
+ These are the three the turn's precedence reads, in that order. A repair
+ that reached only one of them would leave the others deciding the request.
+ """
+
+ with engine.begin() as connection:
+ _add_agent(connection, "agent-1", f"{ADDRESS}/gpt-5.5")
+ _add_scope(
+ connection,
+ "scope-1",
+ model=f"{ADDRESS}/gpt-5.5",
+ routing={"agent_name": "claude", "model": f"{ADDRESS}/gpt-5.5"},
+ )
+ _add_session(connection, "session-1", f"{ADDRESS}/gpt-5.5")
+
+ moved = remove_credential_addresses_from_selections({ADDRESS}, engine=engine)
+
+ assert moved == 4
+ with engine.connect() as connection:
+ assert connection.execute(select(agents.c.model)).scalar_one() == "gpt-5.5"
+ row = connection.execute(
+ select(scope_settings.c.model, scope_settings.c.settings_json)
+ ).one()
+ assert row.model == "gpt-5.5"
+ assert json.loads(row.settings_json)["routing"]["model"] == "gpt-5.5"
+ assert (
+ connection.execute(select(agent_sessions.c.model)).scalar_one() == "gpt-5.5"
+ )
+
+
+def test_the_routing_payload_moves_under_every_key_it_can_use(engine) -> None:
+ """A scope spells its selection under whichever key its backend uses.
+
+ ``_routing_from_row`` reads the payload before the column, so a repair that
+ stopped at the column would leave the value a turn actually resolves.
+ """
+
+ routing = {
+ "agent_name": "claude",
+ "model_override": f"{ADDRESS}/opus",
+ "claude_model": f"{ADDRESS}/sonnet",
+ "codex_model": f"{ADDRESS}/gpt-5.5",
+ "opencode_model": f"{ADDRESS}/kimi",
+ "opencode_agent": "build",
+ }
+ with engine.begin() as connection:
+ _add_scope(connection, "scope-1", model=None, routing=routing)
+
+ moved = remove_credential_addresses_from_selections({ADDRESS}, engine=engine)
+
+ assert moved == 4
+ with engine.connect() as connection:
+ stored = json.loads(
+ connection.execute(select(scope_settings.c.settings_json)).scalar_one()
+ )
+ assert stored["routing"] == {
+ "agent_name": "claude",
+ "model_override": "opus",
+ "claude_model": "sonnet",
+ "codex_model": "gpt-5.5",
+ "opencode_model": "kimi",
+ "opencode_agent": "build",
+ }
+
+
+def test_an_identity_no_address_proves_is_left_alone(engine) -> None:
+ """Only a proven address is an address; a vendor's own name is not ours.
+
+ ``x-ai/grok-4.6-latest`` is a real upstream identity, and one spelled like
+ a minted address still belongs to whoever minted it — unless this exact
+ installation proved it is one of its own.
+ """
+
+ with engine.begin() as connection:
+ _add_agent(connection, "agent-1", "x-ai/grok-4.6-latest")
+ _add_agent(connection, "agent-2", f"{OTHER_ADDRESS}/gpt-5.5")
+ _add_session(connection, "session-1", "anthropic/claude-sonnet-4")
+
+ moved = remove_credential_addresses_from_selections({ADDRESS}, engine=engine)
+
+ assert moved == 0
+ with engine.connect() as connection:
+ stored = set(connection.execute(select(agents.c.model)).scalars())
+ assert stored == {"x-ai/grok-4.6-latest", f"{OTHER_ADDRESS}/gpt-5.5"}
+ assert (
+ connection.execute(select(agent_sessions.c.model)).scalar_one()
+ == "anthropic/claude-sonnet-4"
+ )
+
+
+def test_a_second_pass_finds_nothing_left_to_move(engine) -> None:
+ """Idempotent, so the retry an aborted repair schedules is free."""
+
+ with engine.begin() as connection:
+ _add_agent(connection, "agent-1", f"{ADDRESS}/gpt-5.5")
+
+ assert remove_credential_addresses_from_selections({ADDRESS}, engine=engine) == 1
+ assert remove_credential_addresses_from_selections({ADDRESS}, engine=engine) == 0
+
+
+def test_no_proven_address_touches_nothing(engine) -> None:
+ """With nothing proven there is nothing to remove, and no scan to pay for."""
+
+ with engine.begin() as connection:
+ _add_agent(connection, "agent-1", f"{ADDRESS}/gpt-5.5")
+
+ assert remove_credential_addresses_from_selections(frozenset(), engine=engine) == 0
+ with engine.connect() as connection:
+ assert (
+ connection.execute(select(agents.c.model)).scalar_one()
+ == f"{ADDRESS}/gpt-5.5"
+ )
+
+
+def test_a_payload_that_cannot_be_read_does_not_stop_the_others(engine) -> None:
+ """One unreadable blob is the previous release's state, not a failed repair."""
+
+ with engine.begin() as connection:
+ _add_agent(connection, "agent-1", f"{ADDRESS}/gpt-5.5")
+ _add_scope(connection, "scope-1", model=None, routing={})
+ connection.execute(
+ scope_settings.update()
+ .where(scope_settings.c.scope_id == "scope-1")
+ .values(settings_json="{not json")
+ )
+
+ assert remove_credential_addresses_from_selections({ADDRESS}, engine=engine) == 1
+ with engine.connect() as connection:
+ assert connection.execute(select(agents.c.model)).scalar_one() == "gpt-5.5"