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
fix(model-hub): defer shared config migrations to service startup (#2076)
Call White1898db8bb79d
diff --git a/config/v2_config.py b/config/v2_config.pyindex 0a0f43323..5a50548a1 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -3567,8 +3567,9 @@ class ModelHubConfig:backend: ModelHubAgentSupplyConfig.default(backend, mode="hub") for backend in MODEL_HUB_BACKENDS})- # Current writers stamp this even when saving enabled=False. Only disk- # loading may promote an old absent/false marker together with enabled=True.+ # Fresh configs and explicit Start/Stop consume the default. Disk observers+ # retain a pending false marker until lock-owning startup commits promotion;+ # an unrelated save must not acknowledge an upgrade it did not perform.runtime_default_applied: bool = True@staticmethod@@ -3994,9 +3995,16 @@ class V2Config:cls,config_path: Optional[Path] = None,*,- persist_migrations: bool = True,+ persist_migrations: bool = False,_migration_reload_depth: int = 0,) -> "V2Config":+ """Read/project config without implicitly upgrading the shared file.++ A newly installed CLI can coexist with a still-running older service.+ Only the replacement service's lock-owning startup opts into migration+ persistence; incidental reads must not invalidate that older reader.+ Explicit saves remain writes, and recovery keeps its backup evidence.+ """paths.ensure_data_dirs()path = config_path or paths.get_config_path()with CONFIG_LOCK:@@ -4054,8 +4062,11 @@ class V2Config:stored_hub = payload.get("model_hub")previous_runtime_enabled = isinstance(stored_hub, dict) and stored_hub.get("enabled") is Trueif runtime_default_pending:- config.model_hub.enabled = True- config.model_hub.runtime_default_applied = True+ # Reading an old file is not permission to activate its pending+ # default. In particular, a store reload after a failed startup+ # backup/CAS must not undo the failure's disabled-runtime result.+ config.model_hub.enabled = True if persist_migrations else previous_runtime_enabled+ config.model_hub.runtime_default_applied = persist_migrationsmigrated = Trueelif migration_warnings or recovery_warnings:# Do not materialize a new runtime default while recovering an@@ -4090,6 +4101,7 @@ class V2Config:if "file changed" in persistence_warning and _migration_reload_depth == 0:winning_config = cls.load(config_path=path,+ persist_migrations=persist_migrations,_migration_reload_depth=1,)winning_config.load_warnings = tuple(diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex deef66d7b..42b9430e9 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -6374,6 +6374,7 @@ class ModelHubService:previous = self.store.load()updated = self._clone_config(previous)updated.enabled = True+ updated.runtime_default_applied = Trueself._save_projection_neutral(previous, updated)await self._prepare_engine_for_demand()status = await self._engine_call(self.adapter.start())@@ -6403,6 +6404,7 @@ class ModelHubService:raise ModelHubError("runtime_busy", status=409)updated = self._clone_config(previous)updated.enabled = False+ updated.runtime_default_applied = Trueself._save_projection_neutral(previous, updated)return _runtime_payload(status, enabled=False)diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 90b89b8f5..42ef2fc9e 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -330,7 +330,7 @@ every other existing field and enum meaning remains unchanged.| `AgentSupply.cli_present` | backend CLI detector | zero-installed-backend state | Boolean installation fact only; it does not imply login or process readiness. || `AgentSupply.model_supply[].has_runnable_hop` | exact-chain live annotator | backend-group collapse predicate | Uses the AgentChain runnability axiom rather than inferring liveness from configured membership. `chain_length: 0` forces false; a nonzero length may carry either value. || `RuntimeDependency.enabled` | explicit runtime start/stop mutation | Gateway switch and service-start recovery | Persisted user intent, independent of observed process health. Fresh/default configuration is true; explicit Stop persists false. |-| `model_hub.runtime_default_applied` | config loader/default migration | one-time legacy upgrade and runtime-start recovery | Additive persisted marker. Missing on disk upgrades once to `enabled: true` and `runtime_default_applied: true`; later explicit Stop remains false. |+| `model_hub.runtime_default_applied` | lock-owning service startup/default migration or explicit runtime Start/Stop | one-time legacy upgrade and runtime-start recovery | Additive persisted marker. Missing/false on disk remains pending through ordinary reads and unrelated writes; startup upgrades once to `enabled: true` and a true marker. Explicit Start/Stop consume the marker with their chosen intent; refused/failed Stop does not. Later explicit Stop remains disabled. || `RuntimeDependency.host_platform` | server host detector | unsupported-host runtime pill | Names the Avibe host, not the browser; exact membership in `manifest.assets[].platform` decides install support. || `RuntimeDependency.status.error_key` | runtime installer | install-failed runtime state | Closed persisted i18n key: `settings.models.install.fail.detail` after installation fails; null after a new attempt begins and in every non-failure state. || `RouteHopRef.position` | guarded mutation planner | guarded-change hop row | One-based position in the named Route before the attempted mutation. |diff --git a/docs/plans/model-hub-upgrade-config-compatibility.md b/docs/plans/model-hub-upgrade-config-compatibility.mdnew file mode 100644index 000000000..66b0d9969--- /dev/null+++ b/docs/plans/model-hub-upgrade-config-compatibility.md@@ -0,0 +1,83 @@+# Model Hub config migration ownership during mixed-version upgrades++## Problem and scope++Installing a new CLI does not replace an already running service. Avibe+3.1.1rc1's ordinary `V2Config.load()` writes the new+`model_hub.runtime_default_applied` field. A live 3.1.0rc3 reader rejects this+unknown field, recovers the entire Hub section to direct-mode defaults, and+rejects an already-running gateway request with `mode_switch_blocked` / 409.+The persisted sources and modes are still present: this is an unintended+writer during the upgrade overlap, not lost credentials or a Codex-only bug.++## Contract++1. Ordinary config loading parses and projects legacy shapes without+ committing schema migrations. This applies at the shared loader, including+ CLI Agent/Session commands, settings reads, status/diagnostics, and upgrade+ preflight. No per-command exception list or version probe is required.+2. Service startup explicitly persists migrations **after** acquiring the+ existing data-directory service-instance lock and before constructing the+ controller. A candidate that cannot acquire that lock cannot migrate the+ live service's config.+3. Keep the existing explicit `persist_migrations` API, in-memory legacy-shape+ projection, strict validation, recovery evidence, backup/CAS transaction,+ and bounded stale-snapshot reread. A reread preserves the caller's explicit+ migration-persistence choice. Non-persisting reads retain the stored runtime+ intent, rather than activating the uncommitted pending default in memory.+ This also prevents a store reload from bypassing a failed startup backup/CAS.+ An absent/false default marker stays pending (`false`) in this projection+ and through unrelated settings, Memory, and generic config writes; only+ startup promotion or an explicit runtime action consumes it.+4. Keep the shipped marker, fresh-install defaults, backend routing modes,+ source custody, and one-time runtime promotion unchanged. Explicit runtime+ Start/Stop persist their chosen enabled state together with a true marker,+ even when the enabled state was already equal. Start records run intent+ before preparing the engine, as before; refused/failed Stop leaves the+ config and pending marker unchanged. A deliberate Stop stays stopped+ across reads and new-service startups.+5. Explicit settings/config writes remain writes. This change does not promise+ arbitrary old-reader support after a new version deliberately saves a new+ schema, nor roll back a config already migrated by an earlier release.+ It removes incidental migration writes from ordinary observation.++The service lock and migration CAS already express the necessary ownership;+do not add another upgrade coordinator, sidecar marker, schema negotiation,+blanket unknown-field tolerance, or a gateway retry/fallback.++## Validation invariants++- A legacy Hub config survives real CLI/settings/upgrade-reader entry points+ byte-for-byte, without migration backups or recovery. Its old-reader field+ vocabulary remains valid and the invocation-resolution consumer continues+ to resolve its configured source instead of returning mode-switch 409.+- Cover enabled and disabled legacy runtime intent, Unicode paths/data,+ unrelated fields, existing marker/explicit opt-out, and legacy shape+ projection. Tests use temporary HOME/XDG/state and synthetic sources only.+- New-service startup commits the existing upgrade once, with an exact+ restricted-permission backup. A rejected second service does not reach+ migration. Backup failure and concurrent writes retain their existing+ fail-closed behavior.+- Unrelated writes keep a pending legacy upgrade pending until startup.+ Explicit Start/Stop consume it without changing sources or backend modes;+ refused/busy/failed Stop does not. Cover absent and false markers with+ both enabled states, including already-disabled Stop.+- Re-run the existing migration, settings, CLI, service-lock, and upgrade+ suites. Separately replay the installed historical reader against a+ fixture touched by the changed reader; no native CLI, credentials,+ production config, live request, or service restart is needed.++## Known-by-design boundaries++- `persist_migrations=False` remains a legacy-shape compatibility projection,+ not a dump of the raw file, but no longer previews runtime activation.+ Recoverable malformed files can still produce the existing+ backup/warning evidence; no recovery default is silently written over them.+- Existing explicit config mutations can serialize the current schema.+ Backward compatibility after such an authorized write, or a manual+ downgrade after migration, is not added by this read-side fix.+- The generic recovery-to-mode-switch error in already shipped old services+ cannot be changed in place. Preventing the incompatible incidental write+ removes this incident's cause without weakening the gateway guard.+- No deployment, restart, merge, native account acceptance, regression reset,+ or local persistent regression update is part of this implementation.diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex 13423f89c..beb5fa07c 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -963,8 +963,15 @@ state set; prose cannot add another runtime health value. `RuntimeDependency.enais orthogonal persisted user intent. New configurations default it to true without anenable-confirmation dialog. The additive persisted`model_hub.runtime_default_applied: bool` marker defaults to true; a pre-marker disk-shape is upgraded once to `enabled: true` and the marker is then persisted. Later-explicit Stop writes `enabled: false` and does not get re-enabled by that one-time+shape is upgraded once to `enabled: true` and the marker is then persisted by+service startup after acquiring the instance lock. Ordinary config reads only+project compatible shapes in memory and retain the pending marker as false;+unrelated settings or Memory writes do not consume it. Installing a newer CLI must not rewrite+the shared file ahead of an older running service (see+[migration ownership](model-hub-upgrade-config-compatibility.md)). Explicit+Start/Stop consume the marker together with their enabled intent, including an+already-disabled Stop; a refused/failed Stop leaves both unchanged.+Stop writes `enabled: false` and does not get re-enabled by that one-timedefaulting rule. Service startup starts the runtime only when the persisted intent istrue, and a transient process loss changes health, never this switch state.diff --git a/main.py b/main.pyindex c9e19d497..c1dadfa7b 100644--- a/main.py+++ b/main.py@@ -80,7 +80,9 @@ def apply_claude_sdk_patches():def load_config() -> Any:from config.v2_config import V2Config- return V2Config.load()+ # main() acquires the instance lock first: a newly installed CLI or a+ # rejected second service must not migrate an older live reader's config.+ return V2Config.load(persist_migrations=True)def ensure_sqlite_state(*args, **kwargs):diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.pyindex 43c30cac6..6b2a4d8ef 100644--- a/tests/test_api_save_config_merge.py+++ b/tests/test_api_save_config_merge.py@@ -668,12 +668,20 @@ def test_config_load_ignores_retired_show_pages_prompt(tmp_path, legacy_fields):payload.update(legacy_fields)config_path = tmp_path / "config.json"config_path.write_text(json.dumps(payload), encoding="utf-8")+ original = config_path.read_bytes()created = V2Config.load(config_path)assert created.load_warnings == ()assert not hasattr(created, "show_pages_prompt")- assert api.config_to_payload(created) == api.config_to_payload(V2Config.from_payload(_full_config_payload()))+ expected = V2Config.from_payload(_full_config_payload())+ # An observer does not turn the fixture's missing legacy Hub into a+ # committed fresh-install default while discarding unrelated retired data.+ expected.model_hub.enabled = False+ expected.model_hub.runtime_default_applied = False+ assert api.config_to_payload(created) == api.config_to_payload(expected)+ assert config_path.read_bytes() == original+ assert not list(tmp_path.glob("config.json.bak-*"))def test_config_load_preserves_pre_upgrade_audio_asr_false_as_opt_out():diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex f52be4e58..b18211f7e 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -1802,7 +1802,7 @@ def test_config_reload_does_not_replace_file_when_migration_backup_fails(monkeypconfig_path.write_text(original, encoding="utf-8")monkeypatch.setattr(v2_config, "_backup_config_file", lambda *args, **kwargs: None)- loaded = V2Config.load(config_path=config_path)+ loaded = V2Config.load(config_path=config_path, persist_migrations=True)assert loaded.model_hub.to_payload() != payload["model_hub"]assert config_path.read_text(encoding="utf-8") == original@@ -2188,7 +2188,7 @@ def test_config_reload_defaults_omitted_legacy_backend_entries(monkeypatch, tmp_config_path = tmp_path / "config.json"config_path.write_text(json.dumps(current), encoding="utf-8")- loaded = V2Config.load(config_path=config_path)+ loaded = V2Config.load(config_path=config_path, persist_migrations=True)assert loaded.model_hub.agents["codex"].mode == "direct"assert loaded.load_warnings == ()@@ -2354,7 +2354,7 @@ def test_config_reload_does_not_overwrite_config_changed_during_migration(persist_after_concurrent_save,)- loaded = V2Config.load(config_path=config_path)+ loaded = V2Config.load(config_path=config_path, persist_migrations=True)assert loaded.show_duration is Truepersisted = json.loads(config_path.read_text(encoding="utf-8"))@@ -2393,7 +2393,7 @@ def test_config_reload_does_not_overwrite_config_changed_before_replace(write_after_concurrent_save,)- loaded = V2Config.load(config_path=config_path)+ loaded = V2Config.load(config_path=config_path, persist_migrations=True)assert loaded.show_duration is Truepersisted = json.loads(config_path.read_text(encoding="utf-8"))@@ -2808,7 +2808,7 @@ def test_config_reload_drops_valid_retired_consent_metadata(monkeypatch, tmp_patconfig_path = tmp_path / "config.json"config_path.write_text(json.dumps(payload), encoding="utf-8")- loaded = V2Config.load(config_path=config_path)+ loaded = V2Config.load(config_path=config_path, persist_migrations=True)assert loaded.load_warnings == ()persisted = json.loads(config_path.read_text(encoding="utf-8"))diff --git a/tests/test_model_hub_config_read_compatibility.py b/tests/test_model_hub_config_read_compatibility.pynew file mode 100644index 000000000..1db9e563a--- /dev/null+++ b/tests/test_model_hub_config_read_compatibility.py@@ -0,0 +1,376 @@+"""A newer config observer must not invalidate an older running Hub reader."""++from __future__ import annotations++import asyncio+import json+import stat+from unittest.mock import AsyncMock++import pytest++from config import paths+from config.v2_config import (+ ModelHubConfig,+ ModelHubRouteConfig,+ ModelHubRouteHopConfig,+ V2Config,+ atomic_update_memory,+ update_config_fields,+)+from core.handlers.model_hub.adapter import EngineHealth, EngineStatus+from core.handlers.model_hub.events import BoundedEventLog+from core.handlers.model_hub.service import ModelHubError, ModelHubService, V2ModelHubConfigStore+from core.services import settings+from tests.test_model_hub_resolution import FakeAdapter, _service, _source+from vibe import api, cli, runtime, upgrade++[email protected](autouse=True)+def forbid_live_boundaries(monkeypatch):+ import socket+ import subprocess++ import psutil++ from vibe.native_oauth_store import _SecurityKeychainStore++ def forbidden(*args, **kwargs):+ raise AssertionError("No real process, network, or native credentials in config fixtures")++ monkeypatch.setattr(subprocess, "Popen", forbidden)+ monkeypatch.setattr(socket.socket, "connect", forbidden)+ monkeypatch.setattr(socket.socket, "connect_ex", forbidden)+ monkeypatch.setattr(socket, "getaddrinfo", forbidden)+ for method in ("Process", "pids", "process_iter"):+ monkeypatch.setattr(psutil, method, forbidden)+ for method in ("metadata", "read", "write", "delete"):+ monkeypatch.setattr(_SecurityKeychainStore, method, forbidden)+++def legacy_config(*, enabled=True):+ config = V2Config.default()+ model_id = config.model_hub.agents["codex"].models[0].id+ source = _source("src_fixture409", (model_id,), vendor="openai")+ source.display_name = "升级前的合成来源"+ config.model_hub.sources = [source]+ config.model_hub.agents["codex"].sources.order = [source.id]+ config.model_hub.agents["codex"].routes[model_id] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(source.id, model_id),),+ )+ path = paths.get_config_path()+ config.save(path)+ payload = json.loads(path.read_text(encoding="utf-8"))+ payload["model_hub"].pop("runtime_default_applied")+ payload["model_hub"]["enabled"] = enabled+ payload["unrelated_fixture"] = {"keep": "共享文件不能被观察者改写"}+ path.write_text(json.dumps(payload, ensure_ascii=False) + "\n", encoding="utf-8")+ return path, model_id+++def legacy_service_read(path, monkeypatch):+ """Retain the shipped 3.1.0rc3 top-level Hub field contract.++ Only the old parser's rejection rule is substituted; disk recovery and the+ invocation consumer remain real. An installed historical-reader replay+ additionally checks the full old package outside the portable unit suite.+ """+ parse = ModelHubConfig.from_payload++ def old_parse(cls, payload, **kwargs):+ if isinstance(payload, dict) and set(payload) - {"enabled", "sources", "agents"}:+ raise ValueError("Config 'model_hub' contains unknown fields")+ return parse(payload, **kwargs)++ with monkeypatch.context() as old:+ old.setattr(ModelHubConfig, "from_payload", classmethod(old_parse))+ return V2Config.load(path, persist_migrations=False)+++READERS = (+ "loader",+ "settings",+ "settings_or_default",+ "cli_platform",+ "cli_enabled_platforms",+ "cli_show_target",+ "api",+ "runtime_ensure",+ "upgrade_preflight",+)+++def observe(reader, monkeypatch):+ if reader == "loader":+ V2Config.load()+ elif reader == "settings":+ settings.load_config()+ elif reader == "settings_or_default":+ settings.load_config_or_default()+ elif reader == "cli_platform":+ cli._primary_platform()+ elif reader == "cli_enabled_platforms":+ cli._supported_task_platforms()+ elif reader == "cli_show_target":+ monkeypatch.setattr(runtime, "read_status", lambda: {})+ cli._local_show_events_targets("ses_fixture")+ elif reader == "api":+ api.load_config()+ elif reader == "runtime_ensure":+ runtime.ensure_config()+ else:+ assert reader == "upgrade_preflight"+ upgrade.configured_memory_enabled()++[email protected]("reader", READERS)+def test_new_observer_keeps_old_invocation_resolvable(tmp_path, monkeypatch, reader):+ path, model_id = legacy_config()+ original = path.read_bytes()+ before = legacy_service_read(path, monkeypatch)+ assert before.load_warnings == ()+ service, _, _ = _service(tmp_path, before.model_hub)+ first = service._invocation_resolution(before.model_hub, "codex", model_id)+ assert first.source.id == "src_fixture409"++ observe(reader, monkeypatch)++ after = legacy_service_read(path, monkeypatch)+ resumed = service._invocation_resolution(after.model_hub, "codex", model_id)+ assert resumed.source.id == first.source.id+ assert resumed.target_model == first.target_model+ assert after.load_warnings == ()+ assert path.read_bytes() == original+ assert not list(path.parent.glob("config.json.bak-*"))++[email protected]("reader", READERS)+def test_new_observer_does_not_commit_legacy_disabled_intent(monkeypatch, reader):+ path, _ = legacy_config(enabled=False)+ original = path.read_bytes()++ observe(reader, monkeypatch)++ assert path.read_bytes() == original+ assert not list(path.parent.glob("config.json.bak-*"))++[email protected]("shape", ("enabled", "disabled", "missing-enabled", "missing-hub"))+def test_readers_do_not_activate_an_uncommitted_runtime_default(shape):+ from core.handlers.model_hub.service import V2ModelHubConfigStore++ path, _ = legacy_config(enabled=shape == "enabled")+ payload = json.loads(path.read_text(encoding="utf-8"))+ if shape == "missing-enabled":+ payload["model_hub"].pop("enabled")+ elif shape == "missing-hub":+ payload.pop("model_hub")+ path.write_text(json.dumps(payload), encoding="utf-8")+ original = path.read_bytes()++ assert V2Config.load().model_hub.enabled is (shape == "enabled")+ assert V2ModelHubConfigStore().load().enabled is (shape == "enabled")+ assert path.read_bytes() == original+++def test_failed_startup_commit_cannot_activate_on_next_store_read(monkeypatch):+ import main++ from config import v2_config+ from core.handlers.model_hub.service import V2ModelHubConfigStore++ path, _ = legacy_config(enabled=False)+ original = path.read_bytes()+ monkeypatch.setattr(v2_config, "_backup_config_file", lambda *args, **kwargs: None)++ startup = main.load_config()++ assert startup.load_warnings+ assert startup.model_hub.enabled is False+ assert V2ModelHubConfigStore().load().enabled is False+ assert path.read_bytes() == original+++def test_service_boot_explicitly_commits_once_and_preserves_stop(monkeypatch):+ import main++ from config.v2_config import update_config_fields++ path, _ = legacy_config(enabled=False)+ original = path.read_bytes()+ loaded = main.load_config()+ assert loaded.model_hub.enabled is True+ assert loaded.model_hub.runtime_default_applied is True+ persisted = json.loads(path.read_text(encoding="utf-8"))+ assert persisted["model_hub"]["runtime_default_applied"] is True+ assert persisted["unrelated_fixture"] == json.loads(original)["unrelated_fixture"]+ [backup] = path.parent.glob("config.json.bak-model-hub-migration-*")+ assert backup.read_bytes() == original+ assert stat.S_IMODE(backup.stat().st_mode) == 0o600++ update_config_fields(lambda config: setattr(config.model_hub, "enabled", False))+ stopped = path.read_bytes()+ for _ in range(2):+ assert V2Config.load().model_hub.enabled is False+ assert main.load_config().model_hub.enabled is False+ assert path.read_bytes() == stopped+ assert len(list(path.parent.glob("config.json.bak-*"))) == 1+++def test_rejected_service_cannot_reach_migration(monkeypatch):+ import main++ path, _ = legacy_config()+ original = path.read_bytes()++ def occupied():+ raise runtime.ServiceAlreadyRunningError(lock_path=path.parent / "fixture.lock", holder_pid=42)++ monkeypatch.setattr(main, "acquire_service_instance_lock", occupied)+ with pytest.raises(SystemExit):+ main.main()+ assert path.read_bytes() == original+ assert not list(path.parent.glob("config.json.bak-*"))++[email protected]("writer", ("transaction", "save", "settings_api", "memory"))[email protected]("marker", ("absent", False))[email protected]("enabled", (False, True))+def test_unrelated_writer_keeps_upgrade_pending_until_startup(writer, marker, enabled):+ import main++ path, _ = legacy_config(enabled=enabled)+ original = json.loads(path.read_text(encoding="utf-8"))+ if marker is False:+ original["model_hub"]["runtime_default_applied"] = False+ path.write_text(json.dumps(original), encoding="utf-8")++ if writer == "transaction":+ update_config_fields(lambda config: setattr(config, "language", "zh"))+ elif writer == "save":+ config = V2Config.load()+ config.language = "zh"+ config.save()+ elif writer == "settings_api":+ api.save_config({"language": "zh"}, validate_remote_access_network=False)+ else:+ atomic_update_memory(lambda memory: memory)++ written = json.loads(path.read_text(encoding="utf-8"))+ assert written["model_hub"]["runtime_default_applied"] is False+ assert written["model_hub"]["enabled"] is enabled+ assert written["model_hub"]["sources"] == original["model_hub"]["sources"]+ assert written["model_hub"]["agents"] == original["model_hub"]["agents"]+ if writer != "memory":+ assert written["language"] == "zh"+ assert V2ModelHubConfigStore().load().runtime_default_applied is False+ assert not list(path.parent.glob("config.json.bak-*"))+ pending = path.read_bytes()++ startup = main.load_config()++ assert startup.model_hub.runtime_default_applied is True+ assert startup.model_hub.enabled is True+ [backup] = path.parent.glob("config.json.bak-model-hub-migration-*")+ assert backup.read_bytes() == pending+ after = path.read_bytes()+ assert main.load_config().model_hub.enabled is True+ assert path.read_bytes() == after+++def pending_runtime_service(tmp_path, *, enabled, marker):+ path, _ = legacy_config(enabled=enabled)+ payload = json.loads(path.read_text(encoding="utf-8"))+ for backend in payload["model_hub"]["agents"].values():+ backend["mode"] = "direct"+ if marker is False:+ payload["model_hub"]["runtime_default_applied"] = False+ path.write_text(json.dumps(payload), encoding="utf-8")+ adapter = FakeAdapter()+ adapter.stop_runtime = AsyncMock(return_value=EngineStatus(+ EngineHealth.NOT_STARTED, "fixture", True, "127.0.0.1", None, None,+ ))+ service = ModelHubService(+ store=V2ModelHubConfigStore(),+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "runtime-events.json"),+ )+ return path, service, adapter++[email protected]("action", ("runtime_start", "runtime_stop"))[email protected]("enabled", (False, True))[email protected]("marker", ("absent", False))+def test_explicit_runtime_action_consumes_pending_marker(tmp_path, action, enabled, marker):+ import main++ path, service, adapter = pending_runtime_service(tmp_path, enabled=enabled, marker=marker)+ before = json.loads(path.read_text(encoding="utf-8"))++ outcome = asyncio.run(getattr(service, action)())++ expected = action == "runtime_start"+ assert outcome["enabled"] is expected+ if action == "runtime_stop":+ adapter.stop_runtime.assert_awaited_once()+ written = json.loads(path.read_text(encoding="utf-8"))+ assert written["model_hub"]["runtime_default_applied"] is True+ assert written["model_hub"]["enabled"] is expected+ assert written["model_hub"]["sources"] == before["model_hub"]["sources"]+ assert written["model_hub"]["agents"] == before["model_hub"]["agents"]+ after = path.read_bytes()+ assert main.load_config().model_hub.enabled is expected+ assert path.read_bytes() == after+ assert not list(path.parent.glob("config.json.bak-*"))++[email protected]("failure", ("in-use", "installing", "missing-adapter", "adapter-error"))[email protected]("marker", ("absent", False))+def test_unsuccessful_runtime_stop_does_not_consume_pending_marker(tmp_path, failure, marker):+ import main++ path, service, adapter = pending_runtime_service(tmp_path, enabled=False, marker=marker)+ if failure == "in-use":+ payload = json.loads(path.read_text(encoding="utf-8"))+ payload["model_hub"]["agents"]["codex"]["mode"] = "hub"+ path.write_text(json.dumps(payload), encoding="utf-8")+ elif failure == "installing":+ adapter.stop_runtime.return_value = EngineStatus(+ EngineHealth.INSTALLING, None, False, "127.0.0.1", None, None,+ )+ elif failure == "missing-adapter":+ adapter.stop_runtime = None+ else:+ adapter.stop_runtime.side_effect = RuntimeError("fixture stop failed")+ before = path.read_bytes()++ with pytest.raises(ModelHubError) as caught:+ asyncio.run(service.runtime_stop())++ assert caught.value.code == {+ "in-use": "runtime_in_use",+ "installing": "runtime_busy",+ }.get(failure, "engine_down")+ assert path.read_bytes() == before+ assert V2ModelHubConfigStore().load().runtime_default_applied is False+ assert main.load_config().model_hub.enabled is True++[email protected]("marker", ("absent", False))+def test_runtime_start_failure_retains_explicit_start_intent(tmp_path, marker):+ import main++ path, service, adapter = pending_runtime_service(tmp_path, enabled=False, marker=marker)+ adapter.start = AsyncMock(side_effect=RuntimeError("fixture start failed"))++ with pytest.raises(ModelHubError) as caught:+ asyncio.run(service.runtime_start())++ assert caught.value.code == "engine_down"+ written = json.loads(path.read_text(encoding="utf-8"))+ assert written["model_hub"]["runtime_default_applied"] is True+ assert written["model_hub"]["enabled"] is True+ after = path.read_bytes()+ assert main.load_config().model_hub.enabled is True+ assert path.read_bytes() == after+ assert not list(path.parent.glob("config.json.bak-*"))diff --git a/tests/test_model_hub_legacy_opencode_migration.py b/tests/test_model_hub_legacy_opencode_migration.pyindex 458f77686..39700ec76 100644--- a/tests/test_model_hub_legacy_opencode_migration.py+++ b/tests/test_model_hub_legacy_opencode_migration.py@@ -42,7 +42,7 @@ def _write(tmp_path, payload):def _assert_migrated(path, original):- loaded = V2Config.load(config_path=path)+ loaded = V2Config.load(config_path=path, persist_migrations=True)assert loaded.load_warnings == ()assert loaded.recovered_sections == ()assert loaded.model_hub.enabled is True@@ -217,7 +217,7 @@ def test_legacy_opencode_migration_requires_backup_before_persist(monkeypatch, tpath, original = _write(tmp_path, payload)monkeypatch.setattr(v2_config, "_backup_config_file", lambda *args, **kwargs: None)- loaded = V2Config.load(config_path=path)+ loaded = V2Config.load(config_path=path, persist_migrations=True)assert loaded.model_hub.enabled is Trueassert "could not be backed up" in " ".join(loaded.load_warnings)@@ -241,7 +241,7 @@ def test_legacy_opencode_migration_does_not_replace_concurrent_save(monkeypatch,monkeypatch.setattr(v2_config, "_write_config_payload_if_unchanged", concurrent_write)- loaded = V2Config.load(config_path=path)+ loaded = V2Config.load(config_path=path, persist_migrations=True)assert loaded.show_duration is Falseassert "before replacement" in " ".join(loaded.load_warnings)diff --git a/tests/test_model_hub_runtime_default_upgrade.py b/tests/test_model_hub_runtime_default_upgrade.pyindex 00d7b8149..52d5084a4 100644--- a/tests/test_model_hub_runtime_default_upgrade.py+++ b/tests/test_model_hub_runtime_default_upgrade.py@@ -75,7 +75,7 @@ def test_old_install_promotes_once_and_backs_up_exact_snapshot(tmp_path, enabledoriginal["model_hub"]["runtime_default_applied"] = Falsepath, raw = write_config(tmp_path, original)- loaded = V2Config.load(config_path=path)+ loaded = V2Config.load(config_path=path, persist_migrations=True)assert loaded.load_warnings == ()assert loaded.model_hub.enabled is True@@ -102,7 +102,7 @@ def test_default_upgrade_composes_with_existing_shape_migration(tmp_path, alreadpayload["model_hub"]["priority_order"] = []path, original = write_config(tmp_path, payload)- loaded = V2Config.load(config_path=path)+ loaded = V2Config.load(config_path=path, persist_migrations=True)assert loaded.load_warnings == ()assert loaded.model_hub.enabled is (not already_applied)@@ -127,7 +127,7 @@ def test_legacy_omissions_never_consent_to_native_takeover(tmp_path, shape):original["model_hub"]["agents"]["claude"]["mode"] = "hub"path, _ = write_config(tmp_path, original)- loaded = V2Config.load(config_path=path)+ loaded = V2Config.load(config_path=path, persist_migrations=True)assert loaded.load_warnings == ()assert loaded.model_hub.enabled is True@@ -141,7 +141,7 @@ def test_legacy_omissions_never_consent_to_native_takeover(tmp_path, shape):def test_runtime_stop_after_upgrade_survives_subsequent_loads(tmp_path):path, _ = write_config(tmp_path, legacy_payload(tmp_path))- V2Config.load(config_path=path)+ V2Config.load(config_path=path, persist_migrations=True)# This is the real narrow config transaction used by the Model Hub store.stopped = update_config_fields(lambda cfg: setattr(cfg.model_hub, "enabled", False),@@ -166,6 +166,8 @@ def test_service_runtime_stop_round_trips_real_store_with_fake_runtime(tmp_path,payload = legacy_payload(tmp_path)path, _ = write_config(tmp_path, payload)monkeypatch.setattr(v2_config.paths, "get_config_path", lambda: path)+ # Real service startup commits the upgrade before constructing this store.+ V2Config.load(config_path=path, persist_migrations=True)stop = AsyncMock(return_value=EngineStatus(health=EngineHealth.NOT_STARTED,installed_version=None,@@ -279,11 +281,11 @@ def test_unrelated_recovery_defers_old_default_upgrade(tmp_path, shape):assert path.read_bytes() == original-def test_read_only_preview_does_not_persist_or_create_upgrade_backup(tmp_path):+def test_read_only_load_preserves_runtime_intent_without_upgrade_backup(tmp_path):path, original = write_config(tmp_path, legacy_payload(tmp_path))loaded = V2Config.load(config_path=path, persist_migrations=False)- assert loaded.model_hub.enabled is True- assert loaded.model_hub.runtime_default_applied is True+ assert loaded.model_hub.enabled is False+ assert loaded.model_hub.runtime_default_applied is Falseassert path.read_bytes() == originalassert not list(path.parent.glob("config.json.bak-*"))@@ -301,7 +303,7 @@ def test_both_fields_are_written_in_one_compare_and_swap(tmp_path, monkeypatch):return write(target, upgraded, expected_raw)monkeypatch.setattr(v2_config, "_write_config_payload_if_unchanged", capture)- V2Config.load(config_path=path)+ V2Config.load(config_path=path, persist_migrations=True)assert len(calls) == 1assert read_config(path) == calls[0]@@ -319,7 +321,7 @@ def test_failed_persistence_does_not_activate_or_stamp_the_upgrade(tmp_path, monmonkeypatch.setattr(v2_config, "_backup_config_file", lambda *a, **kw: None)else:monkeypatch.setattr(v2_config, "_persist_migrated_config_payload", Mock(side_effect=OSError("fixture refusal")))- loaded = V2Config.load(config_path=path)+ loaded = V2Config.load(config_path=path, persist_migrations=True)assert loaded.model_hub.enabled is Falseassert loaded.model_hub.runtime_default_applied is Falseassert loaded.load_warnings@@ -343,7 +345,7 @@ def test_concurrent_new_stop_wins_over_upgrade_snapshot(tmp_path, monkeypatch):return persist(target, expected_raw, upgraded)monkeypatch.setattr(v2_config, "_persist_migrated_config_payload", concurrent_save)- loaded = V2Config.load(config_path=path)+ loaded = V2Config.load(config_path=path, persist_migrations=True)assert loaded.model_hub.enabled is Falseassert loaded.model_hub.runtime_default_applied is Trueassert loaded.show_duration is True