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(runtime): make managed install state disk-truthful (#1666)
Call White85fa9439d56b
diff --git a/core/managed_runtime.py b/core/managed_runtime.pyindex cc726e161..3b5e030fe 100644--- a/core/managed_runtime.py+++ b/core/managed_runtime.py@@ -126,7 +126,7 @@ class ManagedRuntimeManager:offline: bool = False,) -> None:self.spec = spec- self.runtime_dir = runtime_dir+ self.runtime_dir = runtime_dir.expanduser().absolute()self.manifest_path = Path(manifest_path).expanduser() if manifest_path else Noneself.manifest_url = manifest_urlself.offline = offline@@ -166,7 +166,7 @@ class ManagedRuntimeManager:manifest=manifest,)target = self._install_target_identity(manifest, archive)- if expected_target is not None and dict(expected_target) != target:+ if expected_target is not None and self._normalized_install_target(expected_target) != target:return self._failure(self._reason("install_target_changed"),manifest=manifest,@@ -188,16 +188,21 @@ class ManagedRuntimeManager:)install_dir = self._manifest_install_dir(manifest, archive)- existing = self._verified_manifest_binary(install_dir, manifest, archive)+ current_install_dir = self._current_install_dir(self.runtime_dir / "versions")+ existing_install_dir = current_install_dir or install_dir+ existing = self._verified_manifest_binary(existing_install_dir, manifest, archive)+ if existing is None and existing_install_dir != install_dir:+ existing_install_dir = install_dir+ existing = self._verified_manifest_binary(install_dir, manifest, archive)if existing is not None and not force:- return self._reuse_existing_install(existing, install_dir, manifest, archive)+ return self._reuse_existing_install(existing, existing_install_dir, manifest, archive)archive_path = self._resolve_manifest_archive(archive)if archive_path is None:if existing is not None:return self._reuse_existing_install(existing,- install_dir,+ existing_install_dir,manifest,archive,reason=self._install_reason,@@ -210,6 +215,7 @@ class ManagedRuntimeManager:self.runtime_dir.mkdir(parents=True, exist_ok=True)staging_dir = Path(tempfile.mkdtemp(prefix="install-", dir=self.runtime_dir))+ candidate_install_dir: Path | None = Nonetry:with tarfile.open(archive_path, "r:gz") as archive_file:safe_extract_tar(archive_file, staging_dir)@@ -242,10 +248,15 @@ class ManagedRuntimeManager:archive=archive,)- if install_dir.exists():- shutil.rmtree(install_dir)install_dir.parent.mkdir(parents=True, exist_ok=True)+ if install_dir.exists():+ replacement = Path(+ tempfile.mkdtemp(prefix=f"{install_dir.name}-", dir=install_dir.parent)+ )+ replacement.rmdir()+ install_dir = replacementshutil.move(str(staging_dir), str(install_dir))+ candidate_install_dir = install_dirinstalled_binary = install_dir / archive.bin_pathself._write_manifest_install_metadata(install_dir,@@ -254,6 +265,7 @@ class ManagedRuntimeManager:binary_sha256=binary_sha256,)self._write_current_pointer(install_dir, manifest, archive)+ candidate_install_dir = Noneself._install_reason = Nonereturn {**self._success_payload(@@ -266,6 +278,8 @@ class ManagedRuntimeManager:"preparation": preparation,}except Exception as exc: # noqa: BLE001+ if candidate_install_dir is not None:+ shutil.rmtree(candidate_install_dir, ignore_errors=True)logger.exception("Failed to install managed %s runtime", self.spec.runtime_id)return self._failure(self._reason("install_failed"),@@ -282,40 +296,148 @@ class ManagedRuntimeManager:def resolve_binary(self) -> Path | None:"""Resolve an already installed runtime without performing network I/O."""+ inspection_reason = f"{self.spec.runtime_id}_install_inspection_failed"try:- manifest = self._load_manifest(allow_network=False)- if manifest is None or not self._manifest_installable(manifest):+ pointer = json.loads((self.runtime_dir / "current.json").read_text(encoding="utf-8"))+ except FileNotFoundError:+ return None+ except (OSError, RecursionError, UnicodeError, ValueError):+ self._install_reason = inspection_reason+ return None++ self._install_reason = inspection_reason+ try:+ if not isinstance(pointer, dict):return None- archive = self._manifest_archive_for_platform(manifest)- if archive is None:+ runtime_version = pointer.get("runtime_version")+ platform_tag = pointer.get("platform")+ install_dir_value = pointer.get("install_dir")+ bin_path = pointer.get("bin_path", self.spec.default_bin_path)+ digest_fields = ("manifest_sha256", "archive_sha256")+ aliases = dict(self.spec.platform_aliases)+ host_platform = aliases.get(runtime_platform_tag(), runtime_platform_tag())+ installed_platform = aliases.get(platform_tag, platform_tag) if isinstance(platform_tag, str) else None+ if (+ pointer.get("provider") != "manifest"+ or pointer.get("runtime_id") != self.spec.runtime_id+ or not _safe_metadata_value(runtime_version)+ or not _safe_metadata_value(platform_tag)+ or installed_platform != host_platform+ or not isinstance(install_dir_value, str)+ or not isinstance(bin_path, str)+ or archive_path_is_unsafe(bin_path)+ or any(+ not _SHA256_RE.fullmatch(str(pointer.get(field) or ""))+ for field in digest_fields+ )+ ):return None- return self._verified_manifest_binary(- self._manifest_install_dir(manifest, archive),- manifest,- archive,- )- except Exception: # noqa: BLE001++ configured_install_dir = Path(install_dir_value)+ if not configured_install_dir.is_absolute():+ return None+ install_dir = configured_install_dir.resolve(strict=True)+ versions_dir = (self.runtime_dir / "versions").resolve(strict=True)+ binary = (install_dir / bin_path).resolve(strict=True)+ if (+ install_dir == versions_dir+ or versions_dir not in install_dir.parents+ or install_dir not in binary.parents+ ):+ return None++ metadata = json.loads((install_dir / self.spec.metadata_filename).read_text(encoding="utf-8"))+ if not isinstance(metadata, dict):+ return None+ metadata_platform = metadata.get("platform")+ metadata_bin_path = metadata.get("bin_path", self.spec.default_bin_path)+ binary_sha256 = metadata.get("binary_sha256")+ if not (+ metadata.get("provider") == "manifest"+ and metadata.get("runtime_id") == self.spec.runtime_id+ and metadata.get("runtime_version") == runtime_version+ and isinstance(metadata_platform, str)+ and aliases.get(metadata_platform, metadata_platform) == installed_platform+ and all(metadata.get(field) == pointer.get(field) for field in digest_fields)+ and metadata_bin_path == bin_path+ and isinstance(binary_sha256, str)+ and _SHA256_RE.fullmatch(binary_sha256)+ and binary.is_file()+ and os.access(binary, os.X_OK)+ ):+ return None++ manifest = self._load_manifest(allow_network=False)+ selected_is_installed = False+ if manifest is not None and self._manifest_installable(manifest):+ archive = self._manifest_archive_for_platform(manifest)+ selected_is_installed = archive is not None and (+ runtime_version,+ installed_platform,+ pointer.get(digest_fields[1]),+ ) == (+ manifest.runtime_version,+ aliases.get(archive.platform, archive.platform),+ archive.sha256,+ )+ if selected_is_installed:+ if self._verified_manifest_binary(install_dir, manifest, archive) != binary:+ self._install_reason = inspection_reason+ return None+ elif file_sha256(binary) != binary_sha256:+ self._install_reason = inspection_reason+ return None+ self._install_reason = None+ return binary+ except (OSError, RecursionError, RuntimeError, UnicodeError, ValueError):+ self._install_reason = inspection_reasonlogger.debug("Failed to resolve managed %s runtime", self.spec.runtime_id, exc_info=True)return Nonedef status(self) -> dict[str, Any]:manifest = self._load_manifest(allow_network=False)- platform_tag = runtime_platform_tag()archive = self._manifest_archive_for_platform(manifest) if manifest else None- install_dir = self._manifest_install_dir(manifest, archive) if manifest and archive else None- binary = self.resolve_binary() if manifest and archive else None+ pointer_path = self.runtime_dir / "current.json"+ pointer: dict[str, Any] = {}+ binary: Path | None = None+ for _attempt in range(2):+ try:+ before = json.loads(pointer_path.read_text(encoding="utf-8"))+ except (OSError, RecursionError, UnicodeError, ValueError):+ before = {}+ if not isinstance(before, dict):+ before = {}+ binary = self.resolve_binary()+ try:+ after = json.loads(pointer_path.read_text(encoding="utf-8"))+ except (OSError, RecursionError, UnicodeError, ValueError):+ after = {}+ if not isinstance(after, dict):+ after = {}+ if before == after:+ pointer = before+ break+ else:+ binary = None+ self._install_reason = self._reason("install_inspection_failed")+ matches_manifest = False if binary is not None and manifest and archive else None+ if matches_manifest is not None and isinstance(pointer.get("install_dir"), str):+ with contextlib.suppress(Exception): # noqa: BLE001+ matches_manifest = self._verified_manifest_binary(Path(pointer["install_dir"]), manifest, archive) == binaryreturn {"id": self.spec.runtime_id,"provider": "manifest",- "platform": platform_tag,+ "platform": runtime_platform_tag(),"installed": binary is not None,- "version": manifest.runtime_version if manifest else None,- "status": "ready" if binary else "missing",+ "version": pointer.get("runtime_version") if binary is not None else None,+ "selected_version": manifest.runtime_version if manifest else None,+ "matches_manifest": matches_manifest,+ "status": "ready" if binary else "error" if str(self._install_reason or "").endswith("install_inspection_failed") else "missing","path": str(binary) if binary else None,- "install_dir": str(install_dir) if install_dir 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": self._install_reason,+ "reason": self._install_reason if binary is None else None,"download_error": self._download_error,}@@ -752,7 +874,7 @@ class ManagedRuntimeManager:else:raise ValueError("invalid archive collection")for platform_tag, item in archive_entries:- if not isinstance(platform_tag, str) or not isinstance(item, dict):+ if not _safe_metadata_value(platform_tag) or not isinstance(item, dict):raise ValueError("invalid archive entry")url = str(item["url"])name = str(item.get("name") or Path(urllib.parse.urlparse(url).path).name)@@ -780,9 +902,12 @@ class ManagedRuntimeManager:size=size,bin_path=bin_path,)+ runtime_version = str(data.get(self.spec.version_field) or "")+ if not _safe_metadata_value(runtime_version):+ raise ValueError("invalid runtime version")manifest = ManagedRuntimeManifest(schema_version=int(data.get("schema_version")),- runtime_version=str(data.get(self.spec.version_field) or ""),+ runtime_version=runtime_version,source=str(data.get("source") or ""),source_url=str(data.get("source_url") or "") or None,archives=archives,@@ -862,7 +987,7 @@ class ManagedRuntimeManager:manifest: ManagedRuntimeManifest,archive: ManagedRuntimeArchive,) -> Path:- fingerprint = hashlib.sha256(f"{manifest.digest}:{archive.sha256}".encode()).hexdigest()[:16]+ fingerprint = hashlib.sha256(f"{manifest.runtime_version}:{archive.platform}:{archive.sha256}".encode()).hexdigest()[:16]return (self.runtime_dir/ "versions"@@ -877,35 +1002,44 @@ class ManagedRuntimeManager:archive: ManagedRuntimeArchive,) -> dict[str, str]:return {- "manifest_sha256": manifest.digest,"runtime_version": manifest.runtime_version,"platform": archive.platform,"archive_sha256": archive.sha256,"binary_sha256": archive.binary_sha256,}+ @staticmethod+ def _normalized_install_target(target: Mapping[str, str]) -> dict[str, str]:+ return {key: value for key, value in target.items() if key != "manifest_sha256"}+def _verified_manifest_binary(self,install_dir: Path,manifest: ManagedRuntimeManifest,archive: ManagedRuntimeArchive,) -> Path | None:- binary = install_dir / archive.bin_path- if not binary.is_file() or not os.access(binary, os.X_OK):- return Nonetry:metadata = json.loads((install_dir / self.spec.metadata_filename).read_text(encoding="utf-8"))except Exception: # noqa: BLE001return None+ bin_path = metadata.get("bin_path", self.spec.default_bin_path)+ if not isinstance(bin_path, str) or archive_path_is_unsafe(bin_path):+ return None+ binary = install_dir / bin_path+ if not binary.is_file() or not os.access(binary, os.X_OK):+ return None+ target = self._install_target_identity(manifest, archive)+ target_platform = target.pop("platform")+ metadata_platform = metadata.get("platform")+ aliases = dict(self.spec.platform_aliases)if not (metadata.get("provider") == "manifest"and metadata.get("runtime_id") == self.spec.runtime_id- and metadata.get("manifest_sha256") == manifest.digest- and metadata.get("runtime_version") == manifest.runtime_version- and metadata.get("platform") == archive.platform- and metadata.get("archive_sha256") == archive.sha256- and metadata.get("bin_path") == archive.bin_path- and metadata.get("binary_sha256") == archive.binary_sha256+ and all(metadata.get(key) == value for key, value in target.items())+ and isinstance(metadata_platform, str)+ and aliases.get(metadata_platform, metadata_platform)+ == aliases.get(target_platform, target_platform)+ and bin_path == archive.bin_pathand file_sha256(binary) == archive.binary_sha256):return None@@ -942,6 +1076,14 @@ class ManagedRuntimeManager:manifest: ManagedRuntimeManifest,archive: ManagedRuntimeArchive,) -> None:+ manifest_sha256 = manifest.digest+ try:+ metadata = json.loads((install_dir / self.spec.metadata_filename).read_text(encoding="utf-8"))+ persisted_digest = metadata.get("manifest_sha256") if isinstance(metadata, dict) else None+ if isinstance(persisted_digest, str) and _SHA256_RE.fullmatch(persisted_digest):+ manifest_sha256 = persisted_digest+ except (OSError, RecursionError, UnicodeError, ValueError):+ passwrite_json_atomic(self.runtime_dir / "current.json",{@@ -950,7 +1092,7 @@ class ManagedRuntimeManager:"runtime_version": manifest.runtime_version,"platform": archive.platform,"install_dir": str(install_dir),- "manifest_sha256": manifest.digest,+ "manifest_sha256": manifest_sha256,"archive_sha256": archive.sha256,"bin_path": archive.bin_path,},@@ -1008,16 +1150,17 @@ class ManagedRuntimeManager:*,reason: str | None = None,) -> dict[str, Any]:- try:- self._write_current_pointer(install_dir, manifest, archive)- except Exception as exc: # noqa: BLE001- logger.exception("Failed to refresh managed %s runtime pointer", self.spec.runtime_id)- return self._failure(- self._reason("pointer_write_failed"),- manifest=manifest,- archive=archive,- message=str(exc),- )+ if self.resolve_binary() != binary:+ try:+ self._write_current_pointer(install_dir, manifest, archive)+ except Exception as exc: # noqa: BLE001+ logger.exception("Failed to refresh managed %s runtime pointer", self.spec.runtime_id)+ return self._failure(+ self._reason("pointer_write_failed"),+ manifest=manifest,+ archive=archive,+ message=str(exc),+ )payload = self._success_payload(binary, install_dir, manifest, archive, changed=False)if reason:payload["reason"] = reason@@ -1173,6 +1316,18 @@ def safe_path_part(value: str) -> str:return cleaned.strip(".-") or "unknown"+def _safe_metadata_value(value: object) -> bool:+ return (+ isinstance(value, str)+ and bool(value)+ and len(value.encode("utf-8")) <= 128+ and all(+ character.isascii() and (character.isalnum() or character in {".", "-", "_", "+"})+ for character in value+ )+ )++def env_flag_enabled(name: str, *, default: bool = False) -> bool:value = os.environ.get(name)if value is None:diff --git a/core/memory/artifact.py b/core/memory/artifact.pyindex edbb87d76..904d17a1e 100644--- a/core/memory/artifact.py+++ b/core/memory/artifact.py@@ -21,14 +21,15 @@ from typing import Any, Protocol, runtime_checkablefrom config import pathsfrom core.managed_runtime import (+ _safe_metadata_value,ManagedRuntimeArchive,ManagedRuntimeManager,ManagedRuntimeManifest,ManagedRuntimeSpec,- archive_path_is_unsafe,env_flag_enabled,file_sha256,runtime_platform_tag,+ write_json_atomic,)from core.process_isolation import isolated_subprocess_kwargsfrom core.memory.confined_filesystem import (@@ -178,33 +179,79 @@ class MemoryArtifactManager(ManagedRuntimeManager):return Nonedef status(self) -> dict[str, Any]:- """Keep the manifest's release-state reason visible to Dependencies."""+ """Report the active pointer without running compatibility probes."""if self._dev_runtime_configured():return self._dev_runtime_status(self._dev_runtime_python())- pointer, pointer_invalid = self._read_active_pointer()- if pointer is not None and self._admitted_active_pointer_binary(pointer) is None:- pointer_invalid = True- status_payload = super().status()- if pointer_invalid:- status_payload.update(- {- "installed": False,- "status": "error",- "path": None,- "reason": "memory_runtime_install_failed",- }- )- return status_payload- if status_payload.get("reason") is not None:- return status_payload+ self._install_reason = None+ manifest = self._load_manifest(allow_network=False)+ if manifest is not None:+ self._manifest_installable(manifest)+ archive = self._manifest_archive_for_platform(manifest) if manifest else None+ pointer, invalid = self._read_active_pointer()try:- manifest = self._load_manifest(allow_network=False)- if manifest is not None and not self._manifest_installable(manifest):- status_payload["reason"] = self._install_reason- except Exception: # noqa: BLE001- status_payload["reason"] = "memory_runtime_install_failed"- return status_payload+ binary = self._verified_active_pointer_binary(pointer) if pointer is not None else None+ except OSError:+ binary = None+ invalid = True+ if (+ pointer is not None+ and pointer.get("admission_revision") == ARTIFACT_ADMISSION_REVISION+ and pointer.get("admission_ok") is not True+ ):+ binary = None+ invalid = True+ invalid = invalid or (pointer is not None and binary is None)+ selected_version = manifest.runtime_version if manifest is not None else None+ matches_manifest = None+ if binary is not None and manifest is not None and archive is not None:+ try:+ matches_manifest = (+ self._verified_manifest_binary(+ Path(pointer["install_dir"]), manifest, archive+ )+ == binary+ )+ except OSError:+ binary = None+ invalid = True+ if matches_manifest:+ try:+ candidate = self._candidate_from_manifest(manifest)+ compatible_formats = pointer.get("compatible_provider_root_formats")+ matches_manifest = (+ pointer.get("provider_root_format") == candidate.provider_root_format+ and isinstance(compatible_formats, list)+ and all(_safe_metadata_value(value) for value in compatible_formats)+ and frozenset(+ {+ pointer.get("provider_root_format"),+ *compatible_formats,+ }+ )+ == candidate.compatible_provider_root_formats+ and _sync_contract_from_payload(pointer)+ == _sync_contract_from_payload(manifest.payload)+ )+ except (MemoryRuntimeActivationError, ValueError):+ matches_manifest = False+ installed_version = pointer.get("runtime_version") if binary is not None else None+ return {+ "id": self.spec.runtime_id,+ "provider": "manifest",+ "platform": runtime_platform_tag(),+ "installed": binary is not None,+ "version": installed_version,+ "selected_version": selected_version,+ "matches_manifest": matches_manifest,+ "status": "ready" if binary is not None else ("error" if invalid 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),+ "download_error": self._download_error,+ }def provider_root_format(self) -> str | None:if self._dev_runtime_configured():@@ -389,8 +436,6 @@ class MemoryArtifactManager(ManagedRuntimeManager):binary: Path,manifest: ManagedRuntimeManifest,) -> dict[str, Any]:- """Admit fresh archives against the sync contract they advertise."""-return self._prepare_binary(binary,sync_contract=_sync_contract_from_payload(manifest.payload),@@ -405,47 +450,69 @@ class MemoryArtifactManager(ManagedRuntimeManager):*,reason: str | None = None,) -> dict[str, Any]:- """Re-admit an existing install before activating it under this contract."""+ """Re-admit and atomically activate an existing Memory runtime contract."""try:sync_contract = _sync_contract_from_payload(manifest.payload)- preparation = (- self._prepare_binary(binary)- if sync_contract is None- else self._prepare_binary(binary, sync_contract=sync_contract)- )- admission_ok = preparation.get("ok") is True+ preparation = self._prepare_binary(binary, sync_contract=sync_contract)except Exception: # noqa: BLE001logger.exception("Failed to admit existing Memory runtime binary")- admission_ok = False- if not admission_ok:- try:- self._persist_active_pointer_admission(binary, admitted=False)- except Exception: # noqa: BLE001- logger.exception("Failed to persist rejected Memory runtime admission")+ preparation = {"ok": False}+ if preparation.get("ok") is not True:return self._failure("memory_runtime_install_failed",manifest=manifest,archive=archive,)- return super()._reuse_existing_install(- binary,- install_dir,- manifest,- archive,- reason=reason,- )- def _persist_active_pointer_admission(self, binary: Path, *, admitted: bool) -> None:+ candidate = self._candidate_from_manifest(manifest)current, invalid = self._read_active_pointer()- if invalid or current is None:- return- if self._verified_active_pointer_binary(current) != binary:- return- admitted_pointer = dict(current)- admitted_pointer["admission_revision"] = ARTIFACT_ADMISSION_REVISION- admitted_pointer["admission_ok"] = admitted- self._restore_current_pointer(admitted_pointer)+ current_binary = (+ self._verified_active_pointer_binary(current)+ if not invalid and current is not None+ else None+ )+ current_contract = None+ if current is not None:+ try:+ current_contract = _sync_contract_from_payload(current)+ except ValueError:+ pass+ pointer_is_current = (+ current is not None+ and current_binary == binary+ and current.get("admission_revision") == ARTIFACT_ADMISSION_REVISION+ and current.get("admission_ok") is True+ and current.get("provider_root_format") == candidate.provider_root_format+ and isinstance(current.get("compatible_provider_root_formats"), list)+ and all(+ _safe_metadata_value(value)+ for value in current["compatible_provider_root_formats"]+ )+ and frozenset(+ {+ current.get("provider_root_format"),+ *current["compatible_provider_root_formats"],+ }+ )+ == candidate.compatible_provider_root_formats+ and current_contract == sync_contract+ )+ if not pointer_is_current:+ try:+ self._write_current_pointer(install_dir, manifest, archive)+ except Exception as exc: # noqa: BLE001+ logger.exception("Failed to refresh Memory runtime pointer")+ return self._failure(+ self._reason("pointer_write_failed"),+ manifest=manifest,+ archive=archive,+ message=str(exc),+ )+ payload = self._success_payload(binary, install_dir, manifest, archive, changed=False)+ if reason:+ payload["reason"] = reason+ return payloaddef _write_current_pointer(self,@@ -467,11 +534,24 @@ class MemoryArtifactManager(ManagedRuntimeManager):raise MemoryRuntimeActivationError(str(error)) from errorroot_state = Noneprevious_pointer = self._active_pointer()+ metadata_path = install_dir / self.spec.metadata_filename+ try:+ previous_metadata = json.loads(metadata_path.read_text(encoding="utf-8"))+ except (OSError, UnicodeError, ValueError):+ previous_metadata = Nonedef commit() -> None:+ self._write_manifest_install_metadata(+ install_dir,+ manifest,+ archive,+ binary_sha256=archive.binary_sha256,+ )self._write_memory_current_pointer(install_dir, manifest, archive, candidate)def rollback() -> None:+ if previous_metadata is not None:+ write_json_atomic(metadata_path, previous_metadata)self._restore_current_pointer(previous_pointer)coordinator = self._activation_coordinator@@ -538,20 +618,15 @@ class MemoryArtifactManager(ManagedRuntimeManager):return None, Truetry:pointer = json.loads(payload.decode("utf-8"))- except (UnicodeError, ValueError):+ except (RecursionError, UnicodeError, ValueError):return None, Truereturn (pointer, False) if isinstance(pointer, dict) else (None, True)def _verified_active_pointer_binary(self, pointer: dict[str, Any]) -> Path | None:- """Verify the binary referenced by ``current.json`` without a manifest lookup."""+ """Apply Memory's build pin around shared installed-binary verification."""- install_dir_value = pointer.get("install_dir")- bin_path = pointer.get("bin_path")if (- pointer.get("provider") != "manifest"- or pointer.get("runtime_id") != self.spec.runtime_id- or not _safe_metadata_value(pointer.get("runtime_version"))- or not _safe_metadata_value(pointer.get("platform"))+ not _safe_metadata_value(pointer.get("runtime_version"))# Well-formed is not the same as usable here. Installation rejects a# manifest whose runtime_version is not EVEROS_VERSION, but the# pointer outlives that check: a ``~/.avibe`` copied between@@ -560,49 +635,12 @@ class MemoryArtifactManager(ManagedRuntimeManager):# Accepting it makes ``resolve_python`` hand back that binary and# Dependencies report ready until the sidecar or processing probe# fails much later, with a far less obvious error.- or pointer.get("platform") != runtime_platform_tag()or pointer.get("runtime_version") != EVEROS_VERSION- or not _valid_sha256(pointer.get("manifest_sha256"))- or not _valid_sha256(pointer.get("archive_sha256"))- or not isinstance(install_dir_value, str)- or not isinstance(bin_path, str)- or archive_path_is_unsafe(bin_path)):return None-- configured_install_dir = Path(install_dir_value)- if not configured_install_dir.is_absolute():- return None- try:- install_dir = configured_install_dir.resolve(strict=True)- versions_dir = (self.runtime_dir / "versions").resolve(strict=True)- binary = (install_dir / bin_path).resolve(strict=True)- except OSError:- return None- if install_dir == versions_dir or versions_dir not in install_dir.parents or install_dir not in binary.parents:- return None- if not binary.is_file() or not os.access(binary, os.X_OK):- return None-- try:- metadata = json.loads((install_dir / self.spec.metadata_filename).read_text(encoding="utf-8"))- except (OSError, UnicodeError, ValueError):- return None- binary_sha256 = metadata.get("binary_sha256") if isinstance(metadata, dict) else None- if not (- isinstance(metadata, dict)- and metadata.get("provider") == "manifest"- and metadata.get("runtime_id") == self.spec.runtime_id- and metadata.get("runtime_version") == pointer["runtime_version"]- and metadata.get("platform") == pointer["platform"]- and metadata.get("manifest_sha256") == pointer["manifest_sha256"]- and metadata.get("archive_sha256") == pointer["archive_sha256"]- and metadata.get("bin_path") == bin_path- and _valid_sha256(binary_sha256)- and file_sha256(binary) == binary_sha256- ):- return None- return binary+ binary = super().resolve_binary()+ current, invalid = self._read_active_pointer()+ return binary if binary is not None and not invalid and current == pointer else Nonedef _admitted_active_pointer_binary(self,@@ -640,11 +678,7 @@ class MemoryArtifactManager(ManagedRuntimeManager):self._install_reason = "memory_runtime_install_failed"return Nonesync_contract = _sync_contract_from_payload(current)- preparation = (- self._prepare_binary(binary)- if sync_contract is None- else self._prepare_binary(binary, sync_contract=sync_contract)- )+ preparation = self._prepare_binary(binary, sync_contract=sync_contract)admission_ok = preparation.get("ok") is Trueadmitted_pointer = dict(current)admitted_pointer["admission_revision"] = ARTIFACT_ADMISSION_REVISION@@ -950,15 +984,6 @@ def set_memory_artifact_manager_for_tests(manager: MemoryArtifactManager | None)_manager = manager-def _safe_metadata_value(value: object) -> bool:- return (- isinstance(value, str)- and bool(value)- and len(value.encode("utf-8")) <= 128- and all(character.isascii() and (character.isalnum() or character in {".", "-", "_"}) for character in value)- )--def _sync_contract_from_payload(payload: Mapping[str, Any],) -> tuple[int, tuple[str, ...], str, str] | None:diff --git a/tests/fixtures/memory/released_active_pointer.json b/tests/fixtures/memory/released_active_pointer.jsonnew file mode 100644index 000000000..7daf02337--- /dev/null+++ b/tests/fixtures/memory/released_active_pointer.json@@ -0,0 +1,13 @@+{+ "provider": "manifest",+ "runtime_id": "memory-runtime",+ "runtime_version": "1.2.3",+ "platform": "__PLATFORM__",+ "install_dir": "__INSTALL_DIR__",+ "manifest_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "archive_sha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",+ "bin_path": "bin/python",+ "provider_root_format": "everos-1.2.3",+ "compatible_provider_root_formats": [],+ "artifact_fingerprint": "released-artifact"+}diff --git a/tests/fixtures/model_hub/released_install_claims.json b/tests/fixtures/model_hub/released_install_claims.jsonnew file mode 100644index 000000000..24e9a1139--- /dev/null+++ b/tests/fixtures/model_hub/released_install_claims.json@@ -0,0 +1,30 @@+{+ "claims": [+ {+ "schema_version": 1,+ "state": "installing",+ "generation": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "error_key": null,+ "target": {+ "manifest_sha256": "1111111111111111111111111111111111111111111111111111111111111111",+ "runtime_version": "v7.2.95",+ "platform": "fixture-platform",+ "archive_sha256": "2222222222222222222222222222222222222222222222222222222222222222",+ "binary_sha256": "3333333333333333333333333333333333333333333333333333333333333333"+ }+ },+ {+ "schema_version": 2,+ "state": "installing",+ "generation": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "error_key": null,+ "target": {+ "manifest_sha256": "1111111111111111111111111111111111111111111111111111111111111111",+ "runtime_version": "v7.2.95",+ "platform": "fixture-platform",+ "archive_sha256": "2222222222222222222222222222222222222222222222222222222222222222",+ "binary_sha256": "3333333333333333333333333333333333333333333333333333333333333333"+ }+ }+ ]+}diff --git a/tests/test_git_runtime.py b/tests/test_git_runtime.pyindex d21bf1033..96d7fb6cf 100644--- a/tests/test_git_runtime.py+++ b/tests/test_git_runtime.py@@ -74,7 +74,8 @@ def test_manifest_parses_and_exposes_archive(tmp_path: Path, monkeypatch: pyteststatus = GitRuntimeManager(manifest_path=manifest).status()- assert status["version"] == "2.55.0"+ assert status["version"] is None+ assert status["selected_version"] == "2.55.0"assert status["manifest"]["git_version"] == "2.55.0"assert status["archive"]["sha256"] == hashlib.sha256(archive.read_bytes()).hexdigest()assert status["archive"]["binary_sha256"] == json.loads(manifest.read_text(encoding="utf-8"))[@@ -351,9 +352,9 @@ def test_clean_preserves_current_install_and_removes_stale_version(first = manager.ensure()assert first["ok"] is True- payload = json.loads(manifest.read_text(encoding="utf-8"))- payload["build_revision"] = 2- manifest.write_text(json.dumps(payload), encoding="utf-8")+ second_archive = _write_git_archive(tmp_path / "second", version="2.56.0")+ second_manifest = _write_manifest(tmp_path / "second", second_archive, version="2.56.0")+ manager.manifest_path = second_manifestsecond = manager.ensure()assert second["ok"] is Trueassert second["install_dir"] != first["install_dir"]@@ -402,7 +403,11 @@ def test_offline_manifest_upgrade_fails_closed_instead_of_trusting_previous_instnext_manifest = _write_manifest(tmp_path / "next", next_archive, version="2.56.0")upgraded = GitRuntimeManager(manifest_path=next_manifest, offline=True)- assert upgraded.resolve_git_path() is None+ assert upgraded.resolve_git_path() == Path(first["path"])+ status = upgraded.status()+ assert status["version"] == "2.55.0"+ assert status["selected_version"] == "2.56.0"+ assert status["matches_manifest"] is Falseresult = upgraded.ensure()assert result["ok"] is Falseassert result["reason"] == "git_archive_unavailable_offline"diff --git a/tests/test_local_deps.py b/tests/test_local_deps.pyindex 8032090be..d5cc5851e 100644--- a/tests/test_local_deps.py+++ b/tests/test_local_deps.py@@ -1186,6 +1186,9 @@ def test_dependencies_status_shape(monkeypatch):def status(self):return {"installed": False,+ "version": None,+ "selected_version": "1.2.3",+ "matches_manifest": None,"status": "missing","manifest": {"everos_version": "1.2.3", "release_state": "unavailable"},"reason": "memory_runtime_unpublished",@@ -1209,7 +1212,9 @@ def test_dependencies_status_shape(monkeypatch):"kind": "runtime","required": True,"installed": False,- "version": "1.2.3",+ "version": None,+ "latest_version": "1.2.3",+ "has_update": False,"status": "missing","reason": "memory_runtime_unpublished","release_state": "unavailable",diff --git a/tests/test_managed_runtime.py b/tests/test_managed_runtime.pyindex 3e2013a88..3f596deb0 100644--- a/tests/test_managed_runtime.py+++ b/tests/test_managed_runtime.py@@ -5,6 +5,7 @@ import hashlibimport ioimport jsonimport os+import shutilimport tarfilefrom pathlib import Path@@ -12,8 +13,14 @@ import pytestfrom core import managed_runtimefrom core.git_runtime import GitRuntimeManager-from core.managed_runtime import ManagedRuntimeManager, ManagedRuntimeSpec-from core.memory.artifact import MemoryArtifactManager+from core.managed_runtime import (+ ManagedRuntimeArchive,+ ManagedRuntimeManager,+ ManagedRuntimeManifest,+ ManagedRuntimeSpec,+)+from core.memory import artifact as memory_artifact+from core.memory.artifact import MemoryArtifactManager, MemoryRuntimeActivationErrorfrom vibe.model_hub_runtime.installer import EngineRuntimeManager@@ -24,6 +31,784 @@ class FixtureRuntimeManager(ManagedRuntimeManager):return binary.read_text(encoding="utf-8").strip()+def _write_subclass_runtime_fixture(+ tmp_path: Path,+ runtime_kind: str,+ *,+ bin_path: str | None = None,+ runtime_version: str | None = None,+) -> tuple[Path, Path]:+ binary_paths = {+ "git": "bin/git",+ "memory": "bin/python",+ "model-hub": "cli-proxy-api",+ }+ binary_path = bin_path or binary_paths[runtime_kind]+ runtime_version = runtime_version or {+ "git": "2.55.0",+ "memory": "1.2.3",+ "model-hub": "v7.2.95",+ }[runtime_kind]+ binary_payloads = {+ "git": f'#!/bin/sh\n[ "$1" = "--version" ] || exit 2\necho git version {runtime_version}\n'.encode(),+ "memory": b"#!/bin/sh\nexit 0\n",+ "model-hub": (+ f'#!/bin/sh\n[ "$1" = "--help" ] || exit 2\n'+ f'echo "CLIProxyAPI Version: {runtime_version.removeprefix("v")}" >&2\n'+ ).encode(),+ }+ binary_payload = binary_payloads[runtime_kind]+ archive = tmp_path / f"{runtime_kind}.tar.gz"+ with tarfile.open(archive, "w:gz") as tar:+ member = tarfile.TarInfo(binary_path)+ member.mode = 0o755+ member.size = len(binary_payload)+ tar.addfile(member, io.BytesIO(binary_payload))++ archive_payload = {+ "name": archive.name,+ "url": archive.as_uri(),+ "sha256": hashlib.sha256(archive.read_bytes()).hexdigest(),+ "binary_sha256": hashlib.sha256(binary_payload).hexdigest(),+ "size": archive.stat().st_size,+ "bin_path": binary_path,+ }+ platform_tag = managed_runtime.runtime_platform_tag()+ if runtime_kind == "git":+ payload = {+ "schema_version": 1,+ "git_version": runtime_version,+ "source": "fixture",+ "release_state": "published",+ "archives": {platform_tag: archive_payload},+ }+ elif runtime_kind == "memory":+ payload = {+ "schema_version": 1,+ "everos_version": runtime_version,+ "python_version": "3.12.12",+ "lock_sha256": "e6acc17e4c0969563d380326e90134965af0822259bb4a9adb4d54433e9737fe",+ "lock_id": "uv-lock-sha256:e6acc17e4c0969563d380326e90134965af0822259bb4a9adb4d54433e9737fe",+ "uv_version": "0.9.18",+ "source": "fixture",+ "release_state": "published",+ "provider_root_format": "everos-1.2.3",+ "compatible_provider_root_formats": [],+ "archives": {platform_tag: archive_payload},+ }+ else:+ asset_platform = "linux-amd64" if platform_tag == "linux-x64" else platform_tag+ payload = {+ "schema_version": 1,+ "name": "cliproxyapi",+ "version": runtime_version,+ "source": "router-for-me/CLIProxyAPI",+ "source_sha": "f71ec0eb6776854457892452cf28c47f0d658251",+ "release_tag": runtime_version,+ "license": "MIT",+ "assets": [+ {+ **archive_payload,+ "platform": asset_platform,+ "size_bytes": archive_payload["size"],+ }+ ],+ }+ del payload["assets"][0]["size"]+ manifest = tmp_path / f"{runtime_kind}-manifest.json"+ manifest.write_text(json.dumps(payload), encoding="utf-8")+ return archive, manifest+++def _subclass_runtime_manager(+ tmp_path: Path,+ runtime_kind: str,+ manifest: Path,+ monkeypatch: pytest.MonkeyPatch,+ *,+ runtime_dir: Path | None = None,+) -> ManagedRuntimeManager:+ runtime_dir = runtime_dir or tmp_path / f"{runtime_kind}-runtime"+ if runtime_kind == "git":+ return GitRuntimeManager(runtime_dir=runtime_dir, manifest_path=manifest)+ if runtime_kind == "memory":+ manager = MemoryArtifactManager(+ runtime_dir=runtime_dir,+ manifest_path=manifest,+ provider_root=tmp_path / "memory-provider-root",+ )+ monkeypatch.setattr(manager, "_prepare_binary", lambda _binary, **_kwargs: {"ok": True})+ monkeypatch.setattr(manager, "_binary_matches_manifest", lambda _binary, _manifest: True)+ return manager+ return EngineRuntimeManager(runtime_dir=runtime_dir, manifest_path=manifest)+++def _change_unrelated_platform(manifest: Path, runtime_kind: str) -> None:+ payload = json.loads(manifest.read_text(encoding="utf-8"))+ unrelated = {+ "name": "unrelated.tar.gz",+ "url": "https://example.test/unrelated.tar.gz",+ "sha256": "d" * 64,+ "binary_sha256": "e" * 64,+ "size": 1,+ "bin_path": "unused",+ }+ if runtime_kind == "model-hub":+ payload["assets"].append(+ {+ **unrelated,+ "platform": "fixture-unrelated",+ "size_bytes": unrelated["size"],+ }+ )+ del payload["assets"][-1]["size"]+ else:+ payload["archives"]["fixture-unrelated"] = unrelated+ manifest.write_text(json.dumps(payload), encoding="utf-8")+++def _resolve_subclass_runtime(manager: ManagedRuntimeManager, runtime_kind: str) -> Path | None:+ if runtime_kind == "git":+ return manager.resolve_git_path() # type: ignore[attr-defined]+ if runtime_kind == "memory":+ return manager.resolve_python() # type: ignore[attr-defined]+ return manager.resolve_engine_path() # type: ignore[attr-defined]++[email protected]("runtime_kind", ["git", "memory", "model-hub"])+def test_subclass_relative_runtime_directory_persists_an_admissible_absolute_path(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ runtime_kind: str,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, runtime_kind)+ monkeypatch.chdir(tmp_path)+ relative_runtime_dir = Path("relative-runtimes") / runtime_kind+ manager = _subclass_runtime_manager(+ tmp_path,+ runtime_kind,+ manifest,+ monkeypatch,+ runtime_dir=relative_runtime_dir,+ )++ installed = manager.ensure()++ assert installed["ok"] is True+ assert manager.runtime_dir == tmp_path / relative_runtime_dir+ assert Path(installed["install_dir"]).is_absolute()+ assert manager.status()["path"] == installed["path"]+ assert _resolve_subclass_runtime(manager, runtime_kind) == Path(installed["path"])++[email protected]("runtime_kind", ["git", "memory", "model-hub"])+def test_installed_subclass_status_and_resolution_survive_unavailable_manifest(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ runtime_kind: str,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, runtime_kind)+ manager = _subclass_runtime_manager(tmp_path, runtime_kind, manifest, monkeypatch)+ installed = manager.ensure()+ assert installed["ok"] is True+ installed_path = Path(installed["path"])+ pointer_path = manager.runtime_dir / "current.json"+ metadata_path = Path(installed["install_dir"]) / manager.spec.metadata_filename+ pointer_before = pointer_path.read_bytes()+ metadata_before = metadata_path.read_bytes()++ _change_unrelated_platform(manifest, runtime_kind)+ monkeypatch.setattr(+ manager,+ "_resolve_manifest_archive",+ lambda _archive: pytest.fail("disk-local inspection accessed an archive"),+ )+ monkeypatch.setattr(+ manager,+ "_write_current_pointer",+ lambda *_args: pytest.fail("disk-local inspection rewrote the active pointer"),+ )++ reused = manager.ensure()++ assert reused["ok"] is True+ assert reused["changed"] is False+ assert reused["path"] == str(installed_path)+ assert reused["install_dir"] == installed["install_dir"]+ assert pointer_path.read_bytes() == pointer_before+ assert metadata_path.read_bytes() == metadata_before++ manifest.unlink()+ status = manager.status()++ assert status["installed"] is True+ assert status["version"] == {"git": "2.55.0", "memory": "1.2.3", "model-hub": "v7.2.95"}[+ runtime_kind+ ]+ assert status["selected_version"] is None+ assert status["matches_manifest"] is None+ assert status["path"] == str(installed_path)+ assert status["install_dir"] == installed["install_dir"]+ assert status["reason"] is None+ assert _resolve_subclass_runtime(manager, runtime_kind) == installed_path+ assert pointer_path.read_bytes() == pointer_before+ assert metadata_path.read_bytes() == metadata_before++[email protected]("runtime_kind", ["git", "memory", "model-hub"])+def test_subclass_operational_resolution_uses_disk_snapshot_when_manifest_is_missing(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ runtime_kind: str,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, runtime_kind)+ manager = _subclass_runtime_manager(tmp_path, runtime_kind, manifest, monkeypatch)+ installed = manager.ensure()+ assert installed["ok"] is True+ installed_path = Path(installed["path"])+ manifest.unlink()++ status = manager.status()+ resolved = _resolve_subclass_runtime(manager, runtime_kind)++ assert (status["installed"], status["path"], resolved) == (+ True,+ str(installed_path),+ installed_path,+ )+++def test_git_resolves_a_runtime_version_accepted_by_the_installer(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _archive, manifest = _write_subclass_runtime_fixture(+ tmp_path,+ "git",+ runtime_version="2.55.0+avibe.1",+ )+ manager = _subclass_runtime_manager(tmp_path, "git", manifest, monkeypatch)++ installed = manager.ensure()+ manifest.unlink()++ assert installed["ok"] is True+ assert manager.status()["version"] == "2.55.0+avibe.1"+ assert manager.resolve_git_path() == Path(installed["path"])++[email protected]("bin_path", ["python", "usr/bin/python"])+def test_memory_status_uses_the_recorded_install_dir_for_any_safe_entrypoint(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ bin_path: str,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest = _write_subclass_runtime_fixture(+ tmp_path,+ "memory",+ bin_path=bin_path,+ )+ manager = _subclass_runtime_manager(tmp_path, "memory", manifest, monkeypatch)++ installed = manager.ensure()+ status = manager.status()++ assert installed["ok"] is True+ assert status["installed"] is True+ assert status["matches_manifest"] is True+ assert status["path"] == installed["path"]+ assert status["install_dir"] == installed["install_dir"]+++def test_shared_status_retries_when_current_pointer_switches_during_resolution(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, "git")+ manager = _subclass_runtime_manager(tmp_path, "git", manifest, monkeypatch)+ installed = manager.ensure()+ assert installed["ok"] is True+ manifest.unlink()++ pointer_path = manager.runtime_dir / "current.json"+ old_pointer = json.loads(pointer_path.read_text(encoding="utf-8"))+ new_install_dir = manager.runtime_dir / "versions" / "concurrent-replacement"+ old_install_dir = Path(installed["install_dir"])+ shutil.copytree(old_install_dir, new_install_dir)+ metadata_path = new_install_dir / manager.spec.metadata_filename+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))+ metadata["runtime_version"] = "2.56.0"+ managed_runtime.write_json_atomic(metadata_path, metadata)+ new_pointer = {+ **old_pointer,+ "runtime_version": "2.56.0",+ "install_dir": str(new_install_dir),+ }++ original_resolve = manager.resolve_binary+ resolve_calls = 0++ def switch_pointer_after_first_resolution() -> Path | None:+ nonlocal resolve_calls+ binary = original_resolve()+ resolve_calls += 1+ if resolve_calls == 1:+ managed_runtime.write_json_atomic(pointer_path, new_pointer)+ return binary++ monkeypatch.setattr(manager, "resolve_binary", switch_pointer_after_first_resolution)++ status = manager.status()++ expected_binary = new_install_dir / manager.spec.default_bin_path+ assert resolve_calls == 2+ assert status["installed"] is True+ assert status["version"] == "2.56.0"+ assert status["path"] == str(expected_binary)+ assert status["install_dir"] == str(new_install_dir)++[email protected]("runtime_kind", ["git", "model-hub"])+def test_subclass_derives_released_missing_bin_path_from_safe_spec_default(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ runtime_kind: str,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, runtime_kind)+ manager = _subclass_runtime_manager(tmp_path, runtime_kind, manifest, monkeypatch)+ installed = manager.ensure()+ assert installed["ok"] is True+ installed_path = Path(installed["path"])+ pointer_path = manager.runtime_dir / "current.json"+ metadata_path = Path(installed["install_dir"]) / manager.spec.metadata_filename+ pointer = json.loads(pointer_path.read_text(encoding="utf-8"))+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))+ pointer.pop("bin_path")+ metadata.pop("bin_path")+ managed_runtime.write_json_atomic(pointer_path, pointer)+ managed_runtime.write_json_atomic(metadata_path, metadata)+ pointer_before = pointer_path.read_bytes()+ metadata_before = metadata_path.read_bytes()+ monkeypatch.setattr(+ manager,+ "_resolve_manifest_archive",+ lambda _archive: pytest.fail("safe default entrypoint accessed an archive"),+ )+ monkeypatch.setattr(+ manager,+ "_write_current_pointer",+ lambda *_args: pytest.fail("safe default entrypoint rewrote the pointer"),+ )++ reused = manager.ensure()++ assert reused["ok"] is True+ assert reused["changed"] is False+ assert reused["path"] == str(installed_path)+ manifest.unlink()+ status = manager.status()+ assert status["installed"] is True+ assert status["path"] == str(installed_path)+ assert _resolve_subclass_runtime(manager, runtime_kind) == installed_path+ assert pointer_path.read_bytes() == pointer_before+ assert metadata_path.read_bytes() == metadata_before++[email protected]("runtime_kind", ["git", "memory", "model-hub"])+def test_subclass_status_rejects_an_unreadable_installed_binary(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ runtime_kind: str,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, runtime_kind)+ manager = _subclass_runtime_manager(tmp_path, runtime_kind, manifest, monkeypatch)+ installed = manager.ensure()+ assert installed["ok"] is True++ def unreadable_binary(_path: Path) -> str:+ raise OSError("binary became unreadable")++ monkeypatch.setattr(managed_runtime, "file_sha256", unreadable_binary)++ status = manager.status()++ assert status["installed"] is False+ assert status["status"] == "error"+ assert status["reason"] is not None+ assert _resolve_subclass_runtime(manager, runtime_kind) is None++[email protected]("runtime_kind", ["git", "memory", "model-hub"])[email protected]("state_file", ["pointer", "metadata"])+def test_subclass_projects_deep_installed_json_as_an_inspection_failure(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ runtime_kind: str,+ state_file: str,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, runtime_kind)+ manager = _subclass_runtime_manager(tmp_path, runtime_kind, manifest, monkeypatch)+ installed = manager.ensure()+ assert installed["ok"] is True+ state_path = (+ manager.runtime_dir / "current.json"+ if state_file == "pointer"+ else Path(installed["install_dir"]) / manager.spec.metadata_filename+ )+ state_path.write_text(+ "[" * 2_000 + "0" + "]" * 2_000,+ encoding="utf-8",+ )++ status = manager.status()++ assert status["installed"] is False+ assert status["status"] == "error"+ assert _resolve_subclass_runtime(manager, runtime_kind) is None++[email protected]("runtime_kind", ["git", "model-hub"])+def test_shared_reuse_repairs_pointer_from_persisted_metadata_identity(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ runtime_kind: str,+) -> None:+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, runtime_kind)+ manager = _subclass_runtime_manager(tmp_path, runtime_kind, manifest, monkeypatch)+ installed = manager.ensure()+ assert installed["ok"] is True+ pointer_path = manager.runtime_dir / "current.json"+ metadata_path = Path(installed["install_dir"]) / manager.spec.metadata_filename+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))+ pointer = json.loads(pointer_path.read_text(encoding="utf-8"))+ pointer["manifest_sha256"] = "f" * 64+ managed_runtime.write_json_atomic(pointer_path, pointer)+ metadata_before = metadata_path.read_bytes()+ monkeypatch.setattr(+ manager,+ "_resolve_manifest_archive",+ lambda _archive: pytest.fail("pointer repair accessed an archive"),+ )++ reused = manager.ensure()++ assert reused["ok"] is True+ assert reused["changed"] is False+ repaired = json.loads(pointer_path.read_text(encoding="utf-8"))+ assert repaired["manifest_sha256"] == metadata["manifest_sha256"]+ assert metadata_path.read_bytes() == metadata_before+ assert _resolve_subclass_runtime(manager, runtime_kind) == Path(installed["path"])++[email protected]("runtime_kind", ["git", "memory", "model-hub"])+def test_invalid_manifest_keeps_disk_resolution_but_blocks_repair(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ runtime_kind: str,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, runtime_kind)+ manager = _subclass_runtime_manager(tmp_path, runtime_kind, manifest, monkeypatch)+ installed = manager.ensure()+ assert installed["ok"] is True+ installed_path = Path(installed["path"])+ manifest.write_text("{", encoding="utf-8")+ monkeypatch.setattr(+ manager,+ "_resolve_manifest_archive",+ lambda _archive: pytest.fail("invalid manifest repair accessed an archive"),+ )++ status = manager.status()+ resolved = _resolve_subclass_runtime(manager, runtime_kind)+ repair = manager.ensure()++ assert status["installed"] is True+ assert status["path"] == str(installed_path)+ assert resolved == installed_path+ assert repair["ok"] is False+ assert str(repair["reason"]).endswith("manifest_invalid")+++def test_memory_reuse_refreshes_changed_manifest_contract_through_activation(+ 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 isinstance(manager, MemoryArtifactManager)+ installed = manager.ensure()+ assert installed["ok"] is True++ payload = json.loads(manifest_path.read_text(encoding="utf-8"))+ payload["provider_root_format"] = "everos-2.0"+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")+ updated_manifest_digest = hashlib.sha256(manifest_path.read_bytes()).hexdigest()+ selected_status = manager.status()++ assert selected_status["installed"] is True+ assert selected_status["path"] == installed["path"]+ assert selected_status["matches_manifest"] is False++ activations: list[str] = []++ def activate(candidate, root_state, commit, _rollback) -> None:+ activations.append(candidate.provider_root_format)+ assert root_state is not None+ assert root_state.exists is False+ commit()++ manager.set_activation_coordinator(activate)+ sync_admissions: list[tuple[int, tuple[str, ...], str, str] | None] = []++ def admit_sync(+ _binary: Path,+ contract: tuple[int, tuple[str, ...], str, str] | None,+ ) -> bool:+ sync_admissions.append(contract)+ return True++ monkeypatch.setattr(manager, "_admit_sync_contract", admit_sync)+ monkeypatch.setattr(+ manager,+ "_resolve_manifest_archive",+ lambda _archive: pytest.fail("Memory contract refresh accessed an archive"),+ )++ reused = manager.ensure()++ assert reused["ok"] is True+ assert reused["changed"] is False+ assert reused["path"] == installed["path"]+ assert activations == ["everos-2.0"]+ active = manager._active_pointer()+ assert active is not None+ assert active["provider_root_format"] == "everos-2.0"+ assert active["compatible_provider_root_formats"] == []+ assert active["artifact_fingerprint"] == updated_manifest_digest[:16]+ assert sync_admissions == []+ assert manager.status()["matches_manifest"] is True+++def test_memory_selected_contract_failure_preserves_admitted_install(+ 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 isinstance(manager, MemoryArtifactManager)+ installed = manager.ensure()+ assert installed["ok"] is True+ pointer_path = manager.runtime_dir / "current.json"+ pointer_before = pointer_path.read_bytes()+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))+ payload["provider_root_format"] = "everos-next"+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")+ monkeypatch.setattr(manager, "_prepare_binary", lambda _binary, **_kwargs: {"ok": False})+ monkeypatch.setattr(+ manager,+ "_resolve_manifest_archive",+ lambda _archive: pytest.fail("failed Memory re-admission accessed an archive"),+ )++ failed = manager.ensure()++ assert failed["ok"] is False+ assert pointer_path.read_bytes() == pointer_before+ assert manager.status()["installed"] is True+ assert manager.resolve_python() == Path(installed["path"])+++def test_memory_force_pointer_failure_preserves_active_install_and_retry_repairs_contract(+ 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 isinstance(manager, MemoryArtifactManager)+ installed = manager.ensure()+ assert installed["ok"] is True+ pointer_path = manager.runtime_dir / "current.json"+ metadata_path = Path(installed["install_dir"]) / manager.spec.metadata_filename+ metadata_before = metadata_path.read_bytes()+ install_dirs_before = {+ path.parent for path in manager.runtime_dir.rglob(manager.spec.metadata_filename)+ }+ original_pointer = json.loads(pointer_path.read_text(encoding="utf-8"))+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))+ payload["provider_root_format"] = "everos-2.0"+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")+ real_write_pointer = manager._write_memory_current_pointer++ def fail_pointer_write(*_args, **_kwargs) -> None:+ raise MemoryRuntimeActivationError("pointer write failed")++ monkeypatch.setattr(manager, "_write_memory_current_pointer", fail_pointer_write)++ failed = manager.ensure(force=True)++ assert failed["ok"] is False+ assert metadata_path.read_bytes() == metadata_before+ assert json.loads(pointer_path.read_text(encoding="utf-8")) == original_pointer+ assert manager.resolve_python() == Path(installed["path"])+ assert {+ path.parent for path in manager.runtime_dir.rglob(manager.spec.metadata_filename)+ } == install_dirs_before++ monkeypatch.setattr(manager, "_write_memory_current_pointer", real_write_pointer)+ monkeypatch.setattr(+ manager,+ "_resolve_manifest_archive",+ lambda _archive: pytest.fail("pointer retry accessed an archive"),+ )++ retried = manager.ensure()++ assert retried["ok"] is True+ assert retried["changed"] is False+ repaired_pointer = json.loads(pointer_path.read_text(encoding="utf-8"))+ repaired_metadata = json.loads(metadata_path.read_text(encoding="utf-8"))+ assert repaired_pointer["manifest_sha256"] == repaired_metadata["manifest_sha256"]+ assert repaired_pointer["manifest_sha256"] != original_pointer["manifest_sha256"]+ assert repaired_pointer["install_dir"] == installed["install_dir"]+++def test_memory_force_repair_rollback_preserves_the_active_install_directory(+ 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 isinstance(manager, MemoryArtifactManager)+ installed = manager.ensure()+ assert installed["ok"] is True+ active_dir = Path(installed["install_dir"])+ pointer_path = manager.runtime_dir / "current.json"+ metadata_path = active_dir / manager.spec.metadata_filename+ pointer_before = pointer_path.read_bytes()+ metadata_before = metadata_path.read_bytes()+ binary_before = Path(installed["path"]).read_bytes()+ install_dirs_before = {path.parent for path in manager.runtime_dir.rglob(manager.spec.metadata_filename)}+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))+ payload["source"] = "fixture-force-repair"+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")++ def reject_candidate(_candidate, _root_state, commit, rollback) -> None:+ commit()+ candidate = manager._active_pointer()+ assert candidate is not None+ assert candidate["install_dir"] != str(active_dir)+ rollback()+ raise MemoryRuntimeActivationError("candidate rejected")++ manager.set_activation_coordinator(reject_candidate)++ failed = manager.ensure(force=True)++ assert failed["ok"] is False+ assert pointer_path.read_bytes() == pointer_before+ assert metadata_path.read_bytes() == metadata_before+ assert Path(installed["path"]).read_bytes() == binary_before+ assert manager.resolve_python() == Path(installed["path"])+ assert {path.parent for path in manager.runtime_dir.rglob(manager.spec.metadata_filename)} == install_dirs_before++ def accept_candidate(_candidate, _root_state, commit, _rollback) -> None:+ commit()++ manager.set_activation_coordinator(accept_candidate)+ repaired = manager.ensure(force=True)+ assert repaired["ok"] is True+ assert repaired["changed"] is True+ assert repaired["install_dir"] != str(active_dir)+ assert active_dir.is_dir()+ monkeypatch.setattr(+ manager,+ "_resolve_manifest_archive",+ lambda _archive: pytest.fail("successful force reuse accessed an archive"),+ )++ reused = manager.ensure()++ assert reused["ok"] is True+ assert reused["changed"] is False+ assert reused["install_dir"] == repaired["install_dir"]++[email protected]("runtime_kind", ["git", "memory", "model-hub"])+def test_existing_subclass_adopts_released_manifest_digest_layout_without_write_or_download(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ runtime_kind: str,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ _archive, manifest_path = _write_subclass_runtime_fixture(tmp_path, runtime_kind)+ manager = _subclass_runtime_manager(tmp_path, runtime_kind, manifest_path, monkeypatch)+ installed = manager.ensure()+ assert installed["ok"] is True++ manifest = manager._load_manifest(allow_network=False)+ assert manifest is not None+ archive = manager._manifest_archive_for_platform(manifest)+ assert archive is not None+ install_dir = Path(installed["install_dir"])+ released_fingerprint = hashlib.sha256(+ f"{manifest.digest}:{archive.sha256}".encode("utf-8")+ ).hexdigest()[:16]+ released_install_dir = install_dir.parent / released_fingerprint+ if released_install_dir != install_dir:+ install_dir.rename(released_install_dir)+ pointer_path = manager.runtime_dir / "current.json"+ pointer = json.loads(pointer_path.read_text(encoding="utf-8"))+ pointer["install_dir"] = str(released_install_dir)+ pointer.pop("binary_sha256", None)+ pointer_path.write_text(json.dumps(pointer), encoding="utf-8")+ released_binary = released_install_dir / archive.bin_path+ metadata_path = released_install_dir / manager.spec.metadata_filename+ pointer_before = pointer_path.read_bytes()+ metadata_before = metadata_path.read_bytes()+ install_mtime_before = released_install_dir.stat().st_mtime_ns++ monkeypatch.setattr(+ manager,+ "_resolve_manifest_archive",+ lambda _archive: pytest.fail("released install adoption accessed an archive"),+ )+ monkeypatch.setattr(+ manager,+ "_write_current_pointer",+ lambda *_args: pytest.fail("released install adoption rewrote the active pointer"),+ )++ reused = manager.ensure()++ assert reused["ok"] is True+ assert reused["changed"] is False+ assert reused["install_dir"] == str(released_install_dir)+ assert Path(reused["path"]) == released_binary+ assert pointer_path.read_bytes() == pointer_before+ assert metadata_path.read_bytes() == metadata_before+ assert released_install_dir.stat().st_mtime_ns == install_mtime_before++ manifest_path.unlink()+ status = manager.status()+ assert status["installed"] is True+ assert status["path"] == str(released_binary)+ assert _resolve_subclass_runtime(manager, runtime_kind) == released_binary+ assert pointer_path.read_bytes() == pointer_before+ assert metadata_path.read_bytes() == metadata_before++def test_clean_dry_run_is_read_only_and_creates_no_lock(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,@@ -227,74 +1012,6 @@ def test_shared_ensure_failure_vocabulary_matches_reachable_reason_literals() ->assert managed_runtime._ENSURE_FAILURE_SUFFIXES == reason_suffixes- ("include_direct_platform", "expected_platform"),- [(False, "linux-amd64"), (True, "linux-x64")],-)-def test_list_asset_manifest_prefers_direct_platform_then_falls_back_to_alias(- tmp_path: Path,- monkeypatch,- include_direct_platform: bool,- expected_platform: str,-) -> None:- archive = tmp_path / "fixture-linux_amd64.tar.gz"- binary_payload = b"v1\n"- with tarfile.open(archive, "w:gz") as tar:- member = tarfile.TarInfo("fixture")- member.mode = 0o755- member.size = len(binary_payload)- tar.addfile(member, io.BytesIO(binary_payload))-- assets = [- {- "platform": "linux-amd64",- "url": archive.as_uri(),- "size_bytes": archive.stat().st_size,- "sha256": hashlib.sha256(archive.read_bytes()).hexdigest(),- "binary_sha256": hashlib.sha256(binary_payload).hexdigest(),- }- ]- if include_direct_platform:- assets.append({**assets[0], "platform": "linux-x64"})- manifest = tmp_path / "manifest.json"- manifest.write_text(- json.dumps(- {- "schema_version": 1,- "version": "v1",- "source": "example/fixture",- "assets": assets,- }- ),- encoding="utf-8",- )- monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: "linux-x64")- manager = FixtureRuntimeManager(- spec=ManagedRuntimeSpec(- runtime_id="fixture",- manifest_resource="unused.json",- version_field="version",- default_bin_path="fixture",- archives_field="assets",- archive_size_field="size_bytes",- platform_aliases=(("linux-x64", "linux-amd64"),),- ),- runtime_dir=tmp_path / "runtime",- manifest_path=manifest,- )-- resolved_targets: list[dict[str, str]] = []- result = manager.ensure(on_resolved=resolved_targets.append)-- assert result["ok"] is True- assert result["changed"] is True- assert result["platform"] == expected_platform- assert resolved_targets == [result["target"]]- assert Path(result["path"]).read_bytes() == binary_payload- assert manager.ensure()["changed"] is False- assert manager.status()["installed"] is True--def test_ensure_rejects_a_changed_resolved_target_before_archive_access(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,@@ -337,10 +1054,9 @@ def test_ensure_rejects_a_changed_resolved_target_before_archive_access(manifest_path=manifest,)expected_target = {- "manifest_sha256": "0" * 64,"runtime_version": "v1","platform": "linux-x64",- "archive_sha256": hashlib.sha256(archive.read_bytes()).hexdigest(),+ "archive_sha256": "0" * 64,"binary_sha256": hashlib.sha256(binary_payload).hexdigest(),}monkeypatch.setattr(@@ -353,30 +1069,3 @@ def test_ensure_rejects_a_changed_resolved_target_before_archive_access(assert result["ok"] is Falseassert result["reason"] == "fixture_install_target_changed"--- ("manager_type", "expected_reason"),- [- (GitRuntimeManager, "git_manifest_missing"),- (MemoryArtifactManager, "memory-runtime_manifest_missing"),- (EngineRuntimeManager, "model_hub_engine_manifest_missing"),- ],-)-def test_optional_ensure_hooks_leave_each_existing_subclass_default_unchanged(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,- manager_type,- expected_reason: str,-) -> None:- monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)- manager = manager_type(- runtime_dir=tmp_path / manager_type.__name__,- manifest_path=tmp_path / "missing-manifest.json",- offline=True,- )-- result = manager.ensure()-- assert result["ok"] is False- assert result["reason"] == expected_reasondiff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.pyindex 18fd5148e..f8432905f 100644--- a/tests/test_memory_runtime.py+++ b/tests/test_memory_runtime.py@@ -21,6 +21,7 @@ from types import SimpleNamespaceimport psutilimport pytest+from core import managed_runtimefrom core.managed_runtime import ManagedRuntimeArchive, ManagedRuntimeManifestimport core.memory.artifact as memory_artifactimport core.memory.confined_filesystem as confined_filesystem@@ -91,6 +92,7 @@ from config.v2_config import (PROJECT = "default"PRINCIPAL = "u-11111111111111111111111111111111"+MEMORY_FIXTURES = Path(__file__).parent / "fixtures" / "memory"async def test_all_project_agentic_recall_is_rejected_before_project_access() -> None:@@ -821,6 +823,103 @@ def test_memory_artifact_status_marks_broken_active_binary_as_error(tmp_path: Paassert status["reason"] == "memory_runtime_install_failed"+ ("probe_outcome", "expected_admitted"),+ [("success", True), ("false", False), ("raise", False)],+)+def test_released_memory_pointer_status_is_shallow_and_resolver_readmits(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ probe_outcome: str,+ expected_admitted: bool,+) -> None:+ manager = MemoryArtifactManager(+ runtime_dir=tmp_path / "runtime",+ manifest_path=tmp_path / "missing-manifest.json",+ offline=True,+ )+ pointer = json.loads(+ (MEMORY_FIXTURES / "released_active_pointer.json").read_text(encoding="utf-8")+ )+ pointer["platform"] = memory_artifact.runtime_platform_tag()+ fingerprint = hashlib.sha256(+ f'{pointer["manifest_sha256"]}:{pointer["archive_sha256"]}'.encode("utf-8")+ ).hexdigest()[:16]+ install_dir = (+ manager.runtime_dir+ / "versions"+ / pointer["runtime_version"]+ / pointer["platform"]+ / fingerprint+ )+ binary = install_dir / "bin" / "python"+ binary.parent.mkdir(parents=True)+ binary.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ binary.chmod(0o755)+ pointer["install_dir"] = str(install_dir)+ (install_dir / manager.spec.metadata_filename).write_text(+ json.dumps(+ {+ **pointer,+ "binary_sha256": hashlib.sha256(binary.read_bytes()).hexdigest(),+ }+ ),+ encoding="utf-8",+ )+ manager._restore_current_pointer(pointer)+ pointer_path = manager.runtime_dir / "current.json"+ pointer_before = pointer_path.read_bytes()+ artifact_before = {+ path.relative_to(install_dir): path.read_bytes()+ for path in install_dir.rglob("*")+ if path.is_file()+ }+ real_restore = manager._restore_current_pointer++ monkeypatch.setattr(+ manager,+ "_prepare_binary",+ lambda *_args, **_kwargs: pytest.fail("status performed a deep probe"),+ )+ monkeypatch.setattr(+ manager,+ "_restore_current_pointer",+ lambda *_args: pytest.fail("status rewrote the released pointer"),+ )++ status = manager.status()++ assert status["installed"] is True+ assert status["status"] == "ready"+ assert status["path"] == str(binary)+ assert pointer_path.read_bytes() == pointer_before+ assert {+ path.relative_to(install_dir): path.read_bytes()+ for path in install_dir.rglob("*")+ if path.is_file()+ } == artifact_before++ def probe(*_args, **_kwargs) -> dict[str, bool]:+ if probe_outcome == "raise":+ raise RuntimeError("probe failed")+ return {"ok": probe_outcome == "success"}++ monkeypatch.setattr(manager, "_prepare_binary", probe)+ monkeypatch.setattr(manager, "_restore_current_pointer", real_restore)++ resolved = manager.resolve_python()+ active = manager._active_pointer()++ assert resolved == (binary if expected_admitted else None)+ assert active is not None+ if probe_outcome == "raise":+ assert "admission_revision" not in active+ assert "admission_ok" not in active+ else:+ assert active["admission_revision"] == memory_artifact.ARTIFACT_ADMISSION_REVISION+ assert active["admission_ok"] is expected_admitted++@pytest.mark.parametrize("mismatch",[@@ -869,68 +968,6 @@ def test_memory_artifact_rejects_an_active_pointer_built_for_another_target(assert manager.resolve_python() is None[email protected]("admitted", [False, True])-def test_memory_artifact_readmits_active_pointer_after_contract_revision(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,- admitted: bool,-) -> None:- manager = MemoryArtifactManager(runtime_dir=tmp_path / "runtime", offline=True)- install_dir = manager.runtime_dir / "versions" / "old"- binary = install_dir / "bin" / "python"- binary.parent.mkdir(parents=True)- binary.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")- binary.chmod(0o755)- pointer = {- "provider": "manifest",- "runtime_id": "memory-runtime",- "runtime_version": memory_artifact.EVEROS_VERSION,- "platform": memory_artifact.runtime_platform_tag(),- "install_dir": str(install_dir),- "manifest_sha256": "a" * 64,- "archive_sha256": "b" * 64,- "bin_path": "bin/python",- }- (install_dir / manager.spec.metadata_filename).write_text(- json.dumps(- {- **pointer,- "binary_sha256": hashlib.sha256(binary.read_bytes()).hexdigest(),- }- ),- encoding="utf-8",- )- manager._restore_current_pointer(pointer)- admissions: list[Path] = []-- def admit(candidate: Path) -> dict[str, object]:- admissions.append(candidate)- return {- "ok": admitted,- "reason": None if admitted else "memory_runtime_install_failed",- }-- monkeypatch.setattr(manager, "_prepare_binary", admit)-- resolved = manager.resolve_python()-- assert resolved == (binary if admitted else None)- assert admissions == [binary]- active = manager._active_pointer()- assert active is not None- if admitted:- assert active["admission_revision"] == memory_artifact.ARTIFACT_ADMISSION_REVISION- assert active["admission_ok"] is True- assert manager.resolve_python() == binary- assert admissions == [binary]- else:- assert active["admission_revision"] == memory_artifact.ARTIFACT_ADMISSION_REVISION- assert active["admission_ok"] is False- assert manager.resolve_python() is None- assert manager.status()["reason"] == "memory_runtime_install_failed"- assert admissions == [binary]--@pytest.mark.parametrize("admitted", [False, True])def test_memory_artifact_readmits_existing_install_before_reuse(monkeypatch: pytest.MonkeyPatch,@@ -993,7 +1030,7 @@ def test_memory_artifact_readmits_existing_install_before_reuse(monkeypatch.setattr(manager, "_load_manifest", lambda *, allow_network: manifest)admissions: list[Path] = []- def admit(candidate: Path) -> dict[str, object]:+ def admit(candidate: Path, **_kwargs) -> dict[str, object]:admissions.append(candidate)return {"ok": admitted,@@ -1001,6 +1038,7 @@ def test_memory_artifact_readmits_existing_install_before_reuse(}monkeypatch.setattr(manager, "_prepare_binary", admit)+ pointer_before = (manager.runtime_dir / "current.json").read_bytes()result = manager.ensure(force=False)@@ -1009,12 +1047,16 @@ def test_memory_artifact_readmits_existing_install_before_reuse(assert admissions == [binary]active = manager._active_pointer()assert active is not None- assert active["admission_revision"] == memory_artifact.ARTIFACT_ADMISSION_REVISION- assert active["admission_ok"] is admitted- assert manager.resolve_python() == (binary if admitted else None)- if not admitted:- assert manager.status()["reason"] == "memory_runtime_install_failed"- assert admissions == [binary]+ if admitted:+ assert active["admission_revision"] == memory_artifact.ARTIFACT_ADMISSION_REVISION+ assert active["admission_ok"] is True+ assert manager.resolve_python() == binary+ assert admissions == [binary]+ else:+ assert (manager.runtime_dir / "current.json").read_bytes() == pointer_before+ assert manager.status()["installed"] is True+ assert (manager.runtime_dir / "current.json").read_bytes() == pointer_before+ assert admissions == [binary]def test_memory_artifact_coordinator_rolls_back_the_active_pointer(tmp_path: Path) -> None:@@ -1071,7 +1113,8 @@ def test_memory_artifact_coordinator_rolls_back_the_active_pointer(tmp_path: Pat== memory_artifact.ARTIFACT_ADMISSION_REVISION)assert manager._active_pointer()["admission_ok"] is True- calls.append(("active", manager.provider_root_format()))+ active = manager._active_pointer()+ calls.append(("active", active.get("provider_root_format") if active else None))rollback()manager.set_activation_coordinator(coordinate)@@ -1087,7 +1130,7 @@ def test_memory_artifact_coordinator_rolls_back_the_active_pointer(tmp_path: Pat("active", "everos-2.0"),]assert json.loads((manager.runtime_dir / "current.json").read_text(encoding="utf-8")) == previous_pointer- assert manager.provider_root_format() == "everos-1.0"+ assert manager._active_pointer()["provider_root_format"] == "everos-1.0"def test_memory_artifact_pending_reset_can_commit_when_old_root_is_incompatible(@@ -1135,6 +1178,43 @@ def test_memory_artifact_pending_reset_can_commit_when_old_root_is_incompatible(assert manager._active_pointer() is not None+def test_memory_artifact_activation_fails_closed_without_coordinator(tmp_path: Path) -> None:+ provider_root = tmp_path / "memory" / "everos-root"+ provider_root.mkdir(parents=True, mode=0o700)+ provider_root.parent.chmod(0o700)+ sentinel = provider_root / ".avibe-memory-root.json"+ sentinel.write_text(+ json.dumps(+ {+ "schema_version": 1,+ "provider_root_id": "root-id",+ "provider_id": "everos",+ "provider_root_format": "everos-1.0",+ "created_by_artifact_fingerprint": "old-artifact",+ }+ ),+ encoding="utf-8",+ )+ sentinel.chmod(0o600)+ manager = MemoryArtifactManager(+ runtime_dir=tmp_path / "runtime",+ offline=True,+ provider_root=provider_root,+ )++ with pytest.raises(+ MemoryRuntimeActivationError,+ match="memory runtime activation is unavailable",+ ):+ manager._write_current_pointer(+ manager.runtime_dir / "versions" / "candidate",+ _artifact_manifest("everos-2.0", compatible_formats=["everos-1.0"]),+ _artifact_archive(),+ )++ assert manager._active_pointer() is None++def test_memory_artifact_first_activation_rollback_does_not_need_temp_sqlite(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,@@ -1184,7 +1264,16 @@ async def test_memory_artifact_rollback_resolves_old_active_binary(offline=True,provider_root=tmp_path / "memory" / "everos-root",)- old_install_dir = manager.runtime_dir / "versions" / "old"+ manifest_sha256 = "a" * 64+ archive_sha256 = "b" * 64+ platform_tag = memory_artifact.runtime_platform_tag()+ old_install_dir = (+ manager.runtime_dir+ / "versions"+ / memory_artifact.EVEROS_VERSION+ / platform_tag+ / hashlib.sha256(f"{manifest_sha256}:{archive_sha256}".encode("utf-8")).hexdigest()[:16]+ )old_binary = old_install_dir / "bin" / "python"old_binary.parent.mkdir(parents=True)old_binary.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")@@ -1194,10 +1283,10 @@ async def test_memory_artifact_rollback_resolves_old_active_binary("provider": "manifest","runtime_id": "memory-runtime","runtime_version": memory_artifact.EVEROS_VERSION,- "platform": memory_artifact.runtime_platform_tag(),+ "platform": platform_tag,"install_dir": str(old_install_dir),- "manifest_sha256": "a" * 64,- "archive_sha256": "b" * 64,+ "manifest_sha256": manifest_sha256,+ "archive_sha256": archive_sha256,"bin_path": "bin/python","admission_revision": memory_artifact.ARTIFACT_ADMISSION_REVISION,"admission_ok": True,@@ -1211,9 +1300,9 @@ async def test_memory_artifact_rollback_resolves_old_active_binary("provider": "manifest","runtime_id": "memory-runtime","runtime_version": memory_artifact.EVEROS_VERSION,- "platform": memory_artifact.runtime_platform_tag(),- "manifest_sha256": "a" * 64,- "archive_sha256": "b" * 64,+ "platform": platform_tag,+ "manifest_sha256": manifest_sha256,+ "archive_sha256": archive_sha256,"binary_sha256": binary_sha256,"bin_path": "bin/python",}@@ -4284,12 +4373,33 @@ async def test_runtime_artifact_activation_rolls_back_root_and_sidecar(manager._restore_current_pointer(previous_pointer)monkeypatch.setattr(manager, "resolve_python", lambda: Path(sys.executable))monkeypatch.setattr(manager, "status", lambda: {"reason": None})+ monkeypatch.setattr(+ manager,+ "provider_root_format",+ lambda: manager._active_pointer().get("provider_root_format"),+ )+ monkeypatch.setattr(+ manager,+ "compatible_provider_root_formats",+ lambda: frozenset(+ {+ manager._active_pointer().get("provider_root_format"),+ *manager._active_pointer().get("compatible_provider_root_formats", []),+ }+ ),+ )+ monkeypatch.setattr(+ manager,+ "artifact_fingerprint",+ lambda: manager._active_pointer().get("artifact_fingerprint"),+ )class _Process(FakeEverOSProcess):"""Refuse to boot against the incompatible activated root format."""async def start(self) -> bool:- if manager.provider_root_format() == "everos-2.0":+ active = manager._active_pointer()+ if active is not None and active.get("provider_root_format") == "everos-2.0":self.starts += 1return Falsereturn await super().start()@@ -4321,7 +4431,7 @@ async def test_runtime_artifact_activation_rolls_back_root_and_sidecar()assert manager._active_pointer() == previous_pointer- assert manager.provider_root_format() == "everos-1.0"+ assert manager._active_pointer()["provider_root_format"] == "everos-1.0"assert len(instances) == 3assert instances[0].stopped is Trueassert instances[1].stopped is True@@ -4359,6 +4469,26 @@ async def test_runtime_artifact_activation_switches_incompatible_empty_root()monkeypatch.setattr(manager, "resolve_python", lambda: Path(sys.executable))monkeypatch.setattr(manager, "status", lambda: {"reason": None})+ monkeypatch.setattr(+ manager,+ "provider_root_format",+ lambda: manager._active_pointer().get("provider_root_format"),+ )+ monkeypatch.setattr(+ manager,+ "compatible_provider_root_formats",+ lambda: frozenset(+ {+ manager._active_pointer().get("provider_root_format"),+ *manager._active_pointer().get("compatible_provider_root_formats", []),+ }+ ),+ )+ monkeypatch.setattr(+ manager,+ "artifact_fingerprint",+ lambda: manager._active_pointer().get("artifact_fingerprint"),+ )factory = FakeEverOSProcessFactory()instances = factory.supervised@@ -4385,7 +4515,7 @@ async def test_runtime_artifact_activation_switches_incompatible_empty_root(_artifact_archive(),)- assert manager.provider_root_format() == "everos-2.0"+ assert manager._active_pointer()["provider_root_format"] == "everos-2.0"assert len(instances) == 2assert instances[0].stopped is Trueassert instances[1].stopped is False@@ -5091,6 +5221,11 @@ def _artifact_manifest(provider_root_format: str, *, compatible_formats: list[stdigest="c" * 64,loaded_from="test",payload={+ "release_state": "published",+ "python_version": memory_artifact.EMBEDDED_PYTHON_VERSION,+ "lock_sha256": memory_artifact.PACKAGE_LOCK_SHA256,+ "lock_id": f"uv-lock-sha256:{memory_artifact.PACKAGE_LOCK_SHA256}",+ "uv_version": memory_artifact.RUNTIME_BUILDER_UV_VERSION,"provider_root_format": provider_root_format,"compatible_provider_root_formats": compatible_formats,},diff --git a/tests/test_memory_sync_artifact_contract.py b/tests/test_memory_sync_artifact_contract.pyindex e900ec67f..2a43d49ae 100644--- a/tests/test_memory_sync_artifact_contract.py+++ b/tests/test_memory_sync_artifact_contract.py@@ -114,17 +114,23 @@ def test_sync_capability_rejects_a_nonadmitted_active_pointer() -> None:monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)manager = MemoryArtifactManager(runtime_dir=tmp_path / "runtime", offline=True)- install_dir = manager.runtime_dir / "versions" / "contract"+ manifest_sha256 = "a" * 64+ archive_sha256 = "b" * 64+ platform = runtime_platform_tag()+ fingerprint = hashlib.sha256(+ f"{manifest_sha256}:{archive_sha256}".encode("utf-8")+ ).hexdigest()[:16]+ install_dir = manager.runtime_dir / "versions" / EVEROS_VERSION / platform / fingerprintbinary, contract = _runtime_contract(tmp_path, runtime_root=install_dir)binary.chmod(0o755)pointer = {"provider": "manifest","runtime_id": manager.spec.runtime_id,"runtime_version": EVEROS_VERSION,- "platform": runtime_platform_tag(),+ "platform": platform,"install_dir": str(install_dir),- "manifest_sha256": "a" * 64,- "archive_sha256": "b" * 64,+ "manifest_sha256": manifest_sha256,+ "archive_sha256": archive_sha256,"bin_path": "bin/python","admission_revision": ARTIFACT_ADMISSION_REVISION,"admission_ok": False,@@ -139,6 +145,60 @@ def test_sync_capability_rejects_a_nonadmitted_active_pointer()manager._restore_current_pointer(pointer)+ assert manager.resolve_binary() is None+ assert manager.sync_capability() is False+++def test_sync_corruption_is_detected_by_capability_without_deep_status_probe(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ manager = MemoryArtifactManager(runtime_dir=tmp_path / "runtime", offline=True)+ manifest_sha256 = "a" * 64+ archive_sha256 = "b" * 64+ platform = runtime_platform_tag()+ fingerprint = hashlib.sha256(+ f"{manifest_sha256}:{archive_sha256}".encode("utf-8")+ ).hexdigest()[:16]+ install_dir = manager.runtime_dir / "versions" / EVEROS_VERSION / platform / fingerprint+ binary, contract = _runtime_contract(tmp_path, runtime_root=install_dir)+ binary.chmod(0o755)+ pointer = {+ "provider": "manifest",+ "runtime_id": manager.spec.runtime_id,+ "runtime_version": EVEROS_VERSION,+ "platform": platform,+ "install_dir": str(install_dir),+ "manifest_sha256": manifest_sha256,+ "archive_sha256": archive_sha256,+ "bin_path": "bin/python",+ "provider_root_format": "everos-1.2.3",+ "compatible_provider_root_formats": [],+ "artifact_fingerprint": "released-artifact",+ "admission_revision": ARTIFACT_ADMISSION_REVISION,+ "admission_ok": True,+ "sync_bootstrap_revision": contract[0],+ "sync_argv": list(contract[1]),+ "sync_bootstrap_sha256": contract[2],+ "sync_scrubbers_sha256": contract[3],+ }+ (install_dir / manager.spec.metadata_filename).write_text(+ json.dumps({**pointer, "binary_sha256": _digest(binary)}),+ encoding="utf-8",+ )+ manager._restore_current_pointer(pointer)+ assert manager._verified_active_pointer_binary(pointer) == binary++ scrubbers = (+ install_dir+ / "lib"+ / "python3.12"+ / "site-packages"+ / "avibe_memory_sync_scrubbers.py"+ )+ scrubbers.write_text("tampered", encoding="ascii")+assert manager._verified_active_pointer_binary(pointer) == binaryassert manager.sync_capability() is False@@ -198,22 +258,27 @@ def test_fresh_install_admits_the_manifest_sync_contract(provider_root=tmp_path / "memory" / "everos-root",offline=True,)- observed: list[tuple[int, tuple[str, ...], str, str] | None] = []+ prepared: list[tuple[Path, tuple[int, tuple[str, ...], str, str] | None]] = []monkeypatch.setattr(manager, "_load_manifest", lambda *, allow_network: manifest)monkeypatch.setattr(manager, "_resolve_manifest_archive", lambda _archive: archive_path)monkeypatch.setattr(manager, "_binary_matches_manifest", lambda *_args: True)monkeypatch.setattr(manager, "_write_current_pointer", lambda *_args: None)- def prepare(binary: Path, *, sync_contract=None) -> dict[str, bool]:+ def prepare(+ binary: Path,+ *,+ sync_contract: tuple[int, tuple[str, ...], str, str] | None = None,+ ) -> dict[str, bool]:assert binary.name == "python"- observed.append(sync_contract)+ prepared.append((binary, sync_contract))return {"ok": sync_contract == expected_contract}monkeypatch.setattr(manager, "_prepare_binary", prepare)assert manager.ensure()["ok"] is True- assert observed == [expected_contract]+ assert len(prepared) == 1+ assert prepared[0][1] == expected_contractdef test_release_guard_hashes_packaged_sync_modules(tmp_path: Path) -> None:diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 7cf05c261..644fa275f 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -41,6 +41,7 @@ from core.handlers.model_hub.stream_wire import ()from vibe.model_hub_runtime import adapter as runtime_adapter_modulefrom vibe.model_hub_runtime import client as client_module+from vibe.model_hub_runtime import installer as runtime_installer_modulefrom vibe.model_hub_runtime.adapter import CLIProxyEngineAdapterfrom vibe.model_hub_runtime.client import EngineClient, EngineClientError, EngineConnectionfrom vibe.model_hub_runtime.config import write_engine_config@@ -68,12 +69,14 @@ STREAM_TRANSPORT_BOUNDARIES = json.loads()["cases"]DEEP_JSON_ARRAY = b"[" * 10_000 + b"0" + b"]" * 10_000RUNTIME_INSTALL_TARGET = {- "manifest_sha256": "1" * 64,"runtime_version": "v7.2.95","platform": "fixture-platform","archive_sha256": "2" * 64,"binary_sha256": "3" * 64,}+RELEASED_INSTALL_CLAIMS = json.loads(+ (MODEL_HUB_FIXTURES / "released_install_claims.json").read_text(encoding="utf-8")+)["claims"]RUNTIME_INSTALL_GENERATION_A = "a" * 32RUNTIME_INSTALL_GENERATION_B = "b" * 32@@ -91,6 +94,41 @@ def _create_runtime_install_claim(return generation+ "released_claim",+ RELEASED_INSTALL_CLAIMS,+ ids=lambda claim: f"schema-{claim['schema_version']}",+)+def test_released_install_claim_is_read_without_rewrite_and_resumed_as_current_schema(+ tmp_path: Path,+ released_claim: dict[str, object],+) -> None:+ manager = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)+ managed_runtime.write_json_atomic(manager.install_state_path, released_claim)+ released_bytes = manager.install_state_path.read_bytes()++ projected = manager.install_state()++ assert projected is not None+ assert projected["target"] == RUNTIME_INSTALL_TARGET+ assert manager.install_state_path.read_bytes() == released_bytes++ assert manager.transition_install_claim(+ InstallClaimTransition.RESUME,+ generation=RUNTIME_INSTALL_GENERATION_B,+ previous_generation=RUNTIME_INSTALL_GENERATION_A,+ target=RUNTIME_INSTALL_TARGET,+ )+ persisted = json.loads(manager.install_state_path.read_text(encoding="utf-8"))+ assert persisted == {+ "schema_version": 3,+ "state": "installing",+ "generation": RUNTIME_INSTALL_GENERATION_B,+ "error_key": None,+ "target": RUNTIME_INSTALL_TARGET,+ }++def test_stream_prelude_does_not_charge_released_keepalives_to_frame_budget() -> None:keepalive = b": " + b"k" * (SSE_MAX_LINE_BYTES - 4) + b"\n\n"first = keepalive * (SSE_MAX_FRAME_BYTES // len(keepalive) + 1)@@ -677,6 +715,154 @@ def test_install_admission_fetches_an_uncached_remote_manifest(tmp_path: Path) -assert manager.contract_manifest()["assets"]+def test_released_claim_replay_ignores_unrelated_manifest_entry_without_reinstall(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ archive, binary = _write_fixture_archive(tmp_path / "fixture")+ manifest_path = _write_fixture_manifest(tmp_path / "fixture", archive, binary)+ manager = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest_path)+ installed = manager.ensure()+ assert installed["ok"] is True+ original_manifest = manager._load_manifest(allow_network=False)+ assert original_manifest is not None+ managed_runtime.write_json_atomic(+ manager.install_state_path,+ {+ "schema_version": 2,+ "state": "installing",+ "generation": RUNTIME_INSTALL_GENERATION_A,+ "error_key": None,+ "target": {+ "manifest_sha256": original_manifest.digest,+ **installed["target"],+ },+ },+ )+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))+ payload["assets"].append(+ {+ "platform": "fixture-unrelated",+ "url": "https://example.test/unrelated.tar.gz",+ "size_bytes": 1,+ "sha256": "d" * 64,+ "binary_sha256": "e" * 64,+ "bin_path": "unused",+ }+ )+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")+ pointer_path = manager.runtime_dir / "current.json"+ metadata_path = Path(installed["install_dir"]) / manager.spec.metadata_filename+ pointer_before = pointer_path.read_bytes()+ metadata_before = metadata_path.read_bytes()+ monkeypatch.setattr(+ manager,+ "_resolve_manifest_archive",+ lambda _archive: pytest.fail("released claim replay accessed an archive"),+ )+ monkeypatch.setattr(+ manager,+ "_write_current_pointer",+ lambda *_args: pytest.fail("released claim replay rewrote the pointer"),+ )++ claim = manager.install_state()+ assert claim is not None+ replayed = manager.ensure(expected_target=claim["target"])++ assert claim["target"] == installed["target"]+ assert replayed["ok"] is True+ assert replayed["changed"] is False+ assert replayed["path"] == installed["path"]+ assert pointer_path.read_bytes() == pointer_before+ assert metadata_path.read_bytes() == metadata_before+++def test_released_linux_x64_pointer_and_claim_are_admitted_by_platform_alias(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: "linux-x64")+ archive, binary = _write_fixture_archive(tmp_path / "fixture")+ manifest_path = _write_fixture_manifest(tmp_path / "fixture", archive, binary)+ manager = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest_path)+ installed = manager.ensure()+ assert installed["ok"] is True+ assert installed["target"]["platform"] == "linux-amd64"+ original_manifest = manager._load_manifest(allow_network=False)+ assert original_manifest is not None++ pointer_path = manager.runtime_dir / "current.json"+ pointer = json.loads(pointer_path.read_text(encoding="utf-8"))+ canonical_install_dir = Path(pointer["install_dir"])+ alias_platform_dir = canonical_install_dir.parent.with_name("linux-x64")+ canonical_install_dir.parent.rename(alias_platform_dir)+ alias_install_dir = alias_platform_dir / canonical_install_dir.name+ pointer["platform"] = "linux-x64"+ pointer["install_dir"] = str(alias_install_dir)+ managed_runtime.write_json_atomic(pointer_path, pointer)+ metadata_path = alias_install_dir / manager.spec.metadata_filename+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))+ metadata["platform"] = "linux-x64"+ managed_runtime.write_json_atomic(metadata_path, metadata)+ managed_runtime.write_json_atomic(+ manager.install_state_path,+ {+ "schema_version": 2,+ "state": "installing",+ "generation": RUNTIME_INSTALL_GENERATION_A,+ "error_key": None,+ "target": {+ "manifest_sha256": original_manifest.digest,+ **installed["target"],+ "platform": "linux-x64",+ },+ },+ )+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))+ payload["assets"].append(+ {+ "platform": "fixture-unrelated",+ "url": "https://example.test/unrelated.tar.gz",+ "size_bytes": 1,+ "sha256": "d" * 64,+ "binary_sha256": "e" * 64,+ "bin_path": "unused",+ }+ )+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")+ pointer_before = pointer_path.read_bytes()+ metadata_before = metadata_path.read_bytes()+ monkeypatch.setattr(+ manager,+ "_resolve_manifest_archive",+ lambda _archive: pytest.fail("alias-equivalent replay accessed an archive"),+ )+ monkeypatch.setattr(+ manager,+ "_write_current_pointer",+ lambda *_args: pytest.fail("alias-equivalent replay rewrote the pointer"),+ )++ status = manager.status()+ claim = manager.install_state()+ assert claim is not None+ replayed = manager.ensure(expected_target=claim["target"])++ assert status["installed"] is True+ assert status["version"] == "v7.2.95"+ assert status["selected_version"] == "v7.2.95"+ assert status["matches_manifest"] is True+ assert status["path"] == str(alias_install_dir / "cli-proxy-api")+ assert manager.resolve_engine_path() == alias_install_dir / "cli-proxy-api"+ assert claim["target"] == installed["target"]+ assert replayed["ok"] is True+ assert replayed["changed"] is False+ assert replayed["path"] == str(alias_install_dir / "cli-proxy-api")+ assert pointer_path.read_bytes() == pointer_before+ assert metadata_path.read_bytes() == metadata_before++@pytest.mark.parametrize("transition", tuple(InstallClaimTransition), ids=lambda item: item.value)def test_every_install_claim_transition_preserves_live_generation_ownership(tmp_path: Path,@@ -953,6 +1139,12 @@ def test_engine_installer_selects_verified_packaged_asset(assert archive.binary_sha256 == binary_sha256+def test_engine_platform_identity_is_normalized_locally() -> None:+ assert dict(runtime_installer_module._ENGINE_SPEC.platform_aliases) == runtime_installer_module._ENGINE_PLATFORM_MAP+ assert EngineRuntimeManager._normalize_engine_platform("linux-x64") == "linux-amd64"+ assert EngineRuntimeManager._normalize_engine_platform("linux-amd64") == "linux-amd64"++def test_engine_installer_is_idempotent_and_rejects_tampered_archive(tmp_path: Path) -> None:archive, binary = _write_fixture_archive(tmp_path / "good")manifest = _write_fixture_manifest(tmp_path / "good", archive, binary)@@ -1611,6 +1803,57 @@ def test_supervisor_missing_runtime_stays_installable_after_start(tmp_path: Pathassert supervisor.status()["status"]["health"] == "not_installed"+def test_supervisor_starts_disk_engine_despite_released_failure_state_and_missing_manifest(+ tmp_path: Path,+) -> None:+ source_binary = tmp_path / "fixture" / "mock-engine"+ source_binary.parent.mkdir(parents=True)+ _write_mock_engine(source_binary)+ binary = source_binary.read_text(encoding="utf-8").replace(+ "\nimport json\n",+ "\nimport sys\n"+ "if sys.argv[1:] == ['--help']:\n"+ " print('CLIProxyAPI Version: 7.2.95, Commit: fixture')\n"+ " raise SystemExit(0)\n"+ "import json\n",+ 1,+ ).encode()+ archive = tmp_path / "fixture" / "CLIProxyAPI_fixture.tar.gz"+ with tarfile.open(archive, "w:gz") as tar:+ member = tarfile.TarInfo("cli-proxy-api")+ member.mode = 0o755+ member.size = len(binary)+ tar.addfile(member, io.BytesIO(binary))+ manifest_path = _write_fixture_manifest(tmp_path / "fixture", archive, binary)+ manager = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest_path)+ installed = manager.ensure()+ assert installed["ok"] is True+ assert manager.transition_install_claim(+ InstallClaimTransition.CREATE,+ generation=RUNTIME_INSTALL_GENERATION_A,+ target=installed["target"],+ )+ assert manager.transition_install_claim(+ InstallClaimTransition.SETTLE_FAILURE,+ generation=RUNTIME_INSTALL_GENERATION_A,+ reason="model_hub_engine_manifest_missing",+ )+ manifest_path.unlink()+ manager.offline = True+ supervisor = EngineSupervisor(+ installer=manager,+ state_store=EngineStateStore(tmp_path / "state"),+ startup_timeout=5,+ )++ assert manager.status()["installed"] is True+ assert supervisor.status()["status"]["health"] == "not_started"+ connection = supervisor.ensure_running()+ assert connection.base_url.startswith("http://127.0.0.1:")+ assert supervisor.status()["status"]["health"] == "ok"+ supervisor.stop()++def test_supervisor_keeps_installing_state_unverified_until_settlement(tmp_path: Path,) -> None:diff --git a/vibe/api.py b/vibe/api.pyindex 4ac3ccca4..3d6911902 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -8487,7 +8487,12 @@ def dependencies_status(*, offline: bool = False) -> dict:"kind": "runtime","required": memory_required,"installed": bool(memory_runtime.get("installed")),- "version": memory_manifest.get("everos_version"),+ "version": memory_runtime.get("version"),+ "latest_version": memory_runtime.get("selected_version"),+ "has_update": bool(+ memory_runtime.get("installed")+ and memory_runtime.get("matches_manifest") is False+ ),"status": _memory_runtime_dependency_status(memory_runtime),"reason": memory_runtime.get("reason"),"release_state": release_state if release_state in {"published", "unavailable"} else None,diff --git a/vibe/model_hub_runtime/installer.py b/vibe/model_hub_runtime/installer.pyindex 7f976c109..bec3f83ea 100644--- a/vibe/model_hub_runtime/installer.py+++ b/vibe/model_hub_runtime/installer.py@@ -35,20 +35,23 @@ _ENGINE_PLATFORM_MAP = {"linux-arm64": "linux-arm64",}_ENGINE_ASSET_PLATFORMS = frozenset(_ENGINE_PLATFORM_MAP.values())-_INSTALL_STATE_SCHEMA_VERSION = 2-_INSTALL_STATE_SUPPORTED_SCHEMA_VERSIONS = frozenset({1, _INSTALL_STATE_SCHEMA_VERSION})+_INSTALL_STATE_SCHEMA_VERSION = 3+_INSTALL_STATE_RELEASED_SCHEMA_VERSIONS = frozenset({1, 2})+_INSTALL_STATE_SUPPORTED_SCHEMA_VERSIONS = frozenset(+ {*_INSTALL_STATE_RELEASED_SCHEMA_VERSIONS, _INSTALL_STATE_SCHEMA_VERSION}+)_INSTALL_FAILURE_KEY = "settings.models.install.fail.detail"_INSTALL_CLAIM_INVALID_REASON = "model_hub_engine_install_claim_invalid"_INSTALL_GENERATION_RE = re.compile(r"^[0-9a-f]{32}$")_INSTALL_TARGET_FIELDS = frozenset({- "manifest_sha256","runtime_version","platform","archive_sha256","binary_sha256",})+_RELEASED_INSTALL_TARGET_FIELDS = frozenset({*_INSTALL_TARGET_FIELDS, "manifest_sha256"})_INSTALL_STATE_UNSET = object()_ENGINE_SPEC = ManagedRuntimeSpec(runtime_id="model_hub_engine",@@ -57,6 +60,7 @@ _ENGINE_SPEC = ManagedRuntimeSpec(default_bin_path="cli-proxy-api",archives_field="assets",archive_size_field="size_bytes",+ platform_aliases=tuple(_ENGINE_PLATFORM_MAP.items()),)@@ -117,7 +121,10 @@ class EngineRuntimeManager(ManagedRuntimeManager):return self.runtime_dir / ".install-state.lock"def host_platform(self) -> str:- platform_tag = managed_runtime.runtime_platform_tag()+ return self._normalize_engine_platform(managed_runtime.runtime_platform_tag())++ @staticmethod+ def _normalize_engine_platform(platform_tag: str) -> str:return _ENGINE_PLATFORM_MAP.get(platform_tag, platform_tag)def install_failure_reasons(self) -> frozenset[str]:@@ -249,7 +256,10 @@ class EngineRuntimeManager(ManagedRuntimeManager):if state == "installing" and error_key is not None:logger.warning("Ignoring contradictory Model Hub runtime install state")return None- target = self._validated_install_target(payload.get("target"))+ target = self._validated_install_target(+ payload.get("target"),+ schema_version=int(payload["schema_version"]),+ )generation = payload.get("generation")if generation is not None and (not isinstance(generation, str) or not _INSTALL_GENERATION_RE.fullmatch(generation)@@ -309,9 +319,18 @@ class EngineRuntimeManager(ManagedRuntimeManager):else:self._install_state_override = _INSTALL_STATE_UNSET- @staticmethod- def _validated_install_target(value: object) -> dict[str, str] | None:- if not isinstance(value, Mapping) or set(value) != _INSTALL_TARGET_FIELDS:+ def _validated_install_target(+ self,+ value: object,+ *,+ schema_version: int = _INSTALL_STATE_SCHEMA_VERSION,+ ) -> dict[str, str] | None:+ expected_fields = (+ _RELEASED_INSTALL_TARGET_FIELDS+ if schema_version in _INSTALL_STATE_RELEASED_SCHEMA_VERSIONS+ else _INSTALL_TARGET_FIELDS+ )+ if not isinstance(value, Mapping) or set(value) != expected_fields:return Nonetarget: dict[str, str] = {}for field in _INSTALL_TARGET_FIELDS:@@ -319,7 +338,12 @@ class EngineRuntimeManager(ManagedRuntimeManager):if not isinstance(item, str) or not item:return Nonetarget[field] = item- return target+ return self._normalized_install_target(target)++ def _normalized_install_target(self, target: Mapping[str, str]) -> dict[str, str]:+ normalized = super()._normalized_install_target(target)+ normalized["platform"] = self._normalize_engine_platform(normalized["platform"])+ return normalized@staticmethoddef _failed_install_state(diff --git a/vibe/model_hub_runtime/supervisor.py b/vibe/model_hub_runtime/supervisor.pyindex 4c24b5bd7..423705a9c 100644--- a/vibe/model_hub_runtime/supervisor.py+++ b/vibe/model_hub_runtime/supervisor.py@@ -111,7 +111,11 @@ class EngineSupervisor:health = "ok" if self._healthy_locked() else "degraded"elif install_state and install_state.get("state") == "installing":health = "installing"- elif install_state and install_state.get("state") == "not_installed":+ elif (+ not installed+ and install_state+ and install_state.get("state") == "not_installed"+ ):health = "not_installed"elif installed:health = "down" if self._start_attempted else "not_started"