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(config): scope recovery save refusal to recovered sections (#2237)
Call White01cf5dc4df0f
diff --git a/config/v2_config.py b/config/v2_config.pyindex 5a4768ece..202bea067 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -1200,6 +1200,213 @@ def _reset_recoverable_config_section(return False+# A config path is a tuple of object keys from the document root. Recovery+# regions are tracked at most two keys deep: deep enough to keep one recovered+# Agent backend or one field-scoped setting apart from its siblings, shallow+# enough that a replaced section is compared and preserved as one value.+_RECOVERY_REGION_DEPTH = 2+_MISSING = object()+_RECOVERY_SAVE_REFUSAL = (+ "Config was loaded with recovery warnings; repair the backed-up "+ "config before saving changes"+)+++def _config_json_text(value: object) -> Optional[str]:+ """Order-independent JSON identity of a stored value; ``None`` when absent."""++ if value is _MISSING:+ return None+ return json.dumps(value, sort_keys=True, default=repr)+++def _config_value_at(document: object, path: tuple[str, ...]) -> object:+ value = document+ for key in path:+ if not isinstance(value, dict) or key not in value:+ return _MISSING+ value = value[key]+ return value+++def _changed_config_paths(+ before: object, after: object, prefix: tuple[str, ...] = ()+) -> set[tuple[str, ...]]:+ """Where one recovery step rewrote the stored document."""++ if _config_json_text(before) == _config_json_text(after):+ return set()+ if (+ len(prefix) >= _RECOVERY_REGION_DEPTH+ or not isinstance(before, dict)+ or not isinstance(after, dict)+ ):+ return {prefix}+ changed: set[tuple[str, ...]] = set()+ for key in dict.fromkeys((*before, *after)):+ changed |= _changed_config_paths(+ before.get(key, _MISSING), after.get(key, _MISSING), (*prefix, key)+ )+ return changed+++def _recovered_write_regions(+ regions: dict[tuple[str, ...], set[str]], candidate: dict+) -> tuple[tuple[tuple[str, ...], tuple[str, ...]], ...]:+ """Close recovery's rewritten paths over the values ``from_payload`` derives.++ A save writes derived values from memory, so when recovery rewrote their+ source the derived value would describe the recovered defaults instead of+ the preserved file: the legacy ``platform`` mirrors ``platforms.primary``,+ a forced-off ``audio_asr.enabled`` marks the switch as configured, and an+ absent ``setup_completed`` is inferred from the configured platforms.+ """++ regions = {path: set(causes) for path, causes in regions.items()}++ def follow(target: tuple[str, ...], is_source: Callable[[tuple[str, ...]], bool]) -> None:+ causes = set().union(*(owners for path, owners in regions.items() if is_source(path)))+ if causes:+ regions.setdefault(target, set()).update(causes)++ follow(("platform",), lambda path: path[0] == "platforms")+ follow(+ ("audio_asr", "enabled_configured"),+ lambda path: path == ("audio_asr", "enabled")[: len(path)],+ )+ if "setup_completed" not in candidate:+ setup_sources = {"mode", "platforms", "platform"} | {+ descriptor.config_key for descriptor in platform_descriptors()+ }+ follow(("setup_completed",), lambda path: path[0] in setup_sources)++ # A path inside another region is already preserved with it.+ merged: dict[tuple[str, ...], set[str]] = {}+ for path in sorted(regions, key=len):+ owner = next((region for region in merged if path[: len(region)] == region), None)+ merged.setdefault(owner or path, set()).update(regions[path])+ return tuple((path, tuple(sorted(causes))) for path, causes in sorted(merged.items()))+++@dataclass(frozen=True)+class _RecoveredSectionGuard:+ """Write fence for a config whose sections were recovered at load (#2079).++ Recovery keeps strict parsing and substitutes safe defaults in memory. Those+ defaults must never become the file: a save that leaves every recovered+ region as loaded writes each region back from the file on disk, and a save+ that changes one is refused before anything is written.+ """++ warnings: tuple[str, ...]+ regions: tuple[tuple[tuple[str, ...], tuple[str, ...]], ...]+ loaded: tuple[Optional[str], ...]+ backup: Optional[str]++ @classmethod+ def capture(+ cls,+ config: "V2Config",+ warnings: tuple[str, ...],+ regions: tuple[tuple[tuple[str, ...], tuple[str, ...]], ...],+ backup: Optional[Path],+ ) -> "_RecoveredSectionGuard":+ document = config._persisted_document()+ return cls(+ warnings=warnings,+ regions=regions,+ loaded=tuple(_config_json_text(_config_value_at(document, path)) for path, _ in regions),+ backup=str(backup) if backup is not None else None,+ )++ def refusal(self, touched: list[tuple[tuple[str, ...], tuple[str, ...]]]) -> str:+ sections = sorted({section for _, causes in touched for section in causes})+ changed = ", ".join(".".join(path) for path, _ in touched)+ return (+ f"Config was loaded with recovery warnings for {', '.join(sections)}; "+ f"repair the backed-up config ({self.backup or 'backup unavailable'}) "+ f"before changing {changed}"+ )++ def change_refusal(self, document: dict) -> Optional[str]:+ touched = [+ region+ for region, loaded in zip(self.regions, self.loaded)+ if _config_json_text(_config_value_at(document, region[0])) != loaded+ ]+ return self.refusal(touched) if touched else None++ def scope_refusal(self, sections: tuple[str, ...]) -> Optional[str]:+ touched = [region for region in self.regions if region[0][0] in sections]+ return self.refusal(touched) if touched else None++ def preserve_stored_regions(self, path: Path, document: dict) -> dict:+ """Replace each recovered region with what the file holds now.++ The current file, not the bytes read at load: a region repaired or+ rewritten by another writer since then is kept as it now stands.+ """++ try:+ stored = json.loads(path.read_bytes().decode("utf-8"))+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise ValueError(+ "Config was loaded with recovery warnings and its recovered sections "+ f"could not be re-read before saving: {exc}"+ ) from exc+ if not isinstance(stored, dict):+ raise ValueError(+ "Config was loaded with recovery warnings and the file on disk is no "+ "longer an object; repair it before saving changes"+ )+ for region, _ in self.regions:+ stored_parent = _config_value_at(stored, region[:-1])+ written_parent = _config_value_at(document, region[:-1])+ if not isinstance(written_parent, dict) or (+ stored_parent is not _MISSING and not isinstance(stored_parent, dict)+ ):+ raise ValueError(+ "Config was loaded with recovery warnings and "+ f"'{'.'.join(region)}' can no longer be preserved; repair the "+ "config before saving changes"+ )+ value = stored_parent.get(region[-1], _MISSING) if isinstance(stored_parent, dict) else _MISSING+ if value is _MISSING:+ written_parent.pop(region[-1], None)+ else:+ written_parent[region[-1]] = value+ return document+++def _active_recovery_guard(config: object) -> Optional[_RecoveredSectionGuard]:+ guard = getattr(config, "_recovery_guard", None)+ warnings = tuple(getattr(config, "load_warnings", ()) or ())+ if not isinstance(guard, _RecoveredSectionGuard) or not warnings or guard.warnings != warnings:+ return None+ return guard+++# Model Hub writes and native Agent credential writes move both sections: the+# native takeover migrates Agent backend settings into the Hub.+AGENT_CREDENTIAL_SECTIONS = ("model_hub", "agents")+++def config_recovery_refusal(config: object, *sections: str) -> Optional[str]:+ """Why a writer owning ``sections`` must wait for the config to be repaired.++ Section recovery blocks only the writers of the recovered sections; every+ other warning (migration, persistence, whole-document recovery) still blocks+ every writer. ``V2Config.save`` enforces the same regions on the final write.+ """++ if not getattr(config, "load_warnings", ()):+ return None+ guard = _active_recovery_guard(config)+ if guard is None:+ return _RECOVERY_SAVE_REFUSAL+ return guard.scope_refusal(sections)++def _backup_config_file(path: Path,label: str,@@ -3148,6 +3355,10 @@ class V2Config:load_warnings: ClassVar[tuple[str, ...]] = ()recovered_sections: ClassVar[tuple[str, ...]] = ()whole_config_recovery: ClassVar[bool] = False+ # Where section recovery rewrote the stored document, and the write fence+ # built from it by ``load``. Both are non-persisted, like the diagnostics.+ _recovered_regions: ClassVar[tuple[tuple[tuple[str, ...], tuple[str, ...]], ...]] = ()+ _recovery_guard: ClassVar[Optional[_RecoveredSectionGuard]] = None@classmethoddef default(cls) -> "V2Config":@@ -3258,6 +3469,18 @@ class V2Config:# unrelated malformed section. Preserve an already enabled Hub# only when its own config could be parsed safely.config.model_hub.enabled = config.model_hub.enabled and previous_runtime_enabled+ if (+ "model_hub" not in recovered_sections+ and not whole_config_recovery+ and not (+ isinstance(migrated_payload.get("model_hub"), dict)+ and migrated_payload["model_hub"].get("runtime_default_applied") is True+ )+ ):+ # Section recovery permits unrelated saves, and like a clean+ # read-only load they must not acknowledge an upgrade no one+ # performed.+ config.model_hub.runtime_default_applied = Falseall_warnings = tuple(dict.fromkeys((*migration_warnings, *recovery_warnings)))if (persist_migrations@@ -3304,6 +3527,10 @@ class V2Config:"Started with a recovered config; original file preserved at %s",backup,)+ if config._recovered_regions and not migration_warnings:+ config._recovery_guard = _RecoveredSectionGuard.capture(+ config, all_warnings, config._recovered_regions, backup+ )config.load_warnings = all_warningsconfig.recovered_sections = tuple(sorted(recovered_sections))config.whole_config_recovery = whole_config_recovery@@ -3314,6 +3541,7 @@ class V2Config:"""Parse stored data with recovery defaults, without file IO or locks."""recovery_warnings: list[str] = []recovered_sections: set[str] = set()+ rewritten: dict[tuple[str, ...], set[str]] = {}whole_config_recovery = Falsewhile True:try:@@ -3334,6 +3562,7 @@ class V2Config:recovery_warnings.append(warning)whole_config_recovery = Truebreak+ before_reset = copy.deepcopy(candidate)if not _reset_recoverable_config_section(candidate, section, field_name):warning = f"Config section '{section}' could not be recovered; using recovery defaults: {exc}"logger.error("%s", warning)@@ -3341,12 +3570,21 @@ class V2Config:recovery_warnings.append(warning)whole_config_recovery = Truebreak+ # Diff each reset on its own: ``from_payload`` normalizes a few+ # stored values in place, and those are not recovery's rewrites.+ for path in {+ tuple(recovered.split(".", 1)),+ *_changed_config_paths(before_reset, candidate),+ }:+ rewritten.setdefault(path, set()).add(recovered)recovered_sections.add(recovered)recovery_warnings.append(f"Recovered invalid config section '{recovered}': {exc}")config.load_warnings = tuple(recovery_warnings)config.recovered_sections = tuple(sorted(recovered_sections))config.whole_config_recovery = whole_config_recovery+ if rewritten and not whole_config_recovery:+ config._recovered_regions = _recovered_write_regions(rewritten, candidate)return config@classmethod@@ -3706,23 +3944,58 @@ class V2Config:which loads fresh inside the cross-process file lock and onlyapplies the caller's fields. Direct load → mutate → ``save()``cycles are only acceptable in single-writer contexts.++ A config loaded with section recovery saves only while every recovered+ region still holds what was loaded; those regions are written from the+ file as it stands, never from the recovery defaults in memory. Any other+ load warning refuses the save."""- if self.load_warnings:- raise ValueError(- "Config was loaded with recovery warnings; repair the backed-up "- "config before saving changes"- )+ refusal = self.pending_write_refusal()+ if refusal is not None:+ raise ValueError(refusal)paths.ensure_data_dirs()path = config_path or paths.get_config_path()with config_file_lock(path):self._write_locked(path)+ def pending_write_refusal(self) -> Optional[str]:+ """Why saving this snapshot would be refused, before anything runs."""++ if not self.load_warnings:+ return None+ guard = _active_recovery_guard(self)+ if guard is None:+ return _RECOVERY_SAVE_REFUSAL+ return guard.change_refusal(self._persisted_document())++ def inherit_load_diagnostics(self, loaded: "V2Config") -> None:+ """Hold a snapshot derived from ``loaded`` to that load's recovery state."""++ self.load_warnings = loaded.load_warnings+ self.recovered_sections = loaded.recovered_sections+ self.whole_config_recovery = loaded.whole_config_recovery+ self._recovery_guard = loaded._recovery_guard+def _write_locked(self, path: Path) -> None:"""Write an exact snapshot while the config transaction is held."""self.platforms.validate()self.platform = self.platforms.primary+ guard = _active_recovery_guard(self)+ if guard is None:+ _write_config_payload(path, self._persisted_payload())+ return+ _write_config_payload(+ path, guard.preserve_stored_regions(path, self._persisted_document())+ )++ def _persisted_document(self) -> dict:+ """The saved form as plain JSON values, detached from this object."""++ return json.loads(json.dumps(self._persisted_payload()))++ def _persisted_payload(self) -> dict:platform_payload = {}for descriptor in platform_descriptors():descriptor_config = descriptor.get_config(self)@@ -3733,7 +4006,7 @@ class V2Config:config_payload.pop("guild_denylist", None)platform_payload[descriptor.config_key] = config_payloadpayload = {- "platform": self.platform,+ "platform": self.platforms.primary,"platforms": {"enabled": self.platforms.enabled,"primary": self.platforms.primary,@@ -3781,7 +4054,7 @@ class V2Config:"agent_status_no_output_ms": self.agent_status_no_output_ms,"setup_completed": self.setup_completed,}- _write_config_payload(path, payload)+ return payloaddef enabled_platforms(self) -> list[str]:return list(self.platforms.enabled)diff --git a/core/backend_restart.py b/core/backend_restart.pyindex e4f3b6142..0154676e5 100644--- a/core/backend_restart.py+++ b/core/backend_restart.py@@ -133,7 +133,7 @@ class NativeCredentialLease:use Hub instead. Read without load-time migration writes: this is anadmission check."""- from config.v2_config import V2Config+ from config.v2_config import AGENT_CREDENTIAL_SECTIONS, V2Config, config_recovery_refusalself.assert_owned(backend)try:@@ -142,7 +142,9 @@ class NativeCredentialLease:config = V2Config.default()except (OSError, TypeError, ValueError):raise NativeMigrationBlockedError("config_recovery", (backend,)) from None- if config.load_warnings:+ # Custody reads ``model_hub``; native writers also act on the backend's+ # Agent settings. Recovery elsewhere leaves both trustworthy.+ if config_recovery_refusal(config, *AGENT_CREDENTIAL_SECTIONS) is not None:raise NativeMigrationBlockedError("config_recovery", (backend,))hub = config.model_hubif hub.agents[backend].mode == "direct":diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 4e47f1daa..17025d0f7 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -32,6 +32,8 @@ from config.v2_config import (ModelHubSourceStateConfig,ModelHubSourceUsageConfig,V2Config,+ AGENT_CREDENTIAL_SECTIONS,+ config_recovery_refusal,normalize_storable_backend_model_text,normalize_model_hub_base_url,normalize_model_hub_vendor_id,@@ -385,7 +387,8 @@ class V2ModelHubConfigStore:config = V2Config.load()except FileNotFoundError:return- if config.load_warnings:+ # Hub writes also move Agent backend settings (native migration).+ if config_recovery_refusal(config, *AGENT_CREDENTIAL_SECTIONS) is not None:raise ModelHubError("config_recovery", status=409)def save(self, model_hub: ModelHubConfig) -> None:diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.pyindex 6b2a4d8ef..42c1b76e5 100644--- a/tests/test_api_save_config_merge.py+++ b/tests/test_api_save_config_merge.py@@ -14,6 +14,7 @@ import pytestsys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from config import pathsfrom config.v2_config import (_FIELD_SCOPED_RECOVERY_SECTIONS,AudioAsrConfig,@@ -1464,6 +1465,155 @@ def test_malformed_cloud_section_is_refused_on_writes_and_recovered_on_disk(tmp__assert_degrades(config)+def _seed_recovered_config(tmp_path, monkeypatch, sqlite_schema_db_factory, corrupt) -> tuple[Path, dict]:+ """Store a valid config through the real save, then corrupt it on disk."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")+ api.save_config(_full_config_payload())+ config_path = paths.get_config_path()+ stored = json.loads(config_path.read_text(encoding="utf-8"))+ corrupt(stored)+ config_path.write_text(json.dumps(stored), encoding="utf-8")+ return config_path, stored+++def _refuse_model_hub_change(config_path: Path) -> None:+ # ``/api/config`` drops ``model_hub``; Hub writes reach the file through+ # ``V2Config.save``.+ config = V2Config.load(config_path)+ config.model_hub.enabled = not config.model_hub.enabled+ config.save(config_path)+++ ("region", "corrupt", "change"),+ [+ pytest.param(+ ("model_hub",),+ # A newer release's field this build does not know (#2081).+ lambda stored: stored["model_hub"].update({"routing_v3": {"enabled": True}}),+ _refuse_model_hub_change,+ id="model_hub-newer-release",+ ),+ pytest.param(+ ("slack",),+ lambda stored: stored["slack"].update({"bot_token": 123}),+ lambda _path: api.save_config({"slack": {"require_mention": True}}),+ id="slack",+ ),+ pytest.param(+ ("audio_asr",),+ lambda stored: stored["audio_asr"].update({"enabled": "maybe"}),+ lambda _path: api.save_config({"audio_asr": {"enabled": True}}),+ id="audio_asr-field",+ ),+ pytest.param(+ ("agents", "codex"),+ lambda stored: stored["agents"].update({"codex": "broken"}),+ lambda _path: api.save_config({"agents": {"codex": {"cli_path": "codex-next"}}}),+ id="agents-codex",+ ),+ ],+)+def test_recovered_section_is_saved_as_stored_and_only_its_changes_are_refused(+ tmp_path, monkeypatch, sqlite_schema_db_factory, region, corrupt, change,+):+ """#2079: one recovered section must not lock out every config write.++ Load still recovers the section in memory behind a warning and a backup.+ A save that leaves it alone succeeds and writes the section back exactly+ as stored, never as the recovery defaults held in memory. A save that+ changes it is refused, names the section and the backup, and writes+ nothing.+ """+ config_path, stored = _seed_recovered_config(tmp_path, monkeypatch, sqlite_schema_db_factory, corrupt)+ loaded = V2Config.load(config_path)+ assert loaded.recovered_sections+ recovered = api.config_to_payload(loaded, include_secrets=True, include_internal=True)+ # Otherwise "defaults never written" below would hold trivially.+ assert _walk(recovered, region, attr=False) != _walk(stored, region, attr=False)++ # An unrelated settings save and a direct save both succeed.+ api.save_config({"show_duration": True})+ loaded = V2Config.load(config_path)+ loaded.ui.open_browser = not loaded.ui.open_browser+ loaded.save(config_path)++ persisted = json.loads(config_path.read_text(encoding="utf-8"))+ assert persisted["show_duration"] is True+ assert persisted["ui"]["open_browser"] is loaded.ui.open_browser+ assert _walk(persisted, region, attr=False) == _walk(stored, region, attr=False)+ reloaded = V2Config.load(config_path)+ assert reloaded.recovered_sections == loaded.recovered_sections+ assert reloaded.load_warnings++ before = config_path.read_bytes()+ with pytest.raises(ValueError, match="recovery warnings for ") as refused:+ change(config_path)+ assert config_path.read_bytes() == before+ for section in reloaded.recovered_sections:+ assert section in str(refused.value)+ assert ".bak-recovery-" in str(refused.value)+++def test_recovered_section_save_keeps_the_current_disk_value_not_the_loaded_copy(+ tmp_path, monkeypatch, sqlite_schema_db_factory,+):+ """#2079: a recovered section is spliced from the file at write time.++ Another writer may replace the section between this process's load and+ its save. Writing back the copy seen at load time would undo that write.+ """+ config_path, _stored = _seed_recovered_config(+ tmp_path,+ monkeypatch,+ sqlite_schema_db_factory,+ lambda stored: stored["model_hub"].update({"routing_v3": {"enabled": True}}),+ )+ loaded = V2Config.load(config_path)+ assert "model_hub" in loaded.recovered_sections++ concurrent = json.loads(config_path.read_text(encoding="utf-8"))+ concurrent["model_hub"]["routing_v3"] = {"enabled": False, "hops": 2}+ config_path.write_text(json.dumps(concurrent), encoding="utf-8")++ loaded.show_duration = True+ loaded.save(config_path)++ persisted = json.loads(config_path.read_text(encoding="utf-8"))+ assert persisted["show_duration"] is True+ assert persisted["model_hub"] == concurrent["model_hub"]+++def test_unrelated_save_under_recovery_does_not_acknowledge_the_model_hub_upgrade(+ tmp_path, monkeypatch, sqlite_schema_db_factory,+):+ """A save allowed during recovery must not complete a pending Hub upgrade.++ A clean load of a file without the runtime-default marker still owes the+ upgrade. Recovering an unrelated section skips it, and the save that+ recovery now permits must not persist the marker as done.+ """++ def _corrupt(stored: dict) -> None:+ stored["slack"]["bot_token"] = 123+ stored["model_hub"].pop("runtime_default_applied")+ stored["model_hub"]["enabled"] = False++ config_path, _stored = _seed_recovered_config(tmp_path, monkeypatch, sqlite_schema_db_factory, _corrupt)+ api.save_config({"show_duration": True})++ persisted = json.loads(config_path.read_text(encoding="utf-8"))+ assert persisted["model_hub"].get("runtime_default_applied") is not True++ persisted["slack"]["bot_token"] = ""+ config_path.write_text(json.dumps(persisted), encoding="utf-8")+ repaired = V2Config.load(config_path, persist_migrations=True)+ assert repaired.load_warnings == ()+ assert repaired.model_hub.enabled is True+ assert repaired.model_hub.runtime_default_applied is True++def _settings_write_paths() -> list[tuple[str, ...]]:"""Every preference path the shared Settings pages may write.diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex c43a111d7..9beeb0f09 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -29,7 +29,7 @@ from config.v2_config import (V2Config,is_model_hub_enabled,)-from core.handlers.model_hub.service import ModelHubService+from core.handlers.model_hub.service import ModelHubError, ModelHubService, V2ModelHubConfigStorefrom core.services.settings import default_configfrom core.handlers.model_hub.adapter import (DiscoveredModel,@@ -2350,11 +2350,43 @@ def test_config_reload_recovers_invalid_optional_section_without_overwriting_filV2Config.load(config_path=config_path)assert len(list(config_path.parent.glob("config.json.bak-recovery-*"))) == 1- monkeypatch.setattr(api, "load_config", lambda: loaded)- with pytest.raises(ValueError, match="recovery warnings"):- api.save_config({"show_duration": True})- with pytest.raises(ValueError, match="recovery warnings"):+ # #2079: the recovered defaults never reach the file. A save that leaves+ # model_hub alone writes it back as stored; changing it is refused.+ loaded.show_duration = True+ loaded.save(config_path)+ persisted = json.loads(config_path.read_text(encoding="utf-8"))+ assert persisted["show_duration"] is True+ assert persisted["model_hub"] == payload["model_hub"]+ before = config_path.read_bytes()+ loaded.model_hub.enabled = not loaded.model_hub.enabled+ with pytest.raises(ValueError, match="recovery warnings for model_hub"):loaded.save(config_path)+ assert config_path.read_bytes() == before+++ ("corrupt", "blocked"),+ [+ pytest.param(lambda stored: stored["model_hub"].update({"routing_v3": {}}), True, id="model_hub"),+ pytest.param(lambda stored: stored["agents"].update({"codex": "broken"}), True, id="agents-codex"),+ pytest.param(lambda stored: stored["slack"].update({"bot_token": 123}), False, id="slack"),+ ],+)+def test_hub_writes_wait_only_for_recovered_credential_sections(monkeypatch, tmp_path, corrupt, blocked):+ """#2079: Hub writes read ``model_hub`` and move Agent settings, nothing else."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)+ corrupt(payload)+ config_path = tmp_path / "config" / "config.json"+ config_path.parent.mkdir()+ config_path.write_text(json.dumps(payload), encoding="utf-8")+ assert V2Config.load().recovered_sections++ if blocked:+ with pytest.raises(ModelHubError, match="config_recovery"):+ V2ModelHubConfigStore().ensure_writable()+ else:+ V2ModelHubConfigStore().ensure_writable()@pytest.mark.parametrize(@@ -3099,8 +3131,14 @@ def test_invalid_empty_route_key_keeps_v2_recovery_fence(tmp_path, backend, bad_assert loaded.model_hub.sources == []assert all(agent.mode == "direct" for agent in loaded.model_hub.agents.values())assert path.read_bytes() == before- with pytest.raises(ValueError, match="recovery warnings"):+ # #2079: the fence is on the recovered section, not on every save.+ loaded.save(config_path=path)+ assert json.loads(path.read_text())["model_hub"] == payload["model_hub"]+ before = path.read_bytes()+ loaded.model_hub.enabled = not loaded.model_hub.enabled+ with pytest.raises(ValueError, match="recovery warnings for model_hub"):loaded.save(config_path=path)+ assert path.read_bytes() == before@pytest.mark.parametrize(diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.pyindex 11f7dc59d..6f84ea516 100644--- a/tests/test_remote_access_vibe_cloud.py+++ b/tests/test_remote_access_vibe_cloud.py@@ -3562,6 +3562,58 @@ def test_pair_preflight_failure_never_reaches_the_redeem(monkeypatch, tmp_path)assert not sealed_dir.exists() or not any(sealed_dir.glob("*.json"))+def test_pair_saves_past_a_recovered_model_hub_and_keeps_it_as_stored(monkeypatch, tmp_path) -> None:+ """#2079: a newer release's ``model_hub`` field must not block pairing.++ Pairing writes only ``remote_access``. The recovered ``model_hub`` is+ written back exactly as stored, never as the defaults held in memory, and+ the next load still reports it.+ """+ _prepare_pairing_environment(monkeypatch, tmp_path)+ monkeypatch.setattr(remote_access, "_json_request", lambda *args, **kwargs: dict(_PAIRING_RESPONSE))+ config_path = paths.get_config_path()+ stored = json.loads(config_path.read_text(encoding="utf-8"))+ stored["model_hub"]["routing_v3"] = {"enabled": True}+ config_path.write_text(json.dumps(stored), encoding="utf-8")++ result = remote_access.pair("vrp_test", "https://backend.test")++ assert result["ok"] is True, result+ persisted = json.loads(config_path.read_text(encoding="utf-8"))+ assert persisted["model_hub"] == stored["model_hub"]+ reloaded = V2Config.load(config_path)+ assert reloaded.recovered_sections == ("model_hub",)+ assert reloaded.remote_access.vibe_cloud.instance_id == "inst_123"+ assert reloaded.remote_access.vibe_cloud.tunnel_token == "tunnel-token"+++ ("section", "corrupt", "refused"),+ [+ ("model_hub", lambda stored: stored["model_hub"].update({"routing_v3": {"enabled": True}}), False),+ ("remote_access", lambda stored: stored["remote_access"]["vibe_cloud"].update({"instance_id": 12345}), True),+ ],+)+def test_pair_preflight_refuses_only_a_recovered_remote_access(+ monkeypatch, tmp_path, section, corrupt, refused+) -> None:+ """#2079: pairing changes ``remote_access``, so only that recovery blocks it."""+ _prepare_pairing_environment(monkeypatch, tmp_path)+ config_path = paths.get_config_path()+ stored = json.loads(config_path.read_text(encoding="utf-8"))+ corrupt(stored)+ config_path.write_text(json.dumps(stored), encoding="utf-8")+ assert V2Config.load(config_path).recovered_sections == (section,)++ refusal = remote_access._pairing_local_write_preflight()++ if refused:+ assert "recovery warnings for remote_access" in refusal+ assert ".bak-recovery-" in refusal+ else:+ assert refusal is None++def test_pair_save_failure_after_redeem_reports_the_orphaned_binding(monkeypatch, tmp_path) -> None:"""#2080: a post-redeem save failure names the orphaned binding, not a traceback."""_prepare_pairing_environment(monkeypatch, tmp_path)diff --git a/vibe/api.py b/vibe/api.pyindex 60cbd4f62..9dffbf319 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -32,6 +32,8 @@ from config.v2_config import (CONFIG_LOCK,V2Config,config_file_lock,+ AGENT_CREDENTIAL_SECTIONS,+ config_recovery_refusal,)from config.v2_settings import (SettingsStore,@@ -636,13 +638,19 @@ def config_recovery_notice(config: V2Config) -> Optional[str]:def _config_recovery_message() -> Optional[str]:- """Return a localized guard message before mutating backend-owned auth files."""+ """Return a localized guard message before mutating backend-owned auth files.++ Credential custody is decided by ``model_hub`` and the Agent backend+ settings; recovery of any other section leaves both readable.+ """with CONFIG_LOCK:try:config = load_config()except FileNotFoundError:return None+ if config_recovery_refusal(config, *AGENT_CREDENTIAL_SECTIONS) is None:+ return Nonereturn config_recovery_notice(config)@@ -1014,11 +1022,6 @@ def save_config(base_config: Optional[V2Config] = Nonetry:base_config = load_config()- if base_config.load_warnings:- raise ValueError(- "Config was loaded with recovery warnings; repair the backed-up "- "config before saving changes"- )base_payload = config_to_payload(base_config, include_secrets=True, include_internal=True)except FileNotFoundError:# Fresh install: seed the same workbench-only default served by the read side.@@ -1053,6 +1056,13 @@ def save_config(merged_payload = _merge_legacy_discord_guild_scope_fields(merged_payload, payload, base_config)sanitized_payload, guild_scope_update = _extract_settings_scopes_from_config_payload(merged_payload)config = V2Config.from_payload(sanitized_payload)+ if base_config is not None:+ # A recovered base section must reach the file as stored, never as+ # the defaults merged in above. Refuse before any side effect below.+ config.inherit_load_diagnostics(base_config)+ recovery_refusal = config.pending_write_refusal()+ if recovery_refusal is not None:+ raise ValueError(recovery_refusal)if not context.can_manage_access_members:from core.services.settings import default_configdiff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex d6662ff28..65ebd50d7 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -39,7 +39,7 @@ from jwt import PyJWKClientfrom config import pathsfrom config.atomic_io import write_atomic-from config.v2_config import CONFIG_LOCK, V2Config, config_file_lock+from config.v2_config import CONFIG_LOCK, V2Config, config_file_lock, config_recovery_refusalfrom vibe import api, cloudflare_network, runtimefrom vibe import tunnel_quality@@ -4877,13 +4877,15 @@ def _pairing_local_write_preflight() -> str | None:"""Return a reason when the local config cannot durably accept a pairing.Runs BEFORE the one-time redeem so a predictable local failure never- consumes the pairing key (#2080). ``V2Config.load()`` recovery warnings are- the same condition ``api.save_config`` refuses on, so they fail here too.+ consumes the pairing key (#2080). The pairing save writes only+ ``remote_access``; ``api.save_config`` refuses it on the same recovery+ condition checked here (#2079)."""try:loaded = V2Config.load()- if loaded.load_warnings:- return "config was loaded with recovery warnings; repair the backed-up config before pairing"+ recovery_refusal = config_recovery_refusal(loaded, "remote_access")+ if recovery_refusal is not None:+ return recovery_refusalexcept FileNotFoundError:pass # fresh install: save_config seeds defaultsexcept Exception as exc: