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(memory): harden cloud transition fences
cyhcb17769ef42b
diff --git a/config/v2_config.py b/config/v2_config.pyindex 15bd2a4cb..f5d10acf8 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -1799,6 +1799,7 @@ class MemoryCloudConfig:source_instance_id: str = ""organization_attached: bool = Falsetransition_notice_pending: bool = False+ transition_rebuild_owned: bool = Falseapplied_embedding_identity: str | None = Noneruntime_apply_pending: bool = False@@ -1828,6 +1829,7 @@ class MemoryCloudConfig:("quota_enforced", self.quota_enforced),("organization_attached", self.organization_attached),("transition_notice_pending", self.transition_notice_pending),+ ("transition_rebuild_owned", self.transition_rebuild_owned),("runtime_apply_pending", self.runtime_apply_pending),):if not isinstance(value, bool):@@ -1905,6 +1907,13 @@ class MemoryConfig:self.processing.validate()self.cloud.validate()self.diagnostics.validate()+ if self.cloud.transition_rebuild_owned and (+ not self.cloud.transition_notice_pending+ or self.recovery_intent != "rebuild"+ ):+ raise ValueError(+ "Config 'memory.cloud.transition_rebuild_owned' requires a pending transition rebuild"+ )if (self.enabledand not self.cloud_runtime_selected()@@ -2121,6 +2130,7 @@ def memory_config_to_payload("source_instance_id": memory.cloud.source_instance_id,"organization_attached": memory.cloud.organization_attached,"transition_notice_pending": memory.cloud.transition_notice_pending,+ "transition_rebuild_owned": memory.cloud.transition_rebuild_owned,"applied_embedding_identity": memory.cloud.applied_embedding_identity,"runtime_apply_pending": memory.cloud.runtime_apply_pending,},diff --git a/core/memory/runtime.py b/core/memory/runtime.pyindex 18cc83d17..22a7a1d0c 100644--- a/core/memory/runtime.py+++ b/core/memory/runtime.py@@ -1062,7 +1062,7 @@ class MemoryRuntime:self._configure_insight_reader(config)self._provider = EverOSPort(self._socket_path)self.module.replace_provider(self._provider)- self._runtime_error = "memory_cloud_model_unavailable"+ self._runtime_error = "memory_capability_unavailable"return {"ok": True,"state": "paused",diff --git a/tests/test_memory_config.py b/tests/test_memory_config.pyindex 1483c74b9..b73188b19 100644--- a/tests/test_memory_config.py+++ b/tests/test_memory_config.py@@ -328,6 +328,50 @@ def test_memory_config_accepts_factory_reset_recovery_intent() -> None:assert config.memory.recovery_intent == "factory_reset"+def test_memory_transition_rebuild_owner_round_trips(tmp_path) -> None:+ config_path = tmp_path / "config.json"+ config = V2Config.from_payload(+ _payload(+ {+ "recovery_intent": "rebuild",+ "cloud": {+ "transition_notice_pending": True,+ "transition_rebuild_owned": True,+ },+ }+ )+ )++ config.save(config_path)++ stored = json.loads(config_path.read_text(encoding="utf-8"))+ loaded = V2Config.load(config_path)+ assert stored["memory"]["cloud"]["transition_rebuild_owned"] is True+ assert loaded.memory.cloud.transition_rebuild_owned is True+ assert loaded.memory.recovery_intent == "rebuild"+++ "memory",+ [+ {+ "recovery_intent": "rebuild",+ "cloud": {"transition_rebuild_owned": True},+ },+ {+ "recovery_intent": "factory_reset",+ "cloud": {+ "transition_notice_pending": True,+ "transition_rebuild_owned": True,+ },+ },+ ],+)+def test_memory_config_rejects_unowned_transition_rebuild_state(memory: dict) -> None:+ with pytest.raises(ValueError, match="transition_rebuild_owned"):+ V2Config.from_payload(_payload(memory))++@pytest.mark.parametrize(("field", "expected_name"),[diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.pyindex f24e38f40..808d15518 100644--- a/tests/test_memory_runtime.py+++ b/tests/test_memory_runtime.py@@ -3695,7 +3695,7 @@ async def test_cloud_capability_removal_pauses_claims_keeps_capture_and_resumes_assert paused == {"ok": True,"state": "paused",- "reason": "memory_cloud_model_unavailable",+ "reason": "memory_capability_unavailable",}assert runtime.module._worker._claims_paused is Trueassert factory.supervised[0].stopped is Truediff --git a/tests/test_model_service.py b/tests/test_model_service.pyindex b3ed3f596..a56e87abe 100644--- a/tests/test_model_service.py+++ b/tests/test_model_service.py@@ -13,6 +13,7 @@ from config.v2_config import (MemoryConfig,MemoryEndpointConfig,MemoryProcessingConfig,+ MemoryRecoveryIntent,RuntimeConfig,SlackConfig,V2Config,@@ -234,6 +235,191 @@ def test_unpairing_clears_cloud_runtime_and_reconciles_the_running_sidecar(assert memory.cloud.organization_attached is False+def test_replacement_pairing_fences_the_previous_sidecar_before_status_resolution(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ current = MemoryConfig(+ enabled=True,+ mode="platform",+ cloud=MemoryCloudConfig(+ scope="platform",+ capabilities=MemoryCloudCapabilities(chat=True, embedding=True),+ embedding_identity="emb-old",+ applied_embedding_identity="emb-old",+ model_access_key="mak_old",+ proxy_base_url="https://old.example.test/v1/model",+ source_instance_id="instance-old",+ ),+ )+ _paired_config(current).save()+ events: list[str] = []++ def reconcile(candidate: MemoryConfig) -> bool:+ events.append("reconcile")+ assert candidate.runtime_source() == "unavailable"+ model_service._clear_apply_pending(candidate) # noqa: SLF001+ return True++ def device_request(*_args: object) -> dict:+ events.append("status")+ persisted = V2Config.load().memory+ assert persisted.runtime_source() == "unavailable"+ assert persisted.cloud.model_access_key is None+ raise model_service.ModelServiceResolutionError("status_unavailable")++ monkeypatch.setattr(model_service, "_reconcile_candidate", reconcile)+ monkeypatch.setattr(model_service, "_device_request", device_request)++ with pytest.raises(+ model_service.ModelServiceResolutionError,+ match="status_unavailable",+ ):+ model_service.sync_model_service_once()++ memory = V2Config.load().memory+ assert events == ["reconcile", "status"]+ assert memory.cloud.source_instance_id == "instance-old"+ assert memory.cloud.applied_embedding_identity == "emb-old"+ assert memory.cloud.model_access_key is None+ assert memory.cloud.runtime_apply_pending is False+++def test_replacement_pairing_does_not_contact_the_new_instance_until_the_fence_applies(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ current = MemoryConfig(+ enabled=True,+ mode="platform",+ cloud=MemoryCloudConfig(+ scope="platform",+ capabilities=MemoryCloudCapabilities(chat=True, embedding=True),+ embedding_identity="emb-old",+ applied_embedding_identity="emb-old",+ model_access_key="mak_old",+ proxy_base_url="https://old.example.test/v1/model",+ source_instance_id="instance-old",+ ),+ )+ _paired_config(current).save()+ monkeypatch.setattr(model_service, "_reconcile_candidate", lambda _candidate: False)+ monkeypatch.setattr(+ model_service,+ "_device_request",+ lambda *_args: pytest.fail("status must wait for the durable runtime fence"),+ )++ with pytest.raises(+ model_service.ModelServiceResolutionError,+ match="model_service_pairing_fence_failed",+ ):+ model_service.sync_model_service_once()++ memory = V2Config.load().memory+ assert memory.runtime_source() == "unavailable"+ assert memory.cloud.model_access_key is None+ assert memory.cloud.runtime_apply_pending is True+++def test_stale_pairing_snapshot_is_fenced_before_any_status_request(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ current = MemoryConfig(+ enabled=True,+ mode="platform",+ cloud=MemoryCloudConfig(+ scope="platform",+ capabilities=MemoryCloudCapabilities(chat=True, embedding=True),+ embedding_identity="emb-old",+ applied_embedding_identity="emb-old",+ model_access_key="mak_old",+ proxy_base_url="https://old.example.test/v1/model",+ source_instance_id="instance-old",+ ),+ )+ stale = _paired_config(current)+ stale.remote_access.vibe_cloud.instance_id = "instance-old"+ live = deepcopy(stale)+ live.remote_access.vibe_cloud.instance_id = "instance-new"+ live.save()++ def reconcile(candidate: MemoryConfig) -> bool:+ model_service._clear_apply_pending(candidate) # noqa: SLF001+ return True++ monkeypatch.setattr(model_service, "_reconcile_candidate", reconcile)+ monkeypatch.setattr(+ model_service,+ "_device_request",+ lambda *_args: pytest.fail("a stale pairing snapshot must never be contacted"),+ )+ monkeypatch.setattr(model_service, "request_model_service_refresh", lambda: None)++ with pytest.raises(+ model_service.ModelServiceResolutionError,+ match="model_service_pairing_changed",+ ):+ model_service.sync_model_service_once(stale)++ memory = V2Config.load().memory+ assert memory.runtime_source() == "unavailable"+ assert memory.cloud.model_access_key is None+ assert memory.cloud.source_instance_id == "instance-old"+ assert memory.cloud.runtime_apply_pending is False+++def test_pairing_change_during_failed_status_request_fences_the_old_runtime(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ current = MemoryConfig(+ enabled=True,+ mode="platform",+ cloud=MemoryCloudConfig(+ scope="platform",+ capabilities=MemoryCloudCapabilities(chat=True, embedding=True),+ embedding_identity="emb-old",+ applied_embedding_identity="emb-old",+ model_access_key="mak_old",+ proxy_base_url="https://old.example.test/v1/model",+ source_instance_id="instance-1",+ ),+ )+ _paired_config(current).save()++ def change_pairing_then_fail(*_args: object) -> dict:+ changed = V2Config.load()+ changed.remote_access.vibe_cloud.instance_id = "instance-new"+ changed.save()+ raise model_service.ModelServiceResolutionError("status_unavailable")++ def reconcile(candidate: MemoryConfig) -> bool:+ model_service._clear_apply_pending(candidate) # noqa: SLF001+ return True++ monkeypatch.setattr(model_service, "_device_request", change_pairing_then_fail)+ monkeypatch.setattr(model_service, "_reconcile_candidate", reconcile)+ monkeypatch.setattr(model_service, "request_model_service_refresh", lambda: None)++ with pytest.raises(+ model_service.ModelServiceResolutionError,+ match="model_service_pairing_changed",+ ):+ model_service.sync_model_service_once()++ memory = V2Config.load().memory+ assert memory.runtime_source() == "unavailable"+ assert memory.cloud.model_access_key is None+ assert memory.cloud.source_instance_id == "instance-1"+ assert memory.cloud.runtime_apply_pending is False++def test_managed_scope_is_persisted_before_first_key_mint(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,@@ -319,6 +505,7 @@ def test_enterprise_attachment_pauses_custom_until_acknowledged() -> None:assert candidate.settings_mode() == "organization"assert candidate.cloud.transition_notice_pending is True+ assert candidate.cloud.transition_rebuild_owned is Trueassert candidate.cloud.organization_attached is Falseassert candidate.cloud.model_access_key is Noneassert candidate.recovery_intent == "rebuild"@@ -383,21 +570,30 @@ def test_canceling_enterprise_attachment_resumes_the_preserved_custom_runtime(),)else:- canceled = model_service._unpaired_memory(pending) # noqa: SLF001+ canceled = model_service._fenced_cloud_memory(pending) # noqa: SLF001assert canceled.cloud.transition_notice_pending is False+ assert canceled.cloud.transition_rebuild_owned is Falseassert canceled.cloud.organization_attached is Falseassert canceled.recovery_intent is Noneassert canceled.runtime_source() == "custom"assert canceled.cloud.runtime_apply_pending is True-def test_canceling_enterprise_attachment_preserves_an_unrelated_recovery_fence() -> None:[email protected]("recovery_intent", ["rebuild", "factory_reset"])+def test_enterprise_attachment_preserves_an_unrelated_recovery_fence(+ recovery_intent: MemoryRecoveryIntent,+) -> None:+ current = _manual_memory()+ current.recovery_intent = recovery_intentpending = _resolved(- _manual_memory(),+ current,_status(scope="organization"),)- pending.recovery_intent = "factory_reset"++ assert pending.cloud.transition_notice_pending is True+ assert pending.cloud.transition_rebuild_owned is False+ assert pending.recovery_intent == recovery_intentcanceled = _resolved(pending,@@ -405,7 +601,8 @@ def test_canceling_enterprise_attachment_preserves_an_unrelated_recovery_fence())assert canceled.cloud.transition_notice_pending is False- assert canceled.recovery_intent == "factory_reset"+ assert canceled.cloud.transition_rebuild_owned is False+ assert canceled.recovery_intent == recovery_intentdef test_enterprise_transition_acknowledgement_cannot_edit_custom_endpoints() -> None:diff --git a/tests/test_ui_memory_routes.py b/tests/test_ui_memory_routes.pyindex 3fba4ca07..14ece1315 100644--- a/tests/test_ui_memory_routes.py+++ b/tests/test_ui_memory_routes.py@@ -10,6 +10,8 @@ import pytestfrom config.v2_config import (AgentsConfig,+ MemoryCloudCapabilities,+ MemoryCloudConfig,MemoryConfig,MemoryEndpointConfig,MemoryProcessingConfig,@@ -20,7 +22,7 @@ from config.v2_config import (from core.memory.operation_lock import MemoryOperationLeasefrom core.memory.runtime import MEMORY_LIST_CURSOR_MAX_BYTESfrom tests.ui_server_test_helpers import csrf_headers, remote_session_cookie-from vibe import api, internal_client, remote_access, ui_memory_routes, ui_server+from vibe import api, internal_client, model_service, remote_access, ui_memory_routes, ui_serverfrom vibe.ui_server import app@@ -268,6 +270,60 @@ def _save_memory(memory: MemoryConfig) -> V2Config:)+def test_cloud_mode_switch_returns_a_localized_closed_error_when_key_mint_fails(+ monkeypatch,+ tmp_path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ memory = MemoryConfig(+ enabled=True,+ mode="custom",+ processing=MemoryProcessingConfig(+ llm=MemoryEndpointConfig(+ "https://llm.example.test/v1",+ "chat",+ "llm-key",+ ),+ embedding=MemoryEndpointConfig(+ "https://embed.example.test/v1",+ "embed",+ "embed-key",+ ),+ ),+ cloud=MemoryCloudConfig(+ scope="platform",+ capabilities=MemoryCloudCapabilities(chat=True, embedding=True),+ embedding_identity="emb-cloud",+ proxy_base_url="https://backend.example.test/v1/model",+ source_instance_id="instance-1",+ ),+ )+ _save_memory(memory)++ def fail_mint(_config: V2Config) -> V2Config:+ raise model_service.ModelServiceResolutionError("mint_unavailable")++ monkeypatch.setattr(model_service, "ensure_model_access_key", fail_mint)+ client = app.test_client()+ response = client.patch(+ "/api/memory/settings",+ json={"mode": "platform", "confirm_rebuild": True},+ headers=csrf_headers(client, "http://127.0.0.1:15131"),+ base_url="http://127.0.0.1:15131",+ environ_base={"REMOTE_ADDR": "127.0.0.1"},+ )++ assert response.status_code == 409+ assert response.get_json() == {+ "status": "failed",+ "error": "memory_capability_unavailable",+ }+ persisted = V2Config.load().memory+ assert persisted.mode == "custom"+ assert persisted.cloud.model_access_key is None++def test_enabled_rerank_change_runs_typed_preflight_before_persisting(monkeypatch,tmp_path,diff --git a/ui/src/components/settings/memory/memoryCopyContract.test.ts b/ui/src/components/settings/memory/memoryCopyContract.test.tsindex 2cb4e047f..bab57e852 100644--- a/ui/src/components/settings/memory/memoryCopyContract.test.ts+++ b/ui/src/components/settings/memory/memoryCopyContract.test.ts@@ -117,6 +117,10 @@ describe('Memory UI copy contracts', () => {expect(text).toMatch(language === 'en' ? /may use/ : /可能消耗/);});+ it.each(['en', 'zh'] as const)('localizes the closed cloud capability error in %s', (language) => {+ expect(BUNDLES[language].errors.memory_capability_unavailable).toBeTruthy();+ });+it('keeps processing terminology aligned with the runtime contracts', () => {expect(en.memory.processingRecord.runtime.fact.cascade.optimizeFailureStreak).not.toMatch(/cleanup/i);expect(en.memory.processingRecord.runtime.fact.cascadeReason.optimizeStuck).toMatch(/Optimization/);diff --git a/ui/src/components/settings/memory/memoryStatusPresentation.test.ts b/ui/src/components/settings/memory/memoryStatusPresentation.test.tsindex 03c1f14f1..18234a2dd 100644--- a/ui/src/components/settings/memory/memoryStatusPresentation.test.ts+++ b/ui/src/components/settings/memory/memoryStatusPresentation.test.ts@@ -25,4 +25,9 @@ describe('memory status presentation', () => {expect(memoryStatusSourceReasonLabel(t, 'memory_clear_legacy_state_requires_rerun')).toContain('errors.memory_clear_legacy_state_requires_rerun');});++ it('localizes a cloud capability pause through the closed Memory error vocabulary', () => {+ expect(memoryStatusSourceReasonLabel(t, 'memory_capability_unavailable'))+ .toContain('errors.memory_capability_unavailable');+ });});diff --git a/ui/src/components/settings/memory/memoryStatusPresentation.ts b/ui/src/components/settings/memory/memoryStatusPresentation.tsindex 2850ff9f4..04391e400 100644--- a/ui/src/components/settings/memory/memoryStatusPresentation.ts+++ b/ui/src/components/settings/memory/memoryStatusPresentation.ts@@ -52,6 +52,7 @@ const MEMORY_SOURCE_ERROR_REASONS = new Set(['memory_sidecar_unavailable','memory_provider_timeout','memory_provider_response_invalid',+ 'memory_capability_unavailable','memory_processing_failed','memory_clear_failed','memory_clear_legacy_state_requires_rerun',diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 12483d933..fa2b1dd0b 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1678,6 +1678,7 @@"memory_sidecar_unavailable": "The Memory sidecar isn't reachable right now.","memory_provider_timeout": "The Memory request timed out.","memory_provider_response_invalid": "Memory returned an invalid response.",+ "memory_capability_unavailable": "Memory models are temporarily unavailable. Try again when the configured model service is available.","memory_processing_failed": "Memory processing failed.","memory_clear_failed": "Clearing Memory data failed.","memory_clear_marker_unreadable": "Memory Clear state could not be read. Run Clear again to repair it.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex db24a03dc..b3a7009df 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1678,6 +1678,7 @@"memory_sidecar_unavailable": "记忆 sidecar 当前不可访问。","memory_provider_timeout": "记忆请求超时。","memory_provider_response_invalid": "记忆返回了无效的响应。",+ "memory_capability_unavailable": "记忆模型暂时不可用。请在已配置的模型服务恢复后重试。","memory_processing_failed": "记忆处理失败。","memory_clear_failed": "清除记忆数据失败。","memory_clear_marker_unreadable": "无法读取记忆清除状态。请再次执行清除以修复。",diff --git a/vibe/model_service.py b/vibe/model_service.pyindex 076a586b0..f09d7348d 100644--- a/vibe/model_service.py+++ b/vibe/model_service.py@@ -179,8 +179,12 @@ def _cancel_organization_transition(memory: MemoryConfig) -> bool:if not memory.cloud.transition_notice_pending:return Falsememory.cloud.transition_notice_pending = False- if memory.recovery_intent == "rebuild":+ if (+ memory.cloud.transition_rebuild_owned+ and memory.recovery_intent == "rebuild"+ ):memory.recovery_intent = None+ memory.cloud.transition_rebuild_owned = Falsereturn True@@ -240,10 +244,14 @@ def _resolved_memory(if first_managed_activation:candidate.enabled = Trueelif candidate.cloud.transition_notice_pending:- candidate.recovery_intent = "rebuild"+ if candidate.recovery_intent is None:+ candidate.recovery_intent = "rebuild"+ candidate.cloud.transition_rebuild_owned = Trueelif candidate.mode == "custom" and previous.custom_processing_complete():candidate.cloud.transition_notice_pending = True- candidate.recovery_intent = "rebuild"+ if candidate.recovery_intent is None:+ candidate.recovery_intent = "rebuild"+ candidate.cloud.transition_rebuild_owned = Trueelse:candidate.cloud.organization_attached = Trueif candidate.cloud.model_access_key:@@ -289,8 +297,8 @@ def _resolved_memory(return candidate-def _unpaired_memory(current: MemoryConfig) -> MemoryConfig:- """Pause cloud Memory while retaining its scope and identity baseline."""+def _fenced_cloud_memory(current: MemoryConfig) -> MemoryConfig:+ """Fence cloud egress while retaining scope and the identity baseline."""cloud = current.cloudhad_cloud_state = bool(@@ -320,6 +328,49 @@ def _unpaired_memory(current: MemoryConfig) -> MemoryConfig:return candidate+def _fence_replaced_pairing(current: MemoryConfig) -> tuple[MemoryConfig, bool]:+ """Durably stop an old instance runtime before contacting its replacement."""++ candidate = _fenced_cloud_memory(current)+ changed = candidate != current+ if changed:+ candidate = _persist_candidate(current, candidate).memory+ if candidate.cloud.runtime_apply_pending:+ if not _reconcile_candidate(candidate):+ raise ModelServiceResolutionError("model_service_pairing_fence_failed")+ candidate = V2Config.load().memory+ return candidate, changed+++def _guard_pairing_authority(credentials: tuple[str, str, str]) -> None:+ """Fence stale cloud egress whenever the request authority has changed."""++ live = V2Config.load()+ if live.remote_access.vibe_cloud.runtime_credentials() == credentials:+ return+ _fence_replaced_pairing(live.memory)+ request_model_service_refresh()+ raise ModelServiceResolutionError("model_service_pairing_changed")+++def _paired_device_request(+ config: V2Config,+ credentials: tuple[str, str, str],+ method: str,+ suffix: str,+) -> dict[str, Any]:+ """Run one device request only while its captured pairing owns egress."""++ _guard_pairing_authority(credentials)+ try:+ payload = _device_request(config, method, suffix)+ except Exception:+ _guard_pairing_authority(credentials)+ raise+ _guard_pairing_authority(credentials)+ return payload++def _persist_candidate(current: MemoryConfig, candidate: MemoryConfig) -> V2Config:from vibe import api@@ -372,7 +423,7 @@ def sync_model_service_once(config: V2Config | None = None) -> dict[str, Any]:credentials = config.remote_access.vibe_cloud.runtime_credentials()if credentials is None:current = V2Config.load().memory- candidate = _unpaired_memory(current)+ candidate = _fenced_cloud_memory(current)if candidate == current and not current.cloud.runtime_apply_pending:return {"ok": False, "configured": False, "changed": False}changed = candidate != current@@ -386,7 +437,16 @@ def sync_model_service_once(config: V2Config | None = None) -> dict[str, Any]:"apply_pending": not applied,}backend_url, instance_id, _device_secret = credentials- status = _status_from_payload(_device_request(config, "GET", "model-service"))+ changed = False+ current = V2Config.load().memory+ if (+ current.cloud.source_instance_id+ and current.cloud.source_instance_id != instance_id+ ):+ current, changed = _fence_replaced_pairing(current)+ status = _status_from_payload(+ _paired_device_request(config, credentials, "GET", "model-service")+ )current = V2Config.load().memorycandidate = _resolved_memory(current,@@ -395,15 +455,21 @@ def sync_model_service_once(config: V2Config | None = None) -> dict[str, Any]:proxy_base_url=f"{backend_url.rstrip('/')}/v1/model",minted=None,)- changed = candidate != current- if changed:+ status_changed = candidate != current+ if status_changed:current = _persist_candidate(current, candidate).memory+ changed = Truecurrent_key = current.cloud.model_access_keyif _status_needs_model_key(current, status) and not current_key:try:minted = _mint_from_payload(- _device_request(config, "POST", "model-access-key")+ _paired_device_request(+ config,+ credentials,+ "POST",+ "model-access-key",+ ))except Exception:if current.cloud.runtime_apply_pending:@@ -445,7 +511,14 @@ def rotate_model_access_key(config: V2Config | None = None) -> dict[str, Any]:current = V2Config.load().memoryif current.cloud.source_instance_id != instance_id or not current.cloud_runtime_selected():raise ModelServiceResolutionError("model_service_not_configured")- minted = _mint_from_payload(_device_request(config, "POST", "model-access-key"))+ minted = _mint_from_payload(+ _paired_device_request(+ config,+ credentials,+ "POST",+ "model-access-key",+ )+ )candidate = deepcopy(current)candidate.cloud.model_access_key = minted.keycandidate.cloud.runtime_apply_pending = True@@ -483,7 +556,14 @@ def ensure_model_access_key(config: V2Config | None = None) -> V2Config:raise ModelServiceResolutionError("model_service_not_configured")if current.cloud.model_access_key:return V2Config.load()- minted = _mint_from_payload(_device_request(config, "POST", "model-access-key"))+ minted = _mint_from_payload(+ _paired_device_request(+ config,+ credentials,+ "POST",+ "model-access-key",+ )+ )candidate = deepcopy(current)candidate.cloud.model_access_key = minted.keycandidate.validate()diff --git a/vibe/ui_memory_routes.py b/vibe/ui_memory_routes.pyindex 2bbd7effc..5df470c9e 100644--- a/vibe/ui_memory_routes.py+++ b/vibe/ui_memory_routes.py@@ -211,7 +211,7 @@ def _memory_settings_patch(current: V2Config, patch_payload: object) -> tuple[dimode == "platform"and not current.memory.cloud.memory_capability_available()):- raise ValueError("memory_cloud_unavailable")+ raise ValueError("memory_capability_unavailable")target["mode"] = modeif mode == "platform":adopt_cloud_identity = True@@ -225,6 +225,7 @@ def _memory_settings_patch(current: V2Config, patch_payload: object) -> tuple[diraise ValueError("invalid_memory_patch")target["cloud"]["organization_attached"] = Truetarget["cloud"]["transition_notice_pending"] = False+ target["cloud"]["transition_rebuild_owned"] = Falseadopt_cloud_identity = Trueif adopt_cloud_identity:target["cloud"]["applied_embedding_identity"] = (@@ -893,9 +894,12 @@ async def _apply_memory_settings_patch(and _memory_factory_reset_repair_patch(patch_payload))except ValueError as exc:- if str(exc) == "memory_cloud_unavailable":+ if str(exc) == "memory_capability_unavailable":return _memory_response(- {"status": "failed", "error": "memory_cloud_unavailable"},+ {+ "status": "failed",+ "error": "memory_capability_unavailable",+ },status_code=409,)return _memory_response(@@ -912,7 +916,10 @@ async def _apply_memory_settings_patch(if isinstance(exc, ModelServiceResolutionError):return _memory_response(- {"status": "failed", "error": "memory_cloud_unavailable"},+ {+ "status": "failed",+ "error": "memory_capability_unavailable",+ },status_code=409,)return _memory_response(