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): align cold runtime admission (#1789)
rkrkrkk442ae2c72403
diff --git a/core/memory/artifact.py b/core/memory/artifact.pyindex 0e2b55d37..0d7c13dc3 100644--- a/core/memory/artifact.py+++ b/core/memory/artifact.py@@ -42,6 +42,11 @@ from core.memory.confined_filesystem import (remove_confined_path,replace_confined,)+from core.memory.artifact_contract import (+ EMBEDDED_PYTHON_VERSION,+ EVEROS_VERSION,+ run_cold_artifact_admission,+)from core.memory.provider_root import (PROVIDER_ROOT_CONTROL_FILES,ROOT_SENTINEL_FILENAME,@@ -50,11 +55,8 @@ from core.memory.provider_root import (ProviderRootMetadata,ProviderRootState,)-from core.memory.modality import pinned_modality_contract_script-EVEROS_VERSION = "1.2.3"-EMBEDDED_PYTHON_VERSION = "3.12.12"PACKAGE_LOCK_SHA256 = "e6acc17e4c0969563d380326e90134965af0822259bb4a9adb4d54433e9737fe"RUNTIME_BUILDER_UV_VERSION = "0.9.18"ARTIFACT_ADMISSION_REVISION = 1@@ -70,27 +72,17 @@ _SPEC = ManagedRuntimeSpec(version_field="everos_version",default_bin_path="bin/python",)-_SMOKE_SCRIPT = (- "from importlib.metadata import version\n"- "import platform\n"- "import everos\n"- "import uvicorn\n"- "from everos.entrypoints.api.app import create_app\n"- "import everos.entrypoints.cli.main\n"- "import everos.memory.cascade\n"- f"assert version('everos') == '{EVEROS_VERSION}'\n"- "assert platform.python_version() == '3.12.12'\n"- "assert everos is not None and uvicorn is not None\n"- "assert callable(create_app)\n"- + pinned_modality_contract_script()- +- "print(version('everos'))\n"- "print(platform.python_version())\n"-)_SCRUBBER_ADMISSION_SCRIPT = ("from core.memory.secret_scrubber import install_error_scrubbers\n""install_error_scrubbers()\n")+_SCRUBBER_ADMISSION_TIMEOUT_SECONDS = 30+_SCRUBBER_ADMISSION_TIMEOUT_REASON = "memory_runtime_preparation_scrubber_timeout"+_SCRUBBER_ADMISSION_FAILURE_REASON = "memory_runtime_preparation_scrubber_failed"+_SYNC_ADMISSION_FAILURE_REASON = "memory_runtime_preparation_sync_contract_failed"+_PREPARATION_FAILURE_REASON = "memory_runtime_preparation_failed"+_LATEST_INSTALL_FAILURE_FILENAME = "last-install-failure.json"+_MAX_LATEST_INSTALL_FAILURE_BYTES = 4 * 1024_PROVIDER_ROOT_REPAIR_MARKERS = ("incompatible","does not match",@@ -205,6 +197,7 @@ class MemoryArtifactManager(ManagedRuntimeManager):if self._dev_runtime_configured():return self._dev_runtime_status(self._dev_runtime_python())self._install_reason = None+ latest_failure = self._read_latest_install_failure()manifest = self._load_manifest(allow_network=False)if manifest is not None:self._manifest_installable(manifest)@@ -215,11 +208,14 @@ class MemoryArtifactManager(ManagedRuntimeManager):except OSError:binary = Noneinvalid = True- if (- pointer is not None+ admission_rejected = (+ not invalid+ and pointer is not None+ and binary is not Noneand pointer.get("admission_revision") == ARTIFACT_ADMISSION_REVISIONand pointer.get("admission_ok") is not True- ):+ )+ if admission_rejected:binary = Noneinvalid = Trueinvalid = invalid or (pointer is not None and binary is None)@@ -257,6 +253,15 @@ class MemoryArtifactManager(ManagedRuntimeManager):except (MemoryRuntimeActivationError, ValueError):matches_manifest = Falseinstalled_version = pointer.get("runtime_version") if binary is not None else None+ persisted_reason = latest_failure.get("reason") if latest_failure is not None else None+ if admission_rejected and persisted_reason is not None:+ failure_reason = persisted_reason+ elif invalid:+ failure_reason = "memory_runtime_install_failed"+ else:+ failure_reason = persisted_reason or (+ self._install_reason if binary is None else None+ )return {"id": self.spec.runtime_id,"provider": "manifest",@@ -265,12 +270,16 @@ class MemoryArtifactManager(ManagedRuntimeManager):"version": installed_version,"selected_version": selected_version,"matches_manifest": matches_manifest,- "status": "ready" if binary is not None else ("error" if invalid else "missing"),+ "status": (+ "ready"+ if binary is not None+ else ("error" if invalid or persisted_reason is not None else "missing")+ ),"path": str(binary) if binary is not None else None,"install_dir": pointer.get("install_dir") if binary is not None else None,"manifest": self._manifest_status_payload(manifest),"archive": self._archive_status_payload(archive),- "reason": "memory_runtime_install_failed" if invalid else (self._install_reason if binary is None else None),+ "reason": failure_reason,"download_error": self._download_error,}@@ -478,10 +487,10 @@ class MemoryArtifactManager(ManagedRuntimeManager):preparation = self._prepare_binary(binary, sync_contract=sync_contract)except Exception: # noqa: BLE001logger.exception("Failed to admit existing Memory runtime binary")- preparation = {"ok": False}+ preparation = {"ok": False, "reason": _PREPARATION_FAILURE_REASON}if preparation.get("ok") is not True:return self._failure(- "memory_runtime_install_failed",+ str(preparation.get("reason") or _PREPARATION_FAILURE_REASON),manifest=manifest,archive=archive,)@@ -615,6 +624,45 @@ class MemoryArtifactManager(ManagedRuntimeManager):archive=archive,)+ def _success_payload(+ self,+ binary: Path,+ install_dir: Path,+ manifest: ManagedRuntimeManifest,+ archive: ManagedRuntimeArchive,+ *,+ changed: bool,+ ) -> dict[str, Any]:+ payload = super()._success_payload(+ binary,+ install_dir,+ manifest,+ archive,+ changed=changed,+ )+ self._clear_latest_install_failure()+ return payload++ def _failure(+ self,+ reason: str,+ *,+ manifest: ManagedRuntimeManifest | None = None,+ archive: ManagedRuntimeArchive | None = None,+ message: str | None = None,+ skipped: bool = False,+ ) -> dict[str, Any]:+ payload = super()._failure(+ reason,+ manifest=manifest,+ archive=archive,+ message=message,+ skipped=skipped,+ )+ if not skipped:+ self._write_latest_install_failure(reason)+ return payload+def _candidate_from_manifest(self, manifest: ManagedRuntimeManifest) -> MemoryArtifactCandidate:provider_root_format = manifest.payload.get("provider_root_format")compatible_values = manifest.payload.get("compatible_provider_root_formats", [])@@ -735,7 +783,11 @@ class MemoryArtifactManager(ManagedRuntimeManager):admitted_pointer["admission_ok"] = admission_okself._restore_current_pointer(admitted_pointer)if not admission_ok:- self._install_reason = "memory_runtime_install_failed"+ admission_reason = str(+ preparation.get("reason") or _PREPARATION_FAILURE_REASON+ )+ self._install_reason = admission_reason+ self._write_latest_install_failure(admission_reason)return Noneexcept Exception: # noqa: BLE001self._install_reason = "memory_runtime_install_failed"@@ -752,7 +804,7 @@ class MemoryArtifactManager(ManagedRuntimeManager):archive: ManagedRuntimeArchive,candidate: MemoryArtifactCandidate,) -> None:- _write_memory_pointer_atomic(+ _write_memory_state_atomic(self.runtime_dir,self.runtime_dir / "current.json",{@@ -785,7 +837,7 @@ class MemoryArtifactManager(ManagedRuntimeManager):"memory runtime pointer could not be removed safely") from errorreturn- _write_memory_pointer_atomic(self.runtime_dir, current, pointer)+ _write_memory_state_atomic(self.runtime_dir, current, pointer)def _binary_version(self, binary: Path | None) -> str | None:if binary is None or not binary.is_file():@@ -812,23 +864,23 @@ class MemoryArtifactManager(ManagedRuntimeManager):*,sync_contract: tuple[int, tuple[str, ...], str, str] | None = None,) -> dict[str, Any]:- try:- result = subprocess.run(- [str(binary), "-I", "-c", _SMOKE_SCRIPT],- capture_output=True,- text=True,- timeout=30,- check=False,- **isolated_subprocess_kwargs(),- )- except (OSError, subprocess.SubprocessError):- return {"ok": False, "reason": "memory_runtime_install_failed"}- if result.returncode != 0 or result.stdout.splitlines() != [EVEROS_VERSION, EMBEDDED_PYTHON_VERSION]:- return {"ok": False, "reason": "memory_runtime_install_failed"}- if not self._admit_error_scrubbers(binary):- return {"ok": False, "reason": "memory_runtime_install_failed"}+ cold_admission = run_cold_artifact_admission(binary)+ logger.info(+ "Memory runtime cold import admission completed in %d ms (ok=%s, reason=%s)",+ cold_admission.duration_ms,+ cold_admission.ok,+ cold_admission.reason,+ )+ if not cold_admission.ok:+ return {+ "ok": False,+ "reason": cold_admission.reason or _PREPARATION_FAILURE_REASON,+ }+ scrubber_failure = self._admit_error_scrubbers(binary)+ if scrubber_failure is not None:+ return {"ok": False, "reason": scrubber_failure}if not self._admit_sync_contract(binary, sync_contract):- return {"ok": False, "reason": "memory_runtime_install_failed"}+ return {"ok": False, "reason": _SYNC_ADMISSION_FAILURE_REASON}return {"ok": True,"everos_version": EVEROS_VERSION,@@ -867,7 +919,7 @@ class MemoryArtifactManager(ManagedRuntimeManager):except (OSError, UnicodeError):return False- def _admit_error_scrubbers(self, binary: Path) -> bool:+ def _admit_error_scrubbers(self, binary: Path) -> str | None:"""Prove the child can install mandatory diagnostic scrubbers before launch."""source_root = Path(__file__).resolve().parents[2]@@ -878,7 +930,7 @@ class MemoryArtifactManager(ManagedRuntimeManager):[str(binary), "-c", _SCRUBBER_ADMISSION_SCRIPT],capture_output=True,text=True,- timeout=30,+ timeout=_SCRUBBER_ADMISSION_TIMEOUT_SECONDS,check=False,cwd=str(source_root),env={@@ -893,12 +945,80 @@ class MemoryArtifactManager(ManagedRuntimeManager):},**isolated_subprocess_kwargs(),)+ except subprocess.TimeoutExpired:+ return _SCRUBBER_ADMISSION_TIMEOUT_REASONexcept (OSError, subprocess.SubprocessError):- return False- return result.returncode == 0+ return _SCRUBBER_ADMISSION_FAILURE_REASON+ return None if result.returncode == 0 else _SCRUBBER_ADMISSION_FAILURE_REASON++ def _read_latest_install_failure(self) -> dict[str, str] | None:+ path = self.runtime_dir / _LATEST_INSTALL_FAILURE_FILENAME+ try:+ expected = path.lstat()+ except OSError:+ return None+ if (+ not stat.S_ISREG(expected.st_mode)+ or expected.st_size > _MAX_LATEST_INSTALL_FAILURE_BYTES+ ):+ return None+ try:+ ensure_private_directory(self.runtime_dir, self.runtime_dir)+ descriptor = open_and_harden_confined_regular_file(self.runtime_dir, path)+ except (ConfinedFilesystemError, OSError):+ return None+ try:+ actual = os.fstat(descriptor)+ if (+ not stat.S_ISREG(actual.st_mode)+ or actual.st_dev != expected.st_dev+ or actual.st_ino != expected.st_ino+ or actual.st_size > _MAX_LATEST_INSTALL_FAILURE_BYTES+ ):+ return None+ encoded = os.read(descriptor, _MAX_LATEST_INSTALL_FAILURE_BYTES + 1)+ except OSError:+ return None+ finally:+ os.close(descriptor)+ if len(encoded) > _MAX_LATEST_INSTALL_FAILURE_BYTES:+ return None+ try:+ payload = json.loads(encoded.decode("utf-8"))+ except (RecursionError, UnicodeError, ValueError):+ return None+ if (+ not isinstance(payload, dict)+ or payload.get("status") != "error"+ or not _safe_metadata_value(payload.get("reason"))+ ):+ return None+ return {"status": "error", "reason": payload["reason"]}++ def _write_latest_install_failure(self, reason: str) -> None:+ bounded_reason = reason if _safe_metadata_value(reason) else _PREPARATION_FAILURE_REASON+ try:+ _write_memory_state_atomic(+ self.runtime_dir,+ self.runtime_dir / _LATEST_INSTALL_FAILURE_FILENAME,+ {"status": "error", "reason": bounded_reason},+ )+ except MemoryRuntimeActivationError:+ logger.warning("Failed to persist Memory runtime install failure", exc_info=True)++ def _clear_latest_install_failure(self) -> None:+ try:+ remove_confined_path(+ self.runtime_dir,+ self.runtime_dir / _LATEST_INSTALL_FAILURE_FILENAME,+ )+ except FileNotFoundError:+ pass+ except (ConfinedFilesystemError, OSError):+ logger.warning("Failed to clear Memory runtime install failure", exc_info=True)-def _write_memory_pointer_atomic(+def _write_memory_state_atomic(runtime_root: Path,path: Path,payload: dict[str, Any],@@ -913,7 +1033,7 @@ def _write_memory_pointer_atomic(while view:written = os.write(descriptor, view)if written <= 0:- raise OSError("memory runtime pointer write made no progress")+ raise OSError("memory runtime state write made no progress")view = view[written:]os.fsync(descriptor)os.close(descriptor)@@ -922,7 +1042,7 @@ def _write_memory_pointer_atomic(fsync_directory(runtime_root)except (ConfinedFilesystemError, OSError) as error:raise MemoryRuntimeActivationError(- "memory runtime pointer could not be written safely"+ "memory runtime state could not be written safely") from errorfinally:if descriptor is not None:diff --git a/core/memory/artifact_contract.py b/core/memory/artifact_contract.pynew file mode 100644index 000000000..ca21d5d0f--- /dev/null+++ b/core/memory/artifact_contract.py@@ -0,0 +1,99 @@+"""Shared cold-admission contract for released Memory Runtime artifacts."""++from __future__ import annotations++import os+import subprocess+import time+from dataclasses import dataclass+from pathlib import Path++from core.memory.modality import pinned_modality_contract_script+++EVEROS_VERSION = "1.2.3"+EMBEDDED_PYTHON_VERSION = "3.12.12"+COLD_ARTIFACT_ADMISSION_TIMEOUT_SECONDS = 120+COLD_ARTIFACT_ADMISSION_TIMEOUT_REASON = "memory_runtime_preparation_import_timeout"+COLD_ARTIFACT_ADMISSION_FAILURE_REASON = "memory_runtime_preparation_import_failed"++_COLD_ARTIFACT_ADMISSION_SCRIPT = (+ "from importlib.metadata import version\n"+ "import platform\n"+ "import everos\n"+ "import uvicorn\n"+ "from everos.entrypoints.api.app import create_app\n"+ "import everos.entrypoints.cli.main\n"+ "import everos.memory.cascade\n"+ f"assert version('everos') == '{EVEROS_VERSION}'\n"+ f"assert platform.python_version() == '{EMBEDDED_PYTHON_VERSION}'\n"+ "assert everos is not None and uvicorn is not None\n"+ "assert callable(create_app)\n"+ + pinned_modality_contract_script()+ + "print(version('everos'))\n"+ "print(platform.python_version())\n"+)+++@dataclass(frozen=True)+class ColdArtifactAdmissionResult:+ """One bounded observation of the released artifact's cold import surface."""++ ok: bool+ reason: str | None+ duration_ms: int+++def run_cold_artifact_admission(+ binary: Path,+ *,+ timeout_seconds: int = COLD_ARTIFACT_ADMISSION_TIMEOUT_SECONDS,+) -> ColdArtifactAdmissionResult:+ """Run the exact cold import gate shared by release verification and install."""++ started_at = time.monotonic()+ try:+ result = subprocess.run(+ [str(binary), "-I", "-c", _COLD_ARTIFACT_ADMISSION_SCRIPT],+ capture_output=True,+ text=True,+ timeout=timeout_seconds,+ check=False,+ cwd=binary.parent.parent,+ **_isolated_subprocess_kwargs(),+ )+ except subprocess.TimeoutExpired:+ return ColdArtifactAdmissionResult(+ ok=False,+ reason=COLD_ARTIFACT_ADMISSION_TIMEOUT_REASON,+ duration_ms=_duration_ms(started_at),+ )+ except (OSError, subprocess.SubprocessError):+ return ColdArtifactAdmissionResult(+ ok=False,+ reason=COLD_ARTIFACT_ADMISSION_FAILURE_REASON,+ duration_ms=_duration_ms(started_at),+ )++ expected_output = [EVEROS_VERSION, EMBEDDED_PYTHON_VERSION]+ return ColdArtifactAdmissionResult(+ ok=result.returncode == 0 and result.stdout.splitlines() == expected_output,+ reason=(+ None+ if result.returncode == 0 and result.stdout.splitlines() == expected_output+ else COLD_ARTIFACT_ADMISSION_FAILURE_REASON+ ),+ duration_ms=_duration_ms(started_at),+ )+++def _duration_ms(started_at: float) -> int:+ return max(0, int((time.monotonic() - started_at) * 1000))+++def _isolated_subprocess_kwargs() -> dict[str, object]:+ """Keep the release-builder import path free of installed dependencies."""++ if os.name == "nt":+ return {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}+ return {"start_new_session": True}diff --git a/scripts/build_memory_runtime.py b/scripts/build_memory_runtime.pyindex 88a6c1bf1..7a23ae421 100644--- a/scripts/build_memory_runtime.py+++ b/scripts/build_memory_runtime.py@@ -18,9 +18,18 @@ from collections.abc import Iteratorfrom contextlib import contextmanagerfrom pathlib import Path, PurePosixPath, PureWindowsPath+REPO_ROOT = Path(__file__).resolve().parents[1]+if str(REPO_ROOT) not in sys.path:+ sys.path.insert(0, str(REPO_ROOT))++from core.memory.artifact_contract import (+ EMBEDDED_PYTHON_VERSION,+ EVEROS_VERSION,+ run_cold_artifact_admission,+)+-EVEROS_VERSION = "1.2.3"-PYTHON_VERSION = "3.12.12"+PYTHON_VERSION = EMBEDDED_PYTHON_VERSIONLOCK_SHA256 = "e6acc17e4c0969563d380326e90134965af0822259bb4a9adb4d54433e9737fe"UV_VERSION = "0.9.18"BIN_PATH = "bin/python"@@ -186,7 +195,17 @@ def verify_archive(archive_path: Path, *, binary_sha256: str) -> None:binary = _validate_runtime_tree(destination)if _sha256(binary) != binary_sha256:raise SystemExit("Memory Runtime extracted Python checksum mismatch")- _smoke(binary, cwd=destination.parent)+ admission = run_cold_artifact_admission(binary)+ print(+ "Memory Runtime cold artifact admission: "+ f"{admission.duration_ms} ms ({admission.reason or 'ok'})",+ file=sys.stderr,+ )+ if not admission.ok:+ raise SystemExit(+ "Memory Runtime cold artifact admission failed: "+ f"{admission.reason or 'memory_runtime_preparation_failed'}"+ )with _short_socket_directory("mrv-") as health_home:_sidecar_health_smoke(binary, effective_home=health_home)diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex b6c007c64..ec3eb3088 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -8,6 +8,19 @@ navigation:- Read that capability's observations.yaml.- Read the listed scenario test files before changing production code.capabilities:+ - id: memory_runtime_install+ name: Memory Runtime artifact installation+ status: active+ catalog: tests/scenarios/memory_runtime_install/catalog.yaml+ observations: tests/scenarios/memory_runtime_install/observations.yaml+ scenario_tests:+ - tests/scenarios/memory_runtime_install/test_memory_runtime_install_scenarios.py+ unit_or_contract_tests:+ - tests/test_memory_artifact_contract.py+ - tests/test_managed_runtime.py+ - tests/test_memory_runtime_release.py+ - tests/test_ui_server_install.py+ - ui/src/components/settings/SettingsDependenciesPage.test.tsx- id: memory_delete_dataname: Explicit confirmed deletion of confined Memory datastatus: activediff --git a/tests/scenarios/memory_runtime_install/catalog.yaml b/tests/scenarios/memory_runtime_install/catalog.yamlnew file mode 100644index 000000000..8a09a3515--- /dev/null+++ b/tests/scenarios/memory_runtime_install/catalog.yaml@@ -0,0 +1,51 @@+version: 1+capability:+ id: memory_runtime_install+ name: Memory Runtime artifact installation+ canonical_tests:+ - tests/scenarios/memory_runtime_install/test_memory_runtime_install_scenarios.py+ - tests/test_memory_artifact_contract.py+ - tests/test_managed_runtime.py+ - tests/test_memory_runtime_release.py+status_legend:+ covered: executable evidence exists at the declared layer+ partial: hermetic contract evidence exists and released-archive regression remains manual+scenarios:+ - id: MEMORY-RUNTIME-INSTALL-001+ name: Disabled Memory installs a manifest-shaped linux-arm64 fixture through the Web job+ status: partial+ kind: happy_path+ layer: scenario+ test: tests/scenarios/memory_runtime_install/test_memory_runtime_install_scenarios.py::test_disabled_memory_installs_manifest_shaped_linux_arm64_artifact_through_web_job+ actor: Fresh Avibe user+ trigger: The user installs memory-runtime from Settings Dependencies+ conditions:+ - Memory is disabled with no model credentials or recovery intent+ - The selected manifest and linux-arm64 archive are hermetic test fixtures+ given: A fresh runtime directory and a manifest-valid local linux-arm64 archive+ when: The Web install job is started and polled to completion+ then: Cold staging is admitted, the pointer is published, and dependency status becomes ready+ expected_outputs:+ - A succeeded install job+ - A ready optional memory-runtime dependency at the selected version+ - id: MEMORY-RUNTIME-INSTALL-002+ name: Final release bytes and install staging share one bounded cold-admission command+ status: covered+ kind: release_contract+ layer: contract+ test: tests/test_memory_runtime_release.py::test_final_archive_verification_uses_shared_cold_admission+ related_tests:+ - tests/test_memory_artifact_contract.py::test_cold_artifact_admission_is_bounded_and_warms_the_runtime+ - tests/test_memory_artifact_contract.py::test_cold_artifact_admission_classifies_timeout+ - id: MEMORY-RUNTIME-INSTALL-003+ name: Failed preparation remains actionable across processes without retaining staging+ status: covered+ kind: degradation+ layer: contract+ test: tests/test_managed_runtime.py::test_memory_preparation_timeout_reclaims_staging_and_persists_latest_failure+ related_tests:+ - 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+manual_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.diff --git a/tests/scenarios/memory_runtime_install/observations.yaml b/tests/scenarios/memory_runtime_install/observations.yamlnew file mode 100644index 000000000..ddd857075--- /dev/null+++ b/tests/scenarios/memory_runtime_install/observations.yaml@@ -0,0 +1,12 @@+version: 1+capability: memory_runtime_install+observations:+ - id: MEMORY-RUNTIME-INSTALL-OBS-001+ scenarios:+ - MEMORY-RUNTIME-INSTALL-001+ - MEMORY-RUNTIME-INSTALL-002+ observation: Final archive extraction and install staging execute the same bounded full import gate without suppressing bytecode, so release verification measures the path that warms first sidecar startup. The Web-job scenario uses a hermetic manifest-shaped fixture; a normal wheel consuming the real published linux-arm64 manifest and archive remains an explicit Incus check.+ - id: MEMORY-RUNTIME-INSTALL-OBS-002+ scenarios:+ - MEMORY-RUNTIME-INSTALL-003+ observation: 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.diff --git a/tests/scenarios/memory_runtime_install/test_memory_runtime_install_scenarios.py b/tests/scenarios/memory_runtime_install/test_memory_runtime_install_scenarios.pynew file mode 100644index 000000000..d8c3cf4ce--- /dev/null+++ b/tests/scenarios/memory_runtime_install/test_memory_runtime_install_scenarios.py@@ -0,0 +1,186 @@+"""Closed-loop contract evidence for Memory Runtime installation."""++from __future__ import annotations++import hashlib+import io+import json+import tarfile+import time+from pathlib import Path++import yaml++from core import managed_runtime+from core.memory import artifact as memory_artifact+from core.memory.artifact import MemoryArtifactManager+from core.memory.artifact_contract import ColdArtifactAdmissionResult+from tests.ui_server_test_helpers import csrf_headers, save_config+from vibe import api+from vibe.ui_server import app+++def _manifest_shaped_linux_arm64_archive(tmp_path: Path) -> Path:+ binary = b"manifest-shaped-linux-arm64-python"+ archive = tmp_path / "memory-runtime-1.2.3-linux-arm64.tar.gz"+ with tarfile.open(archive, "w:gz") as bundle:+ member = tarfile.TarInfo("bin/python")+ member.mode = 0o755+ member.size = len(binary)+ bundle.addfile(member, io.BytesIO(binary))+ manifest = {+ "schema_version": 1,+ "everos_version": "1.2.3",+ "python_version": "3.12.12",+ "lock_sha256": "e6acc17e4c0969563d380326e90134965af0822259bb4a9adb4d54433e9737fe",+ "lock_id": "uv-lock-sha256:e6acc17e4c0969563d380326e90134965af0822259bb4a9adb4d54433e9737fe",+ "uv_version": "0.9.18",+ "source": "scenario",+ "release_state": "published",+ "provider_root_format": "everos-1.2.3",+ "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",+ }+ },+ }+ manifest_path = tmp_path / "memory-runtime-manifest.json"+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")+ return manifest_path+++def test_released_wheel_and_archive_acceptance_remains_explicit_residual() -> None:+ """Scenario: MEMORY-RUNTIME-INSTALL-001 evidence boundary."""++ catalog = yaml.safe_load(+ Path("tests/scenarios/memory_runtime_install/catalog.yaml").read_text(+ encoding="utf-8"+ )+ )+ scenario = next(+ row for row in catalog["scenarios"] if row["id"] == "MEMORY-RUNTIME-INSTALL-001"+ )++ assert scenario["status"] == "partial"+ assert "normal wheel" in catalog["manual_evidence"][0]+ assert "real published manifest and archive" in catalog["manual_evidence"][0]+++def test_disabled_memory_installs_manifest_shaped_linux_arm64_artifact_through_web_job(+ tmp_path: Path,+ monkeypatch,+ request,+) -> None:+ """Scenario: MEMORY-RUNTIME-INSTALL-001."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe-home"))+ config = save_config(tmp_path)+ assert config.memory.enabled is False+ assert config.memory.legacy_needs_repair is False+ assert config.memory.custom_processing_complete() is False+ manifest_path = _manifest_shaped_linux_arm64_archive(tmp_path)+ monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: "linux-arm64")+ monkeypatch.setattr(memory_artifact, "runtime_platform_tag", lambda: "linux-arm64")+ admitted: list[Path] = []++ def admit(binary: Path) -> ColdArtifactAdmissionResult:+ admitted.append(binary)+ return ColdArtifactAdmissionResult(ok=True, reason=None, duration_ms=41_000)++ monkeypatch.setattr(memory_artifact, "run_cold_artifact_admission", admit)+ manager = MemoryArtifactManager(+ runtime_dir=tmp_path / "avibe-home" / "runtime" / "memory",+ manifest_path=manifest_path,+ provider_root=tmp_path / "avibe-home" / "memory" / "everos-root",+ )+ monkeypatch.setattr(manager, "_admit_error_scrubbers", lambda _binary: None)+ monkeypatch.setattr(manager, "_binary_matches_manifest", lambda _binary, _manifest: True)++ def install() -> dict:+ result = manager.ensure(force=True)+ reason = result.get("reason") if isinstance(result.get("reason"), str) else None+ return {+ "ok": bool(result.get("ok")),+ "message": reason or "installed",+ "output": None,+ "reason": reason,+ "download_error": result.get("download_error"),+ }++ def dependencies() -> dict:+ status = manager.status()+ return {+ "ok": True,+ "deps": [+ {+ "id": "memory-runtime",+ "kind": "runtime",+ "required": False,+ "installed": bool(status.get("installed")),+ "version": status.get("version"),+ "latest_version": status.get("selected_version"),+ "has_update": False,+ "status": "ready" if status.get("installed") else status.get("status"),+ "reason": status.get("reason"),+ "download_error": status.get("download_error"),+ }+ ],+ }++ monkeypatch.setattr(api, "_prepare_memory_runtime_job", install)+ monkeypatch.setattr(api, "dependencies_status", dependencies)+ with api._AGENT_INSTALL_JOB_LOCK:+ api._AGENT_INSTALL_JOBS.clear()+ api._AGENT_INSTALL_LATEST_BY_BACKEND.clear()+ request.addfinalizer(_clear_install_jobs)++ client = app.test_client()+ headers = csrf_headers(client, "http://127.0.0.1:15131")+ before = client.get(+ "/api/dependencies",+ headers=headers,+ base_url="http://127.0.0.1:15131",+ ).get_json()["deps"][0]+ assert before["required"] is False+ assert before["installed"] is False++ started = client.post(+ "/api/dependencies/memory-runtime/install",+ headers=headers,+ base_url="http://127.0.0.1:15131",+ ).get_json()+ deadline = time.monotonic() + 2+ finished = started+ while finished.get("status") == "running" and time.monotonic() < deadline:+ time.sleep(0.01)+ finished = client.get(+ f"/api/dependencies/memory-runtime/install/{started['job_id']}",+ headers=headers,+ base_url="http://127.0.0.1:15131",+ ).get_json()++ assert finished["status"] == "succeeded"+ assert finished["ok"] is True+ assert len(admitted) == 1+ assert admitted[0].parent.parent.name.startswith("install-")+ after = client.get(+ "/api/dependencies",+ headers=headers,+ base_url="http://127.0.0.1:15131",+ ).get_json()["deps"][0]+ assert after["required"] is False+ assert after["status"] == "ready"+ assert after["installed"] is True+ assert after["version"] == "1.2.3"+++def _clear_install_jobs() -> None:+ with api._AGENT_INSTALL_JOB_LOCK:+ api._AGENT_INSTALL_JOBS.clear()+ api._AGENT_INSTALL_LATEST_BY_BACKEND.clear()diff --git a/tests/test_managed_runtime.py b/tests/test_managed_runtime.pyindex 0a3c421fe..87e99937b 100644--- a/tests/test_managed_runtime.py+++ b/tests/test_managed_runtime.py@@ -7,6 +7,7 @@ import jsonimport osimport shutilimport stat+import subprocessimport tarfileimport timefrom pathlib import Path@@ -25,6 +26,7 @@ from core.managed_runtime import ()from core.memory import artifact as memory_artifactfrom core.memory.artifact import MemoryArtifactManager, MemoryRuntimeActivationError+from core.memory.artifact_contract import COLD_ARTIFACT_ADMISSION_TIMEOUT_REASONfrom core.memory.provider_root import ProviderRootErrorfrom vibe.model_hub_runtime.installer import EngineRuntimeManager@@ -944,6 +946,285 @@ def test_memory_selected_contract_failure_preserves_admitted_install(assert manager.resolve_python() == Path(installed["path"])+def test_memory_preparation_timeout_reclaims_staging_and_persists_latest_failure(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest_path = _write_subclass_runtime_fixture(tmp_path, "memory")+ runtime_dir = tmp_path / "memory-runtime"+ manager = _subclass_runtime_manager(+ tmp_path,+ "memory",+ manifest_path,+ monkeypatch,+ runtime_dir=runtime_dir,+ )+ monkeypatch.setattr(+ manager,+ "_prepare_binary",+ lambda _binary, **_kwargs: {+ "ok": False,+ "reason": COLD_ARTIFACT_ADMISSION_TIMEOUT_REASON,+ },+ )++ failed = manager.ensure()++ assert failed["ok"] is False+ assert failed["reason"] == COLD_ARTIFACT_ADMISSION_TIMEOUT_REASON+ assert not any(path.name.startswith("install-") for path in runtime_dir.iterdir())+ failure_path = runtime_dir / "last-install-failure.json"+ assert json.loads(failure_path.read_text(encoding="utf-8")) == {+ "reason": COLD_ARTIFACT_ADMISSION_TIMEOUT_REASON,+ "status": "error",+ }++ restarted = _subclass_runtime_manager(+ tmp_path,+ "memory",+ manifest_path,+ monkeypatch,+ runtime_dir=runtime_dir,+ )+ restarted_status = restarted.status()+ assert restarted_status["installed"] is False+ assert restarted_status["status"] == "error"+ assert restarted_status["reason"] == COLD_ARTIFACT_ADMISSION_TIMEOUT_REASON++ succeeded = restarted.ensure()+ assert succeeded["ok"] is True+ assert failure_path.exists() is False+ assert restarted.status()["reason"] is None+++def test_memory_legacy_pointer_admission_failure_survives_fresh_manager_status(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest_path = _write_subclass_runtime_fixture(tmp_path, "memory")+ runtime_dir = tmp_path / "memory-runtime"+ manager = _subclass_runtime_manager(+ tmp_path,+ "memory",+ manifest_path,+ monkeypatch,+ runtime_dir=runtime_dir,+ )+ assert isinstance(manager, MemoryArtifactManager)+ assert manager.ensure()["ok"] is True+ pointer = manager._active_pointer()+ assert pointer is not None+ pointer.pop("admission_revision")+ pointer.pop("admission_ok")+ manager._restore_current_pointer(pointer)+ monkeypatch.setattr(+ manager,+ "_prepare_binary",+ lambda _binary, **_kwargs: {+ "ok": False,+ "reason": COLD_ARTIFACT_ADMISSION_TIMEOUT_REASON,+ },+ )++ assert manager.resolve_python() is None++ restarted = _subclass_runtime_manager(+ tmp_path,+ "memory",+ manifest_path,+ monkeypatch,+ runtime_dir=runtime_dir,+ )+ restarted_status = restarted.status()+ assert restarted_status["installed"] is False+ assert restarted_status["status"] == "error"+ assert restarted_status["reason"] == COLD_ARTIFACT_ADMISSION_TIMEOUT_REASON++ (Path(pointer["install_dir"]) / pointer["bin_path"]).unlink()+ corrupted_status = restarted.status()+ assert corrupted_status["installed"] is False+ assert corrupted_status["reason"] == "memory_runtime_install_failed"+++def test_memory_scrubber_timeout_keeps_its_preparation_stage_reason(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ manager = MemoryArtifactManager(+ runtime_dir=tmp_path / "runtime",+ manifest_path=tmp_path / "missing.json",+ provider_root=tmp_path / "provider-root",+ )++ def timeout(command, **kwargs):+ raise subprocess.TimeoutExpired(command, kwargs["timeout"])++ monkeypatch.setattr(memory_artifact.subprocess, "run", timeout)++ assert manager._admit_error_scrubbers(tmp_path / "runtime" / "bin" / "python") == (+ "memory_runtime_preparation_scrubber_timeout"+ )+++def test_memory_sync_contract_failure_keeps_its_preparation_stage_reason(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ manager = MemoryArtifactManager(+ runtime_dir=tmp_path / "runtime",+ manifest_path=tmp_path / "missing.json",+ provider_root=tmp_path / "provider-root",+ )+ monkeypatch.setattr(+ memory_artifact,+ "run_cold_artifact_admission",+ lambda _binary: SimpleNamespace(ok=True, reason=None, duration_ms=1),+ )+ monkeypatch.setattr(manager, "_admit_error_scrubbers", lambda _binary: None)+ monkeypatch.setattr(manager, "_admit_sync_contract", lambda _binary, _expected: False)++ result = manager._prepare_binary(+ tmp_path / "runtime" / "bin" / "python",+ sync_contract=(1, ("write",), "a" * 64, "b" * 64),+ )++ assert result == {+ "ok": False,+ "reason": "memory_runtime_preparation_sync_contract_failed",+ }+++ "content",+ [+ b"{",+ b"[]",+ b'{"reason":"memory_runtime_preparation_import_timeout"}',+ b'{"status":"failed","reason":"memory_runtime_preparation_import_timeout"}',+ b'{"status":"error","reason":42}',+ b"x" * (4 * 1024 + 1),+ ],+)+def test_memory_latest_install_failure_safely_ignores_malformed_or_older_state(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ content: bytes,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest_path = _write_subclass_runtime_fixture(tmp_path, "memory")+ runtime_dir = tmp_path / "memory-runtime"+ runtime_dir.mkdir(mode=0o700)+ failure_path = runtime_dir / "last-install-failure.json"+ failure_path.write_bytes(content)+ failure_path.chmod(0o600)+ manager = _subclass_runtime_manager(+ tmp_path,+ "memory",+ manifest_path,+ monkeypatch,+ runtime_dir=runtime_dir,+ )++ status_payload = manager.status()++ assert status_payload["installed"] is False+ assert status_payload["status"] == "missing"+ assert status_payload["reason"] is None+++def test_memory_latest_install_failure_rejects_symlink_state(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest_path = _write_subclass_runtime_fixture(tmp_path, "memory")+ runtime_dir = tmp_path / "memory-runtime"+ runtime_dir.mkdir(mode=0o700)+ outside = tmp_path / "outside.json"+ outside.write_text(+ json.dumps(+ {+ "status": "error",+ "reason": COLD_ARTIFACT_ADMISSION_TIMEOUT_REASON,+ }+ ),+ encoding="utf-8",+ )+ (runtime_dir / "last-install-failure.json").symlink_to(outside)+ manager = _subclass_runtime_manager(+ tmp_path,+ "memory",+ manifest_path,+ monkeypatch,+ runtime_dir=runtime_dir,+ )++ status_payload = manager.status()++ assert status_payload["status"] == "missing"+ assert status_payload["reason"] is None+ assert outside.is_file()+++def test_memory_reuse_clears_latest_install_failure(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest_path = _write_subclass_runtime_fixture(tmp_path, "memory")+ manager = _subclass_runtime_manager(tmp_path, "memory", manifest_path, monkeypatch)+ assert manager.ensure()["ok"] is True+ failure_path = manager.runtime_dir / "last-install-failure.json"+ manager._write_latest_install_failure(COLD_ARTIFACT_ADMISSION_TIMEOUT_REASON)+ assert failure_path.is_file()++ reused = manager.ensure()++ assert reused["ok"] is True+ assert reused["changed"] is False+ assert failure_path.exists() is False+++def test_memory_skipped_install_does_not_persist_terminal_failure(+ tmp_path: Path,+) -> None:+ manager = MemoryArtifactManager(+ runtime_dir=tmp_path / "runtime",+ manifest_path=tmp_path / "missing.json",+ provider_root=tmp_path / "provider-root",+ )++ result = manager._failure(+ manager._reason("install_already_running"),+ skipped=True,+ )++ assert result["skipped"] is True+ assert (manager.runtime_dir / "last-install-failure.json").exists() is False+++def test_memory_install_failure_persistence_bounds_unsafe_reason(+ tmp_path: Path,+) -> None:+ manager = MemoryArtifactManager(+ runtime_dir=tmp_path / "runtime",+ manifest_path=tmp_path / "missing.json",+ provider_root=tmp_path / "provider-root",+ )++ manager._failure("unsafe reason " + "x" * 1024)++ persisted = json.loads(+ (manager.runtime_dir / "last-install-failure.json").read_text(encoding="utf-8")+ )+ assert persisted == {+ "status": "error",+ "reason": "memory_runtime_preparation_failed",+ }++def test_memory_force_pointer_failure_preserves_active_install_and_retry_repairs_contract(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,diff --git a/tests/test_memory_artifact_contract.py b/tests/test_memory_artifact_contract.pynew file mode 100644index 000000000..60fcbf60d--- /dev/null+++ b/tests/test_memory_artifact_contract.py@@ -0,0 +1,64 @@+from __future__ import annotations++import subprocess+from pathlib import Path++from core.memory import artifact_contract+++def test_cold_artifact_admission_is_bounded_and_warms_the_runtime(+ tmp_path: Path,+ monkeypatch,+) -> None:+ binary = tmp_path / "runtime" / "bin" / "python"+ binary.parent.mkdir(parents=True)+ binary.touch()+ captured: dict[str, object] = {}++ def run(command, **kwargs):+ captured["command"] = command+ captured.update(kwargs)+ return subprocess.CompletedProcess(+ command,+ 0,+ stdout=(+ f"{artifact_contract.EVEROS_VERSION}\n"+ f"{artifact_contract.EMBEDDED_PYTHON_VERSION}\n"+ ),+ stderr="",+ )++ monkeypatch.setattr(artifact_contract.subprocess, "run", run)++ result = artifact_contract.run_cold_artifact_admission(binary)++ assert result.ok is True+ assert result.reason is None+ command = captured["command"]+ assert command[:3] == [str(binary), "-I", "-c"]+ assert "-B" not in command+ assert "everos.entrypoints.cli.main" in command[3]+ assert "everos.memory.cascade" in command[3]+ assert "SUPPORTED_EXTENSIONS" in command[3]+ assert captured["cwd"] == binary.parent.parent+ assert captured["timeout"] == artifact_contract.COLD_ARTIFACT_ADMISSION_TIMEOUT_SECONDS+++def test_cold_artifact_admission_classifies_timeout(+ tmp_path: Path,+ monkeypatch,+) -> None:+ binary = tmp_path / "runtime" / "bin" / "python"+ binary.parent.mkdir(parents=True)+ binary.touch()++ def timeout(command, **kwargs):+ raise subprocess.TimeoutExpired(command, kwargs["timeout"])++ monkeypatch.setattr(artifact_contract.subprocess, "run", timeout)++ result = artifact_contract.run_cold_artifact_admission(binary)++ assert result.ok is False+ assert result.reason == artifact_contract.COLD_ARTIFACT_ADMISSION_TIMEOUT_REASON+ assert result.duration_ms >= 0diff --git a/tests/test_memory_runtime_release.py b/tests/test_memory_runtime_release.pyindex ab6e8a574..115c9aedf 100644--- a/tests/test_memory_runtime_release.py+++ b/tests/test_memory_runtime_release.py@@ -13,6 +13,7 @@ from pathlib import Pathimport pytest+from core.memory.artifact_contract import ColdArtifactAdmissionResultfrom scripts import build_memory_runtime as runtime_builderfrom scripts import generate_memory_runtime_manifest as manifest_generatorfrom scripts.build_memory_runtime import (@@ -31,6 +32,19 @@ from scripts.build_memory_runtime import (PLATFORMS = ("darwin-arm64", "linux-arm64", "linux-x64")+def test_release_builder_imports_without_project_dependencies() -> None:+ repo_root = Path(__file__).resolve().parents[1]+ result = subprocess.run(+ [sys.executable, "-S", "scripts/build_memory_runtime.py", "--help"],+ cwd=repo_root,+ capture_output=True,+ text=True,+ check=False,+ )++ assert result.returncode == 0, result.stderr++def test_memory_runtime_release_platform_contract_excludes_darwin_x64() -> None:expected = set(PLATFORMS)@@ -186,6 +200,29 @@ def _write_archive(directory: Path, platform: str) -> tuple[Path, bytes]:return archive, binary+def test_final_archive_verification_uses_shared_cold_admission(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ archive, binary = _write_archive(tmp_path, "linux-arm64")+ observed: list[Path] = []++ def admit(path: Path) -> ColdArtifactAdmissionResult:+ observed.append(path)+ return ColdArtifactAdmissionResult(ok=True, reason=None, duration_ms=41_000)++ monkeypatch.setattr(runtime_builder, "run_cold_artifact_admission", admit)+ monkeypatch.setattr(runtime_builder, "_sidecar_health_smoke", lambda *_args, **_kwargs: None)++ runtime_builder.verify_archive(+ archive,+ binary_sha256=hashlib.sha256(binary).hexdigest(),+ )++ assert len(observed) == 1+ assert observed[0].parts[-2:] == ("bin", "python")++def test_generate_memory_runtime_manifest_records_verified_platform_archives(tmp_path: Path) -> None:expected: dict[str, tuple[Path, bytes]] = {platform: _write_archive(tmp_path, platform) for platform in PLATFORMS@@ -258,6 +295,11 @@ def test_build_outputs_metadata_accepted_by_manifest_generator(return subprocess.CompletedProcess(command, 0, stdout=stdout, stderr="")monkeypatch.setattr(runtime_builder, "_run", fake_run)+ monkeypatch.setattr(+ runtime_builder,+ "run_cold_artifact_admission",+ lambda _binary: ColdArtifactAdmissionResult(ok=True, reason=None, duration_ms=1),+ )monkeypatch.setattr(runtime_builder, "_sidecar_health_smoke", lambda *args, **kwargs: None)for platform in PLATFORMS:diff --git a/ui/src/components/settings/SettingsDependenciesPage.test.tsx b/ui/src/components/settings/SettingsDependenciesPage.test.tsxindex 1a118eb38..fa448f2f2 100644--- a/ui/src/components/settings/SettingsDependenciesPage.test.tsx+++ b/ui/src/components/settings/SettingsDependenciesPage.test.tsx@@ -103,4 +103,39 @@ describe('SettingsDependenciesPage Memory runtime', () => {'listDependencies',]);});++ it('renders a persisted preparation reason on initial page load', async () => {+ api.listDependencies.mockResolvedValue({+ ok: true,+ deps: [dependency({+ installed: false,+ status: 'error',+ version: null,+ reason: 'memory_runtime_preparation_import_timeout',+ })],+ });++ renderPage();++ const failure = await screen.findByRole('alert');+ expect(failure.textContent).toBe('errors.memory_runtime_preparation_import_timeout');+ expect(screen.getByText('settings.dependencies.statusError')).toBeTruthy();+ expect(api.installDependency).not.toHaveBeenCalled();+ });++ it.each([+ 'memory_runtime_preparation_failed',+ 'memory_runtime_preparation_import_timeout',+ 'memory_runtime_preparation_import_failed',+ 'memory_runtime_preparation_scrubber_timeout',+ 'memory_runtime_preparation_scrubber_failed',+ 'memory_runtime_preparation_sync_contract_failed',+ ])('localizes the bounded preparation reason %s', async (reason) => {+ api.installDependency.mockResolvedValue({ ok: false, reason });+ renderPage();++ await userEvent.click(await screen.findByRole('button', { name: 'settings.dependencies.repair' }));++ await waitFor(() => expect(showToast).toHaveBeenCalledWith(`errors.${reason}`, 'error'));+ });});diff --git a/ui/src/components/settings/SettingsDependenciesPage.tsx b/ui/src/components/settings/SettingsDependenciesPage.tsxindex 099a60a8f..8a26ef7e0 100644--- a/ui/src/components/settings/SettingsDependenciesPage.tsx+++ b/ui/src/components/settings/SettingsDependenciesPage.tsx@@ -86,12 +86,18 @@ export const SettingsDependenciesPage: React.FC = () => {// `memory_runtime_unpublished`) rather than human copy. Localize any// token-shaped string through the shared errors namespace so the user never// sees a raw identifier; fall back to a human message or the generic failure.- const localizedFailure = (res: InstallResult): string => {- const token = res.reason || res.message;+ const localizedReason = (token: string | null | undefined, fallback: string): string => {if (typeof token === 'string' && /^[a-z][a-z0-9_]*$/.test(token)) {return t(`errors.${token}`, { defaultValue: t('settings.dependencies.installFailed') });}- return res.message || t('settings.dependencies.installFailed');+ return fallback;+ };++ const localizedFailure = (res: InstallResult): string => {+ return localizedReason(+ res.reason || res.message,+ res.message || t('settings.dependencies.installFailed')+ );};const install = async (dep: DependencyItem) => {@@ -159,6 +165,9 @@ export const SettingsDependenciesPage: React.FC = () => {const sidecarRunning = isMemoryRuntime && memoryRuntimeSidecarRunning(memoryStatus);const repairBlockedBySidecar = isMemoryRuntime && (!memoryStatusLoaded || sidecarRunning);const dependencyOperationBusy = busy !== null;+ const persistedFailure = isMemoryRuntime && d.status === 'error' && d.reason+ ? localizedReason(d.reason, t('settings.dependencies.installFailed'))+ : null;return (<SettingsResourceRowkey={d.id}@@ -216,6 +225,13 @@ export const SettingsDependenciesPage: React.FC = () => {<div className="border-t border-border pt-3 text-[11px] leading-snug text-muted">{t('settings.dependencies.memoryRuntimeDisableBeforeRepair')}</div>+ ) : persistedFailure ? (+ <div+ role="alert"+ className="border-t border-destructive/30 pt-3 text-[11px] leading-snug text-destructive-ink"+ >+ {persistedFailure}+ </div>) : undefined}/>);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 1b5f6c101..221013dbc 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1898,6 +1898,12 @@"memory_runtime_missing": "The memory-runtime dependency isn't installed yet.","memory_runtime_unsupported": "The memory-runtime dependency isn't supported on this platform.","memory_runtime_install_failed": "The memory-runtime dependency failed to install.",+ "memory_runtime_preparation_failed": "The memory runtime failed its local compatibility checks. Retry the install.",+ "memory_runtime_preparation_import_timeout": "The memory runtime's first import check timed out. Retry after checking available CPU and disk I/O.",+ "memory_runtime_preparation_import_failed": "The memory runtime failed its import compatibility check. Retry the install.",+ "memory_runtime_preparation_scrubber_timeout": "The memory runtime's diagnostic safety check timed out. Retry after checking system load.",+ "memory_runtime_preparation_scrubber_failed": "The memory runtime failed its diagnostic safety check. Retry the install.",+ "memory_runtime_preparation_sync_contract_failed": "The memory runtime does not match this Avibe version's sync contract. Reinstall the runtime.","memory_runtime_install_requires_disabled_memory": "Turn Memory off in Settings \u2192 Memory before repairing a running Memory runtime.","memory_reconcile_failed": "Avibe couldn't apply the Memory settings. Check the runtime logs for the failing step.","memory_sidecar_unavailable": "The Memory sidecar isn't reachable right now.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex b0144392b..023594aa0 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1898,6 +1898,12 @@"memory_runtime_missing": "memory-runtime 依赖尚未安装。","memory_runtime_unsupported": "memory-runtime 依赖在此平台上不受支持。","memory_runtime_install_failed": "memory-runtime 依赖安装失败。",+ "memory_runtime_preparation_failed": "记忆运行时未通过本地兼容性检查,请重试安装。",+ "memory_runtime_preparation_import_timeout": "记忆运行时的首次导入检查超时。请检查可用 CPU 和磁盘 I/O 后重试。",+ "memory_runtime_preparation_import_failed": "记忆运行时未通过导入兼容性检查,请重试安装。",+ "memory_runtime_preparation_scrubber_timeout": "记忆运行时的诊断安全检查超时。请检查系统负载后重试。",+ "memory_runtime_preparation_scrubber_failed": "记忆运行时未通过诊断安全检查,请重试安装。",+ "memory_runtime_preparation_sync_contract_failed": "记忆运行时与当前 Avibe 版本的同步契约不匹配,请重新安装运行时。","memory_runtime_install_requires_disabled_memory": "记忆运行时正在使用中。请先在「设置 → 记忆」中关闭记忆,再修复。","memory_reconcile_failed": "Avibe 无法应用记忆设置。请查看运行时日志了解失败步骤。","memory_sidecar_unavailable": "记忆 sidecar 当前不可访问。",