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): converge native artifacts during wake (#2008)
Call Whitee8a7cb4a94e9
diff --git a/avibe_memory/artifact.py b/avibe_memory/artifact.pyindex 0cf9a6e51..677069689 100644--- a/avibe_memory/artifact.py+++ b/avibe_memory/artifact.py@@ -197,8 +197,7 @@ class MemoryArtifactManager(ManagedRuntimeManager):self._install_reason = Nonelatest_failure = self._read_latest_install_failure()manifest = self._load_manifest(allow_network=False)- if manifest is not None:- self._manifest_installable(manifest)+ manifest_installable = manifest is not None and self._manifest_installable(manifest)archive = self._manifest_archive_for_platform(manifest) if manifest else Nonepointer, invalid = self._read_active_pointer()try:@@ -219,7 +218,10 @@ class MemoryArtifactManager(ManagedRuntimeManager):invalid = invalid or (pointer is not None and binary is None)selected_version = manifest.runtime_version if manifest is not None else Nonematches_manifest = None- if binary is not None and manifest is not None and archive is not None:+ # Only an installable selection can authorize convergence. Source builds+ # and rejected manifests may describe different bytes without offering+ # any artifact that can safely replace the admitted active pointer.+ if binary is not None and manifest_installable and archive is not None:try:matches_manifest = (self._verified_manifest_binary(diff --git a/avibe_memory/runtime.py b/avibe_memory/runtime.pyindex ebe0f8ed4..ad1c02f91 100644--- a/avibe_memory/runtime.py+++ b/avibe_memory/runtime.py@@ -702,18 +702,17 @@ class MemoryRuntime:if callable(cancel_nowait):cancel_nowait()- def artifact_admitted(self) -> bool:- """Return whether the pinned artifact is valid for a reset admission."""+ def _active_artifact_identity(self) -> tuple[Path, str] | None:+ """Snapshot the verified active binary, not the selected manifest."""- try:- status = self._artifact_manager.status()- return (- self._artifact_manager.resolve_python() is not None- and status.get("status") == "ready"- and status.get("reason") is None- )- except Exception:- return False+ status = self._artifact_manager.status()+ if status.get("installed") is not True or status.get("status") != "ready":+ return None+ python = self._artifact_manager.resolve_python()+ fingerprint = self._artifact_manager.artifact_fingerprint()+ if python is None or fingerprint is None:+ return None+ return python, fingerprint@propertydef module(self) -> MemoryModule | _UnavailableMemoryModule:@@ -2182,7 +2181,7 @@ class MemoryRuntime:*,operation_lease_held: bool = False,) -> dict[str, Any]:- """Validate the artifact and non-destructively wake the existing root."""+ """Converge the selected artifact and non-destructively wake its root."""if self._closing:return {@@ -2251,38 +2250,73 @@ class MemoryRuntime:"state": "disabled","error": "memory_disabled",}- artifact_admitted = await self._lifecycle_checkpoint(- run_blocking(self.artifact_admitted)+ artifact_status = await self._lifecycle_checkpoint(+ run_blocking(self._artifact_manager.status)+ )+ previous_artifact = await self._lifecycle_checkpoint(+ run_blocking(self._active_artifact_identity))- if not artifact_admitted:+ # Active usability and selected-manifest currency are independent+ # of the last install attempt's diagnostic. Retained failure evidence+ # must not make a verified old artifact unusable or authorize a retry+ # against an unknown/rejected selection. Same-version byte/contract+ # changes still converge when the installable manifest proves it.+ manifest_changed = artifact_status.get("matches_manifest") is False+ if previous_artifact is None or manifest_changed:if self.available:async with self._reconcile_lock, self.module.lifecycle():self._require_lifecycle_work()self.module.pause_claims()- quiesced = await self._lifecycle_checkpoint(- self.module.quiesce_claims(timeout_seconds=5.0)- )- if not quiesced:- return {- "ok": False,- "state": "degraded",- "error": "memory_runtime_busy",- }- await self._lifecycle_checkpoint(self._close_writer())try:+ quiesced = await self._lifecycle_checkpoint(+ self.module.quiesce_claims(timeout_seconds=5.0)+ )+ if not quiesced:+ self._runtime_error = "memory_runtime_busy"+ return {+ "ok": False,+ "state": "degraded",+ "error": self._runtime_error,+ }+ await self._lifecycle_checkpoint(self._close_writer())await self._lifecycle_checkpoint(self._supervisor.stop())except MemoryRuntimeBusyError:raiseexcept Exception:+ self._runtime_error = "memory_wake_failed"return {"ok": False,"state": "degraded",- "error": "memory_wake_failed",+ "error": self._runtime_error,}+ finally:+ # A pre-install abort must not permanently fence the+ # still-running admitted old child. A pending writer+ # close retains its own fence until cleanup settles;+ # unproved sidecar health or shutdown stays closed.+ if previous_artifact is not None and self._sidecar_ready_is_current():+ self.module.resume_claims()installed = await self._lifecycle_checkpoint(self._install_artifact_with_lease())if installed.get("ok") is not True:+ # The installer owns pointer rollback. Only resume the exact+ # verified artifact it left in place; never restore pointers+ # or erase data here. _wake_locked rechecks the old root and+ # actual native readiness, while dependency status retains+ # the failed update rather than claiming manifest currency.+ active_artifact = await self._lifecycle_checkpoint(+ run_blocking(self._active_artifact_identity)+ )+ if previous_artifact is not None and active_artifact == previous_artifact:+ logger.warning(+ "Memory artifact update failed; waking the retained artifact: %s",+ installed.get("reason") or "memory_runtime_install_failed",+ )+ async with self._reconcile_lock:+ self._require_lifecycle_work()+ result = await self._wake_locked()+ return {**result, "artifact_update": installed}self._runtime_error = str(installed.get("reason") or "memory_wake_failed")diff --git a/docs/plans/memory-native-auto-switch.md b/docs/plans/memory-native-auto-switch.mdnew file mode 100644index 000000000..74870b6a5--- /dev/null+++ b/docs/plans/memory-native-auto-switch.md@@ -0,0 +1,138 @@+# Converge Memory's native artifact during Wake++## Background and contract++A core upgrade can correctly install its exact GitHub Memory companion while+leaving a healthy native artifact from the previous release active. Startup+already calls the controller-owned, non-destructive `MemoryRuntime.wake`.+That path repairs missing/invalid artifacts but overlooks a verified artifact+whose bytes or contract no longer match the new packaged manifest.++Extend this existing owner, not the package updater or a second background+installer. Startup, explicit Wake, and bounded crash recovery must share the+same decision. A proven manifest mismatch is actionable even when the EverOS+version is unchanged. An unchanged/unknown manifest or explicit development+runtime does not create a new update requirement.++## Invariants++- Hold the existing operation lease; pause and join writers and prove the old+ sidecar stopped before installing. Keep the explicit running-runtime install+ rejection unchanged.+- Use the existing manifest/hash/extraction/cold-admission/root-compatibility/+ activation bridge. Never write the user's `enabled` preference, delete data,+ grant accepted-loss authority, or add package rollback/recovery machinery.+- If installation fails, resume only the exact previously admitted active+ artifact when its binary and fingerprint are unchanged and its root/readiness+ checks still pass. Retain the install failure in the dependency owner and+ expose it in the Wake result/log; running the old artifact is not upgrade+ success. An invalid old artifact cannot provide fallback authority.+- No new timer, persistent workflow, retries within a Wake, or service restart.+ A later startup/explicit Wake or existing bounded crash recovery may retry.+- Cancellation/shutdown retains the existing install-join and lease semantics.+ Conflicting settings/repair/install cannot overlap the operation.++## Evidence and scope++Add `MEMORY-RUNTIME-INSTALL-004/005` scenarios with a real managed artifact+manager, generated archives, actual active-pointer and provider-root checks,+and deterministic process/provider boundaries. Cover same-version new bytes,+unchanged state, failed download/admission/activation, incompatible nonempty+roots, configuration/data preservation, contention and cancellation.+Existing wake, artifact, controller and package-consumer suites remain gates.++Hermetic tests do not prove a new released archive or actual host upgrade.+No release, deployment, production restart, Incus mutation, or merge is+authorized by this source-fix task. Deliver a reviewed PR with full CI first.++## Progress++- [x] Inspect actual rc2 receipts and end-to-end production call path.+- [x] Implement the smallest Wake policy change and deterministic regression.+- [x] Run focused/broader tests and changed-file Ruff.+- [ ] Independent root review, exact-head Codex review, complete lint CI.++## Initial local validation++- The selected runtime, supervisor, artifact, disabled-isolation, dependency,+ upgrade, distribution and internal-server suites: 968 passed, 11 skipped.+ One skip needs pinned real EverOS; ten need the CI-built core/Memory package+ matrix. Their dedicated CI jobs remain required, not presumed successful.+- Nine new real-manager scenarios cover startup/running Wake, changed bytes+ or contracts at the same version, and five failed-update boundaries. Narrow+ contracts additionally cover unverified/changed fallback, proven stop,+ unchanged/unknown manifests and cancellation retaining the operation lease.+- The unmodified base Wake method fails all seven initial regression scenarios+ when substituted in-process; the worktree source is not changed by that probe.+- Changed-file Ruff, whitespace checks and the UI build pass. The UI build was+ needed for the normal task-local editable package bootstrap, not UI changes.+ Its existing dependency audit reports 14 issues (6 high); dependency/security+ remediation is not part of this change.+- Initial test-environment failures and stricter fixture assertion corrections+ were diagnosed and retained before the final clean run. No host service,+ configuration, released archive or Incus environment was modified.++`Wake.ok` continues to mean runtime availability. If the selected update fails+but the identical admitted old artifact passes root/readiness checks, Wake also+returns `artifact_update` with the unsuccessful install result. Dependency+status retains the reason and manifest mismatch; this is not upgrade success.++## Review boundary corrections++Round 1 reviewed one findings-bearing head and three distinct classes:+pre-install lifecycle compensation, public failure propagation, and selected+manifest authority. No repeated class or circuit-breaker threshold was reached.++- Restore capture intake on a pre-install abort only when the original admitted+ sidecar is still running/current. A pending writer close retains its own fence+ until cleanup ends; incomplete stop and shutdown remain closed. Record abort+ reasons in status rather than leaving an apparently healthy paused writer.+- Compute `matches_manifest` only for installable selections. Unavailable,+ malformed, unsupported or incompatible-build source manifests are unknown,+ not update authority. This refines the existing producer field, adding no flag.+- The Web Wake response retains only bounded `artifact_update.ok/reason`+ information. Both settings consumers show a localized failed-update message+ even when the prior engine remains available. Raw download diagnostics are+ not exposed. Supervisor recovery keeps its original availability semantics.++### Round 1 validation++- Expanded Python selection, including the Web response consumer: 1011 passed,+ 11 skipped, zero failures/errors. The same pinned-EverOS and CI-built package+ prerequisites account for all skips; they remain explicit CI gates.+- 66 UI tests pass across both settings consumers and their shared Memory+ helper suite. Test typechecking, baseline-aware UI lint, UI build,+ changed-file Ruff and whitespace checks also pass.+- Added eight rejected-manifest variants, three pre-install abort variants+ with actual writer admission checks, a public HTTP response contract, and+ both settings-page failed-update toast consumers.+- Released-native unattended host upgrade and real search are not exercised+ by these isolated source tests. No deployment or publication is authorized.++## Round 2 authority circuit breaker++Selected-manifest authority recurred on two findings-bearing heads; root paused+editing and independently diagnosed the complete review inventory before+continuing. A prior failed candidate remains in status even when the unchanged+old artifact is verified. The older admission predicate conflated that history+with current unusability, bypassing the rejected-manifest guard on a later Wake.++Reuse the existing verified active identity for the whole Wake decision and+fallback, removing the redundant admission predicate. A missing/unusable+identity still enters repair; a usable identity only enters selected-artifact+installation on a proven installable-manifest mismatch. Historical failure+remains in dependency status and is not cleared to authorize availability.+This changes no persistent schema, configuration, installer or release guard.++The scenario matrix now crosses clean/failed update history, startup/running+Wake, and eight rejected selections plus an already-current selection. The+unchanged reviewed implementation fails all 18 retained-failure variants while+passing all 18 clean controls; these are actual installer-call failures with+clean teardown. The initial negative control raised a pytest BaseException+inside the install task and produced teardown noise; it was replaced by a+normal structured failure/recorded-call probe before production code changed.++After the correction, 102 focused tests and 1039 expanded Python tests pass;+the same 11 real-EverOS/package-matrix prerequisite skips remain explicit.+Changed-file Ruff and whitespace checks pass. The prior 66 UI tests and UI+types/lint/build cover unchanged UI bytes; fresh exact-head CI is still required.diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 9c00cae59..f1a123197 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -15,6 +15,7 @@ capabilities:observations: tests/scenarios/memory_runtime_install/observations.yamlscenario_tests:- tests/scenarios/memory_runtime_install/test_memory_runtime_install_scenarios.py+ - tests/scenarios/memory_runtime_install/test_memory_native_auto_switch.pyunit_or_contract_tests:- tests/test_memory_artifact_contract.py- tests/test_managed_runtime.pydiff --git a/tests/scenarios/memory_runtime_install/catalog.yaml b/tests/scenarios/memory_runtime_install/catalog.yamlindex 8a09a3515..2c0a809bd 100644--- a/tests/scenarios/memory_runtime_install/catalog.yaml+++ b/tests/scenarios/memory_runtime_install/catalog.yaml@@ -4,6 +4,7 @@ capability:name: Memory Runtime artifact installationcanonical_tests:- tests/scenarios/memory_runtime_install/test_memory_runtime_install_scenarios.py+ - tests/scenarios/memory_runtime_install/test_memory_native_auto_switch.py- tests/test_memory_artifact_contract.py- tests/test_managed_runtime.py- tests/test_memory_runtime_release.py@@ -47,5 +48,36 @@ scenarios:- tests/test_managed_runtime.py::test_memory_latest_install_failure_safely_ignores_malformed_or_older_state- tests/test_managed_runtime.py::test_memory_latest_install_failure_rejects_symlink_state- tests/test_managed_runtime.py::test_memory_reuse_clears_latest_install_failure+ - id: MEMORY-RUNTIME-INSTALL-004+ name: Enabled startup and Wake converge same-version changed native bytes or contracts+ status: covered+ kind: upgrade+ layer: scenario+ test: tests/scenarios/memory_runtime_install/test_memory_native_auto_switch.py::test_wake_converges_same_version_release_bytes_without_changing_user_state+ given: An admitted old artifact and nonempty Unicode data root with Memory enabled+ when: A new package selects a different archive or compatibility contract at the same EverOS version+ then: Wake stops old execution, admits and activates the selected artifact, preserves data/config, and does not reinstall on the next Wake+ related_tests:+ - tests/test_memory_wake.py::test_unknown_or_current_manifest_does_not_install+ - tests/scenarios/memory_runtime_install/test_memory_native_auto_switch.py::test_selected_manifest_requires_proven_mismatch_to_replace_a_usable_artifact+ - tests/test_memory_wake.py::test_manifest_switch_requires_proven_stop_and_keeps_direct_install_guard+ - tests/test_memory_wake.py::test_preinstall_abort_resumes_capture_only_for_still_running_old_runtime+ - tests/test_memory_wake.py::test_cancelled_artifact_install_joins_before_releasing_lease+ - id: MEMORY-RUNTIME-INSTALL-005+ name: Failed automatic native cutover retains verified old availability and failure evidence+ status: covered+ kind: degradation+ layer: scenario+ test: tests/scenarios/memory_runtime_install/test_memory_native_auto_switch.py::test_failed_update_resumes_only_the_retained_admitted_artifact+ given: A working artifact and nonempty provider root from the previous release+ when: Download, digest validation, cold admission, activation, or root compatibility fails+ then: Existing pointer/data remain intact, the exact admitted old runtime can resume, and update failure stays visible+ related_tests:+ - tests/test_memory_wake.py::test_update_failure_never_wakes_an_unverified_or_changed_artifact+ - tests/scenarios/memory_runtime_install/test_memory_native_auto_switch.py::test_selected_manifest_requires_proven_mismatch_to_replace_a_usable_artifact+ - tests/test_ui_memory_routes.py::test_memory_wake_preserves_failed_update_with_old_runtime_available+ - ui/src/components/settings/SettingsMemoryPage.test.tsx+ - ui/src/components/settings/SettingsDependenciesPage.test.tsxmanual_evidence:- Install a normal wheel in a clean linux-arm64 Incus guest and consume the real published manifest and archive; verify the first Web install succeeds with Memory disabled, no model credentials, and no recovery intent.+ - Upgrade a released core/companion pair with enabled Memory and existing real data; verify unattended native convergence and real search using the new published archive. Hermetic scenario execution substitutes the native process and provider.diff --git a/tests/scenarios/memory_runtime_install/observations.yaml b/tests/scenarios/memory_runtime_install/observations.yamlindex ddd857075..70393e1a6 100644--- a/tests/scenarios/memory_runtime_install/observations.yaml+++ b/tests/scenarios/memory_runtime_install/observations.yaml@@ -10,3 +10,18 @@ observations:scenarios:- MEMORY-RUNTIME-INSTALL-003observation: Failed staging is always reclaimed while a bounded status/reason record survives process replacement; malformed, oversized, or linked state grants no status authority and a successful install or reuse clears the record.+ - id: MEMORY-RUNTIME-INSTALL-OBS-003+ scenarios:+ - MEMORY-RUNTIME-INSTALL-004+ - MEMORY-RUNTIME-INSTALL-005+ observation: A core/companion upgrade can leave a healthy same-version native artifact on earlier release bytes. Previous Wake tests equated admission with manifest currency and did not cross both real release selections. Wake now converges proven manifest mismatches under its existing operation lease without toggling persistent settings. Scenarios use actual archive integrity, pointer activation/rollback and nonempty Unicode root checks, with deterministic native/provider execution. Availability after a failed update is distinct from successful convergence; the failed attempt remains in dependency status and the Wake result.+ - id: MEMORY-RUNTIME-INSTALL-OBS-004+ scenarios:+ - MEMORY-RUNTIME-INSTALL-004+ - MEMORY-RUNTIME-INSTALL-005+ observation: Review exposed three missing consumer boundaries. A timed-out writer join must restore future intake only while the original sidecar remains admitted/running; unproved stop or shutdown stays fenced and degraded. Manifest currency is meaningful only for installable selections, not the unavailable source manifest or rejected pins/contracts. The public Web allowlist and both Wake toast consumers must preserve and display an update failure independently of retained runtime availability. Regression tests now exercise all three boundaries; raw install diagnostics are not copied into the public result.+ - id: MEMORY-RUNTIME-INSTALL-OBS-005+ scenarios:+ - MEMORY-RUNTIME-INSTALL-004+ - MEMORY-RUNTIME-INSTALL-005+ observation: A second reviewed head exposed the same authority class across time. Persisted failure evidence made the older Wake admission predicate false even though the identical fallback artifact remained verified; a later rejected or already-current selection therefore retried unnecessarily. The first rejected-manifest tests began from clean state and missed this composition. Wake now reuses its single verified active-identity check independently of attempt diagnostics, and the scenario matrix crosses clean/failed history, startup/running Wake and all rejected/current selections without clearing historical failure or weakening invalid-artifact repair.diff --git a/tests/scenarios/memory_runtime_install/test_memory_native_auto_switch.py b/tests/scenarios/memory_runtime_install/test_memory_native_auto_switch.pynew file mode 100644index 000000000..da2ab8440--- /dev/null+++ b/tests/scenarios/memory_runtime_install/test_memory_native_auto_switch.py@@ -0,0 +1,333 @@+"""Wake crosses real archive, active-pointer, and data-root boundaries.++Only native execution and remote provider responses are deterministic fakes.+No released archive, real model credential, or current user data is consumed.+"""++from __future__ import annotations++from dataclasses import asdict+import hashlib+import io+import json+from pathlib import Path+import tarfile++import pytest++from avibe_memory import artifact as artifact_module+from avibe_memory import runtime as runtime_module+from avibe_memory.artifact import MemoryArtifactManager+from avibe_memory.artifact_contract import ColdArtifactAdmissionResult+from avibe_memory.everos import FakeMemoryProvider+from avibe_memory.process import FakeEverOSProcess, FakeEverOSProcessFactory+from config.v2_config import MemoryConfig, MemoryEndpointConfig, MemoryProcessingConfig+from core import managed_runtime+from vibe import api+++def _release(tmp_path: Path, name: str, *, root_format: str = "everos-1.2.3") -> Path:+ directory = tmp_path / name+ directory.mkdir()+ binary = f"same-version native bytes: {name}".encode()+ archive = directory / "memory-runtime-1.2.3-linux-arm64.tar.gz"+ with tarfile.open(archive, "w:gz") as bundle:+ entry = tarfile.TarInfo("bin/python")+ entry.mode = 0o755+ entry.size = len(binary)+ bundle.addfile(entry, io.BytesIO(binary))+ manifest = directory / "memory-runtime-manifest.json"+ manifest.write_text(json.dumps({+ "schema_version": 1,+ "everos_version": "1.2.3",+ "python_version": "3.12.12",+ "lock_sha256": artifact_module.PACKAGE_LOCK_SHA256,+ "lock_id": f"uv-lock-sha256:{artifact_module.PACKAGE_LOCK_SHA256}",+ "uv_version": artifact_module.RUNTIME_BUILDER_UV_VERSION,+ "source": name,+ "release_state": "published",+ "provider_root_format": root_format,+ "compatible_provider_root_formats": [],+ "archives": {+ "linux-arm64": {+ "name": archive.name,+ "url": archive.as_uri(),+ "sha256": hashlib.sha256(archive.read_bytes()).hexdigest(),+ "binary_sha256": hashlib.sha256(binary).hexdigest(),+ "size": archive.stat().st_size,+ "bin_path": "bin/python",+ },+ },+ }), encoding="utf-8")+ return manifest+++def released_runtime(tmp_path, monkeypatch, memory_runtime_factory):+ monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: "linux-arm64")+ monkeypatch.setattr(artifact_module, "runtime_platform_tag", lambda: "linux-arm64")+ monkeypatch.setattr(+ artifact_module, "run_cold_artifact_admission",+ lambda _binary: ColdArtifactAdmissionResult(ok=True, reason=None, duration_ms=1),+ )+ monkeypatch.setattr(+ runtime_module, "EverOSPort", lambda *args, **kwargs: FakeMemoryProvider(),+ )+ home = tmp_path / "isolated-home"+ config = MemoryConfig(+ enabled=True,+ processing=MemoryProcessingConfig(+ llm=MemoryEndpointConfig("https://llm.test/v1", "chat", "fixture-key"),+ embedding=MemoryEndpointConfig("https://embed.test/v1", "embed", "fixture-key"),+ ),+ )++ def make(manifest):+ manager = MemoryArtifactManager(+ runtime_dir=home / "runtime" / "memory",+ manifest_path=manifest,+ provider_root=home / "memory" / "everos-root",+ )+ # These are execution probes, not archive/pointer/root validation.+ monkeypatch.setattr(manager, "_admit_error_scrubbers", lambda _binary: None)+ monkeypatch.setattr(manager, "_binary_matches_manifest", lambda *_args: True)+ processes = FakeEverOSProcessFactory()+ runtime = memory_runtime_factory(+ config, artifact_manager=manager, process_factory=processes,+ effective_home=home,+ )+ return runtime, manager, processes++ return make, home, config++[email protected]("entrypoint", ("startup", "running-wake"))[email protected]("change", ("archive", "contract"))+async def test_wake_converges_same_version_release_bytes_without_changing_user_state(+ tmp_path, monkeypatch, memory_runtime_factory, released_runtime, entrypoint, change,+):+ """MEMORY-RUNTIME-INSTALL-004: enabled upgrade converges without a config toggle."""++ make, home, config = released_runtime+ old_manifest = _release(tmp_path, "old")+ new_manifest = _release(tmp_path, "new")+ if change == "contract":+ payload = json.loads(old_manifest.read_text())+ payload["compatible_provider_root_formats"] = ["historical-compatible-format"]+ new_manifest.write_text(json.dumps(payload), encoding="utf-8")+ runtime, manager, processes = make(old_manifest)+ assert await runtime.wake() == {"ok": True, "state": "running"}+ old_python = manager.resolve_python()+ old_fingerprint = manager.artifact_fingerprint()+ root = home / "memory" / "everos-root"+ sentinel = root / "user-记忆.txt"+ sentinel.write_text("保留原有记忆 café 🌱", encoding="utf-8")+ before_root = {path.name: path.read_bytes() for path in root.iterdir() if path.is_file()}+ before_config = asdict(config)++ if entrypoint == "startup":+ await memory_runtime_factory.close(runtime)+ assert not any(process.running for process in processes.created)+ runtime, manager, processes = make(new_manifest)+ else:+ # Simulate selecting the new package manifest while the old native runs.+ monkeypatch.setattr(manager, "manifest_path", new_manifest)+ assert manager.status()["version"] == "1.2.3"+ assert manager.status()["matches_manifest"] is False+ ensured = []+ ensure = manager.ensure++ def install(*, force=False):+ assert not any(process.running for process in processes.created)+ ensured.append(force)+ return ensure(force=force)++ monkeypatch.setattr(manager, "ensure", install)+ assert await runtime.wake() == {"ok": True, "state": "running"}+ assert ensured == [True]+ assert manager.status()["version"] == "1.2.3"+ assert manager.status()["matches_manifest"] is True+ assert manager.resolve_python() != old_python # Forced admission stages a sibling.+ assert manager.artifact_fingerprint() != old_fingerprint+ assert old_python.is_file() # Previous admitted generation is retained.+ assert manager.resolve_python().read_bytes() == (+ b"same-version native bytes: new" if change == "archive" else b"same-version native bytes: old"+ )+ assert sum(process.running for process in processes.created) == 1+ assert processes.supervised[-1].python == manager.resolve_python()+ assert asdict(config) == before_config+ assert runtime._config.enabled and runtime._wake_config.enabled+ for name, content in before_root.items():+ assert (root / name).read_bytes() == content++ assert await runtime.wake() == {"ok": True, "state": "running"}+ assert ensured == [True] # Already-current Wake must not reinstall.++[email protected]("failure", ("download", "digest", "admission", "activation", "root"))+async def test_failed_update_resumes_only_the_retained_admitted_artifact(+ tmp_path, monkeypatch, memory_runtime_factory, released_runtime, failure,+):+ """MEMORY-RUNTIME-INSTALL-005: rejected candidates preserve existing data/runtime."""++ make, home, config = released_runtime+ old_manifest = _release(tmp_path, "old")+ new_manifest = _release(+ tmp_path, "new", root_format="incompatible-next-format" if failure == "root" else "everos-1.2.3",+ )+ runtime, manager, processes = make(old_manifest)+ assert await runtime.wake() == {"ok": True, "state": "running"}+ old_python = manager.resolve_python()+ old_fingerprint = manager.artifact_fingerprint()+ root = home / "memory" / "everos-root"+ sentinel = root / "user-记忆.txt"+ sentinel.write_text("已有记忆保持不变", encoding="utf-8")+ before_root = {path.name: path.read_bytes() for path in root.iterdir() if path.is_file()}+ before_config = asdict(config)+ await memory_runtime_factory.close(runtime)+ runtime, manager, processes = make(new_manifest)+ archive = new_manifest.parent / "memory-runtime-1.2.3-linux-arm64.tar.gz"+ if failure == "download":+ archive.unlink()+ elif failure == "digest":+ damaged = bytearray(archive.read_bytes())+ damaged[len(damaged) // 2] ^= 1+ archive.write_bytes(damaged) # Same size, so only the SHA256 gate catches it.+ elif failure == "admission":+ monkeypatch.setattr(+ artifact_module, "run_cold_artifact_admission",+ lambda _binary: ColdArtifactAdmissionResult(+ ok=False, reason="memory_runtime_preparation_failed", duration_ms=1,+ ),+ )+ elif failure == "activation":+ class CandidateFailure(FakeEverOSProcess):+ async def start(self):+ if self.python != old_python:+ return False+ return await super().start()+ processes.template = CandidateFailure++ result = await runtime.wake()++ assert result["state"] == "running"+ assert result["ok"] is True # Availability, not successful upgrade.+ assert result["artifact_update"]["ok"] is False+ expected_reason = {+ "download": "memory-runtime_archive_download_failed",+ "digest": "memory-runtime_archive_checksum_mismatch",+ "admission": "memory_runtime_preparation_failed",+ "activation": "memory-runtime_install_failed",+ "root": "memory_local_data_unusable",+ }[failure]+ assert result["artifact_update"]["reason"] == expected_reason+ assert manager.status()["reason"] # Failed update remains operator-visible.+ assert manager.status()["matches_manifest"] is False+ dependency = api._memory_runtime_row(+ api._MemoryRequirementProjection(True, "required"), manager.status(),+ action_class=api._memory_runtime_action_class(manager.status()),+ )+ assert dependency["has_update"] is True+ assert dependency["action_class"] == "repairable"+ assert dependency["reason"] == expected_reason+ assert manager.resolve_python() == old_python+ assert manager.artifact_fingerprint() == old_fingerprint+ assert sum(process.running for process in processes.created) == 1+ assert processes.supervised[-1].python == old_python+ assert runtime.needs_repair is False+ assert asdict(config) == before_config+ for name, content in before_root.items():+ assert (root / name).read_bytes() == content++ # Persisted failure must not turn a second failed attempt into an outage.+ again = await runtime.wake()+ assert again["ok"] is True+ assert again["artifact_update"]["ok"] is False+ assert manager.resolve_python() == old_python++[email protected]("entrypoint", ("startup", "running-wake"))[email protected]("prior_failure", (False, True), ids=("clean", "retained-failure"))+ "selection",+ ("current", "unavailable", "version", "lock", "format", "sync", "platform", "malformed", "missing"),+)+async def test_selected_manifest_requires_proven_mismatch_to_replace_a_usable_artifact(+ tmp_path, monkeypatch, memory_runtime_factory, released_runtime,+ selection, prior_failure, entrypoint,+):+ """MEMORY-RUNTIME-INSTALL-004/005: prior failure is not new install authority."""++ make, home, config = released_runtime+ old_manifest = _release(tmp_path, "old")+ runtime, manager, processes = make(old_manifest)+ assert await runtime.wake() == {"ok": True, "state": "running"}+ old_python = manager.resolve_python()+ old_fingerprint = manager.artifact_fingerprint()+ sentinel = home / "memory" / "everos-root" / "user-记忆.txt"+ sentinel.write_text("保留历史失败和已有记忆 café 🌱", encoding="utf-8")+ before_config = asdict(config)+ if prior_failure:+ failed_manifest = _release(tmp_path, "failed-update")+ (failed_manifest.parent / "memory-runtime-1.2.3-linux-arm64.tar.gz").unlink()+ monkeypatch.setattr(manager, "manifest_path", failed_manifest)+ failed = await runtime.wake()+ assert failed["ok"] is True+ assert failed["artifact_update"]["ok"] is False+ assert manager.resolve_python() == old_python+ failure_reason = manager.status()["reason"]+ assert bool(failure_reason) is prior_failure++ new_manifest = _release(tmp_path, "new")+ payload = json.loads(new_manifest.read_text())+ if selection == "unavailable":+ payload["release_state"] = "unavailable"+ elif selection == "version":+ payload["everos_version"] = "0.0.0"+ elif selection == "lock":+ payload["lock_sha256"] = "b" * 64+ elif selection == "format":+ payload["provider_root_format"] = ""+ elif selection == "sync":+ payload["sync_bootstrap_revision"] = 999+ elif selection == "platform":+ payload["archives"] = {"unavailable-platform": next(iter(payload["archives"].values()))}+ new_manifest.write_text(json.dumps(payload), encoding="utf-8")+ if selection == "malformed":+ new_manifest.write_text("{invalid-json", encoding="utf-8")+ elif selection == "missing":+ new_manifest.unlink()+ elif selection == "current":+ new_manifest = old_manifest+ if entrypoint == "startup":+ await memory_runtime_factory.close(runtime)+ runtime, manager, processes = make(new_manifest)+ else:+ monkeypatch.setattr(manager, "manifest_path", new_manifest)+ unexpected_installs = []++ def unexpected_install(**kwargs):+ # Return a normal failure so the negative-control run also proves clean+ # lifecycle teardown, rather than injecting BaseException into its task.+ unexpected_installs.append(kwargs)+ return {"ok": False, "reason": "memory_runtime_install_failed"}++ monkeypatch.setattr(manager, "ensure", unexpected_install)++ assert manager.status()["matches_manifest"] is (True if selection == "current" else None)+ assert manager.status()["reason"] == failure_reason+ result = await runtime.wake()+ assert unexpected_installs == []+ assert result == {"ok": True, "state": "running"}+ assert await runtime.wake() == {"ok": True, "state": "running"}+ assert unexpected_installs == []+ assert manager.resolve_python() == old_python+ assert manager.artifact_fingerprint() == old_fingerprint+ assert manager.status()["reason"] == failure_reason # Evidence is not cleared.+ assert sum(process.running for process in processes.created) == 1+ assert processes.supervised[-1].python == old_python+ assert sentinel.read_text(encoding="utf-8") == "保留历史失败和已有记忆 café 🌱"+ assert asdict(config) == before_configdiff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.pyindex ead408b0b..41798d16a 100644--- a/tests/test_memory_runtime.py+++ b/tests/test_memory_runtime.py@@ -386,7 +386,11 @@ async def test_revoked_lifecycle_stops_before_provider_root_side_effects(monkeypatch.setattr(runtime, "_reconcile_released_ownership", truthy)monkeypatch.setattr(runtime, "_probe_processing", truthy)- monkeypatch.setattr(runtime, "artifact_admitted", lambda: True)+ monkeypatch.setattr(+ runtime._artifact_manager, "status",+ lambda: {"installed": True, "status": "ready", "reason": None},+ )+ monkeypatch.setattr(runtime._artifact_manager, "artifact_fingerprint", lambda: "fixture")monkeypatch.setattr(runtime._artifact_manager, "resolve_python", lambda: Path("python"))monkeypatch.setattr(runtime._supervisor, "stop", delayed_stop)monkeypatch.setattr(diff --git a/tests/test_memory_wake.py b/tests/test_memory_wake.pyindex 95e98ba06..b59d2caee 100644--- a/tests/test_memory_wake.py+++ b/tests/test_memory_wake.py@@ -447,8 +447,10 @@ async def test_repair_fenced_wake_reports_released_ownership_failure(assert status["reason"] == "memory_sidecar_unavailable"[email protected]("consumer", ("install", "wake"))@pytest.mark.asyncioasync def test_cancelled_artifact_install_joins_before_releasing_lease(+ consumer: str,tmp_path: Path,monkeypatch: pytest.MonkeyPatch,memory_runtime_factory,@@ -475,12 +477,19 @@ async def test_cancelled_artifact_install_joins_before_releasing_lease(lease_events.append("release")monkeypatch.setattr(runtime_module, "MemoryOperationLease", Lease)+ artifact = BlockingArtifact(+ python=Path(sys.executable),+ status_payload={"installed": True, "status": "ready", "matches_manifest": False},+ )runtime = memory_runtime_factory(- MemoryConfig(enabled=False),- artifact_manager=BlockingArtifact(),+ _config() if consumer == "wake" else MemoryConfig(enabled=False),+ artifact_manager=artifact,+ process_factory=FakeEverOSProcessFactory(),effective_home=tmp_path,)- task = asyncio.create_task(runtime.install_artifact())+ task = asyncio.create_task(+ runtime.wake() if consumer == "wake" else runtime.install_artifact()+ )assert await asyncio.to_thread(install_started.wait, 2)task.cancel()@@ -494,6 +503,132 @@ async def test_cancelled_artifact_install_joins_before_releasing_lease(assert lease_events == ["acquire", "release"][email protected]("mismatch", (None, True))+async def test_unknown_or_current_manifest_does_not_install(+ tmp_path, monkeypatch, memory_runtime_factory, mismatch,+):+ artifact = FakeMemoryArtifactManager(+ python=Path(sys.executable),+ status_payload={"installed": True, "status": "ready", "matches_manifest": mismatch},+ )+ monkeypatch.setattr(runtime_module, "EverOSPort", lambda *args, **kwargs: FakeMemoryProvider())+ runtime = memory_runtime_factory(+ _config(), artifact_manager=artifact,+ process_factory=FakeEverOSProcessFactory(), effective_home=tmp_path,+ )+ assert await runtime.wake() == {"ok": True, "state": "running"}+ assert artifact.ensure_calls == []++[email protected]("invalid", ("before", "after", "changed", "unidentified"))+async def test_update_failure_never_wakes_an_unverified_or_changed_artifact(+ tmp_path, monkeypatch, memory_runtime_factory, invalid,+):+ class FailedUpdate(FakeMemoryArtifactManager):+ def ensure(self, *, force=False):+ self.ensure_calls.append(force)+ if invalid == "after":+ self.python = None+ elif invalid == "changed":+ self.fingerprint = "different-artifact"+ return {"ok": False, "reason": "memory_runtime_install_failed"}++ artifact = FailedUpdate(+ python=Path(sys.executable),+ status_payload={+ "installed": invalid != "before",+ "status": "invalid" if invalid == "before" else "ready",+ "matches_manifest": False,+ },+ fingerprint=None if invalid == "unidentified" else "old-admitted-artifact",+ )+ monkeypatch.setattr(runtime_module, "EverOSPort", lambda *args, **kwargs: FakeMemoryProvider())+ processes = FakeEverOSProcessFactory()+ runtime = memory_runtime_factory(+ _config(), artifact_manager=artifact, process_factory=processes, effective_home=tmp_path,+ )++ result = await runtime.wake()++ assert result == {"ok": False, "state": "degraded", "error": "memory_runtime_install_failed"}+ assert artifact.ensure_calls == [True]+ assert processes.created == []+++async def test_manifest_switch_requires_proven_stop_and_keeps_direct_install_guard(+ tmp_path, monkeypatch, memory_runtime_factory,+):+ artifact = FakeMemoryArtifactManager(python=Path(sys.executable))+ monkeypatch.setattr(runtime_module, "EverOSPort", lambda *args, **kwargs: FakeMemoryProvider())+ processes = FakeEverOSProcessFactory()+ runtime = memory_runtime_factory(+ _config(), artifact_manager=artifact, process_factory=processes, effective_home=tmp_path,+ )+ assert await runtime.wake() == {"ok": True, "state": "running"}+ artifact.status_payload["matches_manifest"] = False+ assert (await runtime.install_artifact())["reason"] == "memory_runtime_install_requires_stopped_memory"+ child = processes.supervised[-1]+ child.stop_failure = RuntimeError("fixture cannot prove process exit")+ try:+ result = await runtime.wake()+ assert result["ok"] is False+ assert artifact.ensure_calls == []+ assert runtime.runtime_state() == "degraded"+ assert runtime.module.reserve_capture_capacity() == "disabled"+ finally:+ child.stop_failure = None++[email protected]("abort", ("quiesce", "writer-close", "stop-before-effect"))+async def test_preinstall_abort_resumes_capture_only_for_still_running_old_runtime(+ tmp_path, monkeypatch, memory_runtime_factory, abort,+):+ artifact = FakeMemoryArtifactManager(python=Path(sys.executable))+ monkeypatch.setattr(runtime_module, "EverOSPort", lambda *args, **kwargs: FakeMemoryProvider())+ processes = FakeEverOSProcessFactory()+ runtime = memory_runtime_factory(+ _config(), artifact_manager=artifact, process_factory=processes, effective_home=tmp_path,+ )+ assert await runtime.wake() == {"ok": True, "state": "running"}+ artifact.status_payload["matches_manifest"] = False+ pending = runtime.module.reserve_capture_capacity()+ assert not isinstance(pending, str)+ quiesce = runtime.module.quiesce_claims++ async def bounded_quiesce(**_kwargs):+ # Real writer close completes, but a held capture reservation exceeds+ # the join deadline. The old process is still usable.+ return await quiesce(timeout_seconds=0.001)++ async def fail_before_stopping():+ raise RuntimeError("fixture pre-install abort")++ with monkeypatch.context() as scope:+ if abort == "quiesce":+ scope.setattr(runtime.module, "quiesce_claims", bounded_quiesce)+ else:+ runtime.module.release_capture_capacity(pending)+ scope.setattr(+ runtime if abort == "writer-close" else runtime._supervisor,+ "_close_writer" if abort == "writer-close" else "stop",+ fail_before_stopping,+ )+ result = await runtime.wake()++ runtime.module.release_capture_capacity(pending)+ assert result["ok"] is False+ assert runtime.runtime_state() == "degraded" # Abort remains observable.+ assert artifact.ensure_calls == []+ assert processes.supervised[-1].running+ admitted = runtime.module.reserve_capture_capacity()+ assert not isinstance(admitted, str)+ runtime.module.release_capture_capacity(admitted)++@pytest.mark.asyncioasync def test_unexpected_exit_reenters_wake_and_repairs_the_artifact(tmp_path: Path,diff --git a/tests/test_ui_memory_routes.py b/tests/test_ui_memory_routes.pyindex 4a2440095..d884b2740 100644--- a/tests/test_ui_memory_routes.py+++ b/tests/test_ui_memory_routes.py@@ -328,6 +328,40 @@ def test_memory_wake_is_non_destructive_and_preserves_closed_result(assert calls == [True]+def test_memory_wake_preserves_failed_update_with_old_runtime_available(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config()++ async def wake():+ return {+ "status_code": 200,+ "body": {+ "ok": True,+ "state": "running",+ "artifact_update": {+ "ok": False,+ "reason": "memory_runtime_install_failed",+ "download_error": {"private_detail": "not-public"},+ },+ },+ }++ monkeypatch.setattr(internal_client, "memory_wake", wake)+ client = app.test_client()+ response = client.post(+ "/api/memory/runtime/wake", json={},+ headers=csrf_headers(client, BASE_URL), **_request_options(),+ )+ assert response.status_code == 200+ assert response.get_json() == {+ "ok": True, "state": "running",+ "artifact_update": {"ok": False, "reason": "memory_runtime_install_failed"},+ }++def _assert_memory_destructive_route_contract(monkeypatch: pytest.MonkeyPatch,tmp_path,diff --git a/ui/src/components/settings/SettingsDependenciesPage.test.tsx b/ui/src/components/settings/SettingsDependenciesPage.test.tsxindex 695b5c9ce..b61b2c048 100644--- a/ui/src/components/settings/SettingsDependenciesPage.test.tsx+++ b/ui/src/components/settings/SettingsDependenciesPage.test.tsx@@ -461,6 +461,22 @@ describe('SettingsDependenciesPage Memory runtime', () => {expect(api.installDependency).not.toHaveBeenCalled();});+ it('does not toast update success merely because the previous native engine restarted', async () => {+ stubDependencies({ ok: true, deps: [dependency({ installed: false, status: 'missing', action_class: 'repairable' })] });+ api.getMemoryStatus.mockResolvedValue({ status: 'ok', state: 'degraded' });+ api.wakeMemory.mockResolvedValue({+ ok: true, state: 'running',+ artifact_update: { ok: false, reason: 'memory_runtime_install_failed' },+ });+ renderPage();+ await userEvent.click(await screen.findByRole('button', { name: 'memory.runtimeAction.retryButton' }));+ await waitFor(() => expect(showToast).toHaveBeenCalledWith(+ 'memory.runtimeAction.updateFailedStillRunning', 'error',+ ));+ expect(showToast).not.toHaveBeenCalledWith('memory.runtimeAction.completed', 'success');+ expect(api.installDependency).not.toHaveBeenCalled();+ });+it.each(['memory_runtime_preparation_failed','memory_runtime_preparation_import_timeout',diff --git a/ui/src/components/settings/SettingsDependenciesPage.tsx b/ui/src/components/settings/SettingsDependenciesPage.tsxindex 6f0f25f66..a67d13b35 100644--- a/ui/src/components/settings/SettingsDependenciesPage.tsx+++ b/ui/src/components/settings/SettingsDependenciesPage.tsx@@ -32,7 +32,7 @@ import {memoryRuntimeSidecarRunning,} from './SettingsDependenciesPage.logic';import { errorMessage } from '@/lib/errorMessage';-import { memoryErrorMessage } from '@/lib/memoryRead';+import { memoryWakeFailureMessage } from '@/lib/memoryRead';import { useDependencyChecks } from './useDependencyChecks';// Mirrors design.pen "vibe-remote — Settings · Dependencies": one card per@@ -112,9 +112,10 @@ export const SettingsDependenciesPage: React.FC = () => {if (recoverRuntime) {// Wake owns stop proof and artifact recovery for an active runtime.const result = await api.wakeMemory();+ const failure = memoryWakeFailureMessage(t, result);showToast(- result.ok ? t('memory.runtimeAction.completed') : memoryErrorMessage(t, result.error),- result.ok ? 'success' : 'error',+ failure ?? t('memory.runtimeAction.completed'),+ failure ? 'error' : 'success',);return;}diff --git a/ui/src/components/settings/SettingsMemoryPage.test.tsx b/ui/src/components/settings/SettingsMemoryPage.test.tsxindex de0dc7d7f..84fd83590 100644--- a/ui/src/components/settings/SettingsMemoryPage.test.tsx+++ b/ui/src/components/settings/SettingsMemoryPage.test.tsx@@ -291,6 +291,20 @@ describe('SettingsMemoryPage', () => {expect(api.deleteMemoryData).not.toHaveBeenCalled();});+ it('reports a failed native update even when the old runtime remains available', async () => {+ api.getMemoryStatus.mockResolvedValue(status('degraded'));+ api.wakeMemory.mockResolvedValue({+ ok: true, state: 'running',+ artifact_update: { ok: false, reason: 'memory_runtime_install_failed' },+ });+ renderPage();+ await userEvent.click(await screen.findByRole('button', { name: 'memory.runtimeAction.retryButton' }));+ expect(await screen.findByText('memory.runtimeAction.updateFailedStillRunning')).toBeTruthy();+ expect(screen.queryByText('memory.runtimeAction.completed')).toBeNull();+ expect(api.repairMemory).not.toHaveBeenCalled();+ expect(api.deleteMemoryData).not.toHaveBeenCalled();+ });+it.each(['starting', 'needs_repair'] as const)('hides runtime restart actions while Memory is %s', async (state) => {api.getMemoryStatus.mockResolvedValue(status(state));renderPage();diff --git a/ui/src/components/settings/SettingsMemoryPage.tsx b/ui/src/components/settings/SettingsMemoryPage.tsxindex ea5213180..3c8a3ed92 100644--- a/ui/src/components/settings/SettingsMemoryPage.tsx+++ b/ui/src/components/settings/SettingsMemoryPage.tsx@@ -26,7 +26,7 @@ import type {MemoryStatus,} from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';-import { memoryErrorMessage } from '../../lib/memoryRead';+import { memoryErrorMessage, memoryWakeFailureMessage } from '../../lib/memoryRead';import {isMemoryProcessingRecordReason,memoryStatusSourceReasonLabel,@@ -125,9 +125,10 @@ export const SettingsMemoryPage: React.FC = () => {setWaking(true);try {const result = await api.wakeMemory();+ const failure = memoryWakeFailureMessage(t, result);showToast(- result.ok ? t('memory.runtimeAction.completed') : memoryErrorMessage(t, result.error),- result.ok ? 'success' : 'error',+ failure ?? t('memory.runtimeAction.completed'),+ failure ? 'error' : 'success',);} catch {showToast(t('memory.runtimeAction.failed'), 'error');diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex f758efa20..3be57e07c 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -2221,9 +2221,10 @@ export type MemoryProcessingRecordDetailResult =}| MemoryFailure;-export type MemoryWakeResult =+export type MemoryWakeResult = (| { ok: true; state: 'running' }- | { ok: false; state?: MemoryStatus['state']; error?: string };+ | { ok: false; state?: MemoryStatus['state']; error?: string }+) & { artifact_update?: { ok: boolean; reason?: string | null } };export type MemoryDataOperationResult = {ok: boolean;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex ef460fe9c..08aaca7e4 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4609,6 +4609,7 @@"restartRunning": "Restarting…","restartDescription": "Stops and restarts EverOS without deleting Memory data.","completed": "Memory service is ready.",+ "updateFailedStillRunning": "The Memory engine update failed. The previous verified engine is still running; no Memory data was deleted.","failed": "Memory service could not start. No Memory data was deleted."},"repair": {diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex b71bef299..ac01316e6 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4609,6 +4609,7 @@"restartRunning": "正在重启…","restartDescription": "停止并重新启动 EverOS,不会删除记忆数据。","completed": "记忆服务已就绪。",+ "updateFailedStillRunning": "记忆引擎更新失败,已验证的旧引擎仍在运行,未删除任何记忆数据。","failed": "无法启动记忆服务,未删除任何记忆数据。"},"repair": {diff --git a/ui/src/lib/memoryRead.ts b/ui/src/lib/memoryRead.tsindex 02cfa2c38..f2925dcfd 100644--- a/ui/src/lib/memoryRead.ts+++ b/ui/src/lib/memoryRead.ts@@ -1,4 +1,5 @@import type { TFunction } from 'i18next';+import type { MemoryWakeResult } from '../context/ApiContext';// Backend forbidden path (`_memory_forbidden_response`) returns exactly this closed shape for// every Memory route when the request is neither direct-loopback nor an authenticated@@ -61,3 +62,9 @@ export const memoryErrorMessage = (].filter(Boolean);return details.length > 0 ? `${base}: ${details.join(' · ')}` : base;};++/** Availability after fallback is not a successful selected-artifact update. */+export const memoryWakeFailureMessage = (t: TFunction, result: MemoryWakeResult): string | null => {+ if (!result.ok) return memoryErrorMessage(t, result.error);+ return result.artifact_update?.ok === false ? t('memory.runtimeAction.updateFailedStillRunning') : null;+};diff --git a/vibe/ui_memory_routes.py b/vibe/ui_memory_routes.pyindex d51e8d6f6..e3dad97e3 100644--- a/vibe/ui_memory_routes.py+++ b/vibe/ui_memory_routes.py@@ -381,6 +381,14 @@ def _memory_operation_response(payload: dict, status_code: int) -> Response:"roots",}public = {key: payload[key] for key in allowed if key in payload}+ update = payload.get("artifact_update")+ if isinstance(update, dict) and isinstance(update.get("ok"), bool):+ public["artifact_update"] = {+ "ok": update["ok"],+ "reason": _memory_closed_error(+ {"error": update.get("reason")}, fallback="memory_runtime_install_failed"+ ) if update["ok"] is False else None,+ }if payload.get("ok") is not True and "error" not in public:public["error"] = "memory_sidecar_unavailable"return _memory_response(public, status_code=status_code)