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
refactor(show): delete parallel runtime installer (#1737)
Call White0eb15bea2f57
diff --git a/core/managed_runtime.py b/core/managed_runtime.pyindex cda24e7b6..79ba71e5e 100644--- a/core/managed_runtime.py+++ b/core/managed_runtime.py@@ -193,6 +193,7 @@ class ManagedRuntimeManager:message=f"{self.spec.runtime_id} install or repair is already running; try again shortly.",skipped=True,)+ published_result: dict[str, Any] | None = Nonetry:manifest = self._load_manifest(allow_network=not self.offline)if manifest is None:@@ -249,7 +250,12 @@ class ManagedRuntimeManager:existing = candidatebreakif existing is not None and not force:- return self._reuse_existing_install(existing, 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:@@ -330,7 +336,7 @@ class ManagedRuntimeManager:self._write_current_pointer(install_dir, manifest, archive)candidate_install_dir = Noneself._install_reason = None- return {+ published_result = {**self._success_payload(installed_binary,install_dir,@@ -340,6 +346,7 @@ class ManagedRuntimeManager:),"preparation": preparation,}+ return published_resultexcept Exception as exc: # noqa: BLE001if candidate_install_dir is not None:shutil.rmtree(candidate_install_dir, ignore_errors=True)@@ -354,6 +361,24 @@ class ManagedRuntimeManager:shutil.rmtree(staging_dir, ignore_errors=True)finally:self._release_mutation_lock(file_lock)+ if published_result is not None and published_result.get("ok"):+ try:+ self._clean_after_successful_install()+ except Exception: # noqa: BLE001+ logger.warning(+ "Managed %s runtime post-install cleanup failed",+ self.spec.runtime_id,+ exc_info=True,+ )++ def _clean_after_successful_install(self) -> None:+ result = self.clean(keep_previous=1)+ if not result.get("ok"):+ logger.warning(+ "Managed %s runtime post-install cleanup was incomplete: %s",+ self.spec.runtime_id,+ result.get("reason"),+ )def _failure_for_install_exception(self,diff --git a/core/show_runtime.py b/core/show_runtime.pyindex 38ff4b0f5..4e692f996 100644--- a/core/show_runtime.py+++ b/core/show_runtime.py@@ -10,7 +10,6 @@ import importlib.resources as package_resourcesimport jsonimport loggingimport os-import platformimport randomimport reimport shlex@@ -27,7 +26,6 @@ import urllib.requestfrom dataclasses import dataclass, replacefrom enum import Enumfrom pathlib import Path-from sysconfig import get_platformfrom typing import Any, Iterable, Iterator, Mappingimport httpx@@ -42,12 +40,17 @@ from storage.lock import ()from config import paths-from core.dependency_network import dependency_error_details, fetch_bytes, fetch_to_path, probe_url, redact_url+from core.dependency_network import dependency_error_details, fetch_to_path, probe_url, redact_urlfrom core.managed_runtime import (ManagedRuntimeArchive,ManagedRuntimeManager,ManagedRuntimeManifest,ManagedRuntimeSpec,+ env_flag_enabled,+ file_sha256,+ runtime_platform_tag,+ safe_extract_tar,+ safe_path_part,)from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_treefrom core.show_runtime_failures import (@@ -72,8 +75,6 @@ _RUNTIME_SOURCE_NPM = "npm"_WARNED_RETIRED_RUNTIME_SOURCES: set[str] = set()_RUNTIME_MANIFEST_RESOURCE = "show_runtime_manifest.json"_PACKAGED_RUNTIME_MANIFEST_SOURCE = f"package:{_RUNTIME_MANIFEST_RESOURCE}"-_CUSTOM_MANIFEST_LINEAGE = "*custom*"-_MANAGED_RUNTIME_ROLLBACK_INSTALLS = 1_CONTENT_ADDRESSED_ARCHIVE_RE = re.compile(r"^[0-9a-f]{64}\.tgz$")_ABANDONED_ARCHIVE_CLAIM_RE = re.compile(r"^[0-9a-f]{64}\.tgz\.avibe-removing$")# Cross-process safety window: between a download finalizing ``<sha256>.tgz``@@ -257,25 +258,6 @@ class _ManagedInstallAttempt:raise ValueError("failed install attempt requires an operation reason")-@dataclass(frozen=True)-class ShowRuntimeArchive:- platform: str- name: str- url: str- sha256: str- size: int | None = None---@dataclass(frozen=True)-class ShowRuntimeManifest:- schema_version: int- runtime_version: str- minimum_node: str | None- archives: dict[str, ShowRuntimeArchive]- digest: str- source: str--@dataclass(frozen=True)class _ShowRuntimeDiskInstall:install_dir: Path@@ -699,7 +681,7 @@ class _ShowManifestRuntimeManager(ManagedRuntimeManager):parts = install_dir.relative_to((self.runtime_dir / "versions").resolve()).partsexcept (OSError, ValueError):return False- expected_prefix = (_safe_path_part(runtime_version), _safe_path_part(platform_tag))+ expected_prefix = (safe_path_part(runtime_version), safe_path_part(platform_tag))if parts[:2] != expected_prefix:return Falseif len(parts) == 2:@@ -789,7 +771,7 @@ class ShowRuntimeManager:configured_archive_url = archive_url if archive_url is not None else archive_url_envself.archive_url = configured_archive_url if configured_archive_url is not None else _default_runtime_archive_url()self._archive_url_provenance = "configured" if configured_archive_url is not None else "packaged"- self.offline = _env_flag_enabled("VIBE_SHOW_RUNTIME_OFFLINE", default=False) if offline is None else offline+ self.offline = env_flag_enabled("VIBE_SHOW_RUNTIME_OFFLINE", default=False) if offline is None else offlineself.force_install = force_installself.stdout_path = self.runtime_dir / "stdout.log"self.stderr_path = self.runtime_dir / "stderr.log"@@ -1710,7 +1692,7 @@ class ShowRuntimeManager:return Nonedef _managed_install_opt_out_reason(self, *, automatic: bool) -> str | None:- if automatic and _env_flag_enabled(+ if automatic and env_flag_enabled("VIBE_INSTALL_SKIP_SHOW_RUNTIME",default=False,):@@ -1887,7 +1869,6 @@ class ShowRuntimeManager:return _ManagedInstallAttempt(None, self._install_reason)if command:self._download_error = None- self._clean_after_managed_install(command)return _ManagedInstallAttempt(command)return _ManagedInstallAttempt(None, self._install_reason or "runtime_install_failed")@@ -1912,28 +1893,6 @@ class ShowRuntimeManager:self._install_evidence = evidenceself._download_error = download_error- def _clean_after_managed_install(self, command: list[str]) -> None:- try:- if self.runtime_source == _RUNTIME_SOURCE_MANIFEST:- result = self._shared_manifest_manager(offline=True).clean(- keep_previous=_MANAGED_RUNTIME_ROLLBACK_INSTALLS,- )- removed = result.get("removed", [])- if removed:- logger.info("Removed %d stale managed Show Runtime install(s)", len(removed))- archives = result.get("archives", {})- else:- archives = self._clean_downloaded_archives()- if archives.get("removed_count"):- logger.info(- "Removed %d stale Show Runtime archive(s), reclaimed %d byte(s)",- archives["removed_count"],- archives["removed_bytes"],- )- except Exception:- # Cache cleanup must never turn a usable runtime install into a failed prepare.- logger.warning("Failed to clean stale managed Show Runtime installs", exc_info=True)-def status(self, *, offline: bool | None = None) -> dict[str, Any]:explicit_availability = (self._resolve_explicit_command_availability()@@ -1952,7 +1911,7 @@ class ShowRuntimeManager:if manifest_manager is not Noneelse None)- archive: ManagedRuntimeArchive | ShowRuntimeArchive | None = (+ archive: ManagedRuntimeArchive | None = (manifest_manager.archive_for_platform(manifest)if manifest_manager is not None and manifest is not Noneelse None@@ -1966,7 +1925,7 @@ class ShowRuntimeManager:if manifest_manager is not Noneelse None)- platform_tag = _runtime_platform_tag()+ platform_tag = runtime_platform_tag()node = _resolve_node_command()node_version = _node_version(node) if node else Noneminimum_node = (@@ -2375,22 +2334,7 @@ class ShowRuntimeManager:if not dry_run:shutil.rmtree(path, ignore_errors=True)removed.append(str(path))- self._clean_manifest_install_dirs(- keep_previous=keep_previous,- dry_run=dry_run,- removed=removed,- )- # A dry run leaves stale install dirs in place, so their metadata- # would still read as "protected" below. Skip metadata under the- # dirs a real run would remove, so the archive preview matches- # the real outcome. Hold the preview guard through this phase so- # an install starting after staging enumeration cannot expose an- # in-flight archive as reclaimable.- skip_metadata_under = {Path(path) for path in removed} if dry_run else None- archives = self._clean_downloaded_archives(- dry_run=dry_run,- skip_metadata_under=skip_metadata_under,- )+ archives = self._clean_downloaded_archives(dry_run=dry_run)if dry_run and self._preview_raced_busy():return {"ok": False,@@ -2798,152 +2742,6 @@ class ShowRuntimeManager:"skipped_reason": reason,}- def _clean_manifest_install_dirs(- self,- *,- keep_previous: int,- manifest_source: str | None = None,- protected_install_dirs: set[Path] | None = None,- dry_run: bool = False,- removed: list[str] | None = None,- ) -> list[str]:- if removed is None:- removed = []- versions_dir = self.runtime_dir / "versions"- if not versions_dir.is_dir():- return removed- protected = set(protected_install_dirs or ())- current_install_dir = self._current_manifest_install_dir(versions_dir)- if current_install_dir is not None:- protected.add(current_install_dir)- install_dirs = self._manifest_install_dirs(versions_dir, manifest_source=manifest_source)- all_manifest_install_dirs = self._manifest_install_dirs(versions_dir)- sorted_install_dirs = sorted(install_dirs, key=lambda path: path.stat().st_mtime, reverse=True)- resolved_install_dirs = {path: path.resolve() for path in install_dirs}- all_resolved_install_dirs = {path: path.resolve() for path in all_manifest_install_dirs}- rollback_candidates = [- path- for path in sorted_install_dirs- if not any(- resolved_install_dirs[path] in other_resolved.parents- for other, other_resolved in resolved_install_dirs.items()- if other != path- )- ]- kept_previous = 0- for path in rollback_candidates:- path_resolved = resolved_install_dirs[path]- if self._install_dir_overlaps_protected(path_resolved, protected):- continue- if kept_previous < keep_previous:- kept_previous += 1- protected.add(path_resolved)- removable_install_dirs = [- path- for path, path_resolved in resolved_install_dirs.items()- if not self._install_dir_overlaps_protected(path_resolved, protected)- ]- removable_resolved_install_dirs = {resolved_install_dirs[path] for path in removable_install_dirs}- safe_removable_install_dirs = [- path- for path in removable_install_dirs- if not any(- resolved_install_dirs[path] in other_resolved.parents- and other_resolved not in removable_resolved_install_dirs- for other_resolved in all_resolved_install_dirs.values()- )- ]- for path in sorted(safe_removable_install_dirs, key=lambda item: len(resolved_install_dirs[item].parts), reverse=True):- if not path.is_dir():- continue- if not dry_run:- shutil.rmtree(path, ignore_errors=True)- removed.append(str(path))- if not dry_run:- self._prune_empty_manifest_version_dirs(versions_dir)- return removed-- @staticmethod- def _install_dir_overlaps_protected(path_resolved: Path, protected: set[Path]) -> bool:- return any(- path_resolved == item or path_resolved in item.parents or item in path_resolved.parents- for item in protected- )-- def _manifest_install_dirs(self, versions_dir: Path, *, manifest_source: str | None = None) -> set[Path]:- install_dirs: set[Path] = set()- for pattern in ("*/*/.vibe-show-runtime.json", "*/*/*/.vibe-show-runtime.json"):- for metadata_path in versions_dir.glob(pattern):- if not metadata_path.parent.is_dir():- continue- if manifest_source is not None:- try:- metadata = json.loads(metadata_path.read_text(encoding="utf-8"))- except Exception:- continue- if metadata.get("provider") != _RUNTIME_SOURCE_MANIFEST:- continue- source = metadata.get("manifest_source")- if manifest_source == _CUSTOM_MANIFEST_LINEAGE:- if source == _PACKAGED_RUNTIME_MANIFEST_SOURCE:- continue- elif source != manifest_source:- continue- install_dirs.add(metadata_path.parent)- return install_dirs-- def _current_manifest_install_dir(self, versions_dir: Path) -> Path | None:- try:- pointer = json.loads((self.runtime_dir / "current.json").read_text(encoding="utf-8"))- pointer_install_dir = Path(str(pointer.get("install_dir") or "")).resolve()- if versions_dir.resolve() in pointer_install_dir.parents:- return pointer_install_dir- except Exception:- pass- return None-- def _manifest_source_for_install_dirs(self, install_dirs: set[Path]) -> str | None:- for install_dir in install_dirs:- try:- metadata = json.loads(self._manifest_metadata_path(install_dir).read_text(encoding="utf-8"))- except Exception:- continue- source = metadata.get("manifest_source")- if isinstance(source, str) and source:- return source- if self.manifest_path is None and self.manifest_url is None:- return _PACKAGED_RUNTIME_MANIFEST_SOURCE- return None-- def _manifest_install_dirs_for_command(self, command: list[str]) -> set[Path]:- versions_dir = self.runtime_dir / "versions"- if not versions_dir.is_dir():- return set()- install_dirs = self._manifest_install_dirs(versions_dir)- matching_install_dirs: set[Path] = set()- for command_part in command:- try:- command_path = Path(command_part).resolve()- except (OSError, RuntimeError):- continue- for install_dir in install_dirs:- install_dir_resolved = install_dir.resolve()- if install_dir_resolved == command_path or install_dir_resolved in command_path.parents:- matching_install_dirs.add(install_dir_resolved)- return {- path- for path in matching_install_dirs- if not any(path in other.parents for other in matching_install_dirs if other != path)- }-- def _prune_empty_manifest_version_dirs(self, versions_dir: Path) -> None:- for path in sorted(versions_dir.glob("*/*"), reverse=True):- if path.is_dir() and not any(path.iterdir()):- path.rmdir()- for path in sorted(versions_dir.iterdir(), reverse=True):- if path.is_dir() and not any(path.iterdir()):- path.rmdir()-def prepare(self,*,@@ -2966,7 +2764,7 @@ class ShowRuntimeManager:payload.update({"provider": self.runtime_source,- "platform": _runtime_platform_tag(),+ "platform": runtime_platform_tag(),"status": self.status(offline=status_offline),})@@ -2979,101 +2777,6 @@ class ShowRuntimeManager:return self.manifest_urlreturn _PACKAGED_RUNTIME_MANIFEST_SOURCE- def _persisted_manifest_disk_install(self) -> _ShowRuntimeDiskInstall | None:- """Resolve the current manifest install without consulting the manifest source."""- try:- pointer = json.loads((self.runtime_dir / "current.json").read_text(encoding="utf-8"))- if not isinstance(pointer, dict) or pointer.get("provider") != _RUNTIME_SOURCE_MANIFEST:- return None-- versions_dir = self.runtime_dir / "versions"- versions_stat = versions_dir.lstat()- if _is_reparse_point(versions_stat) or not stat.S_ISDIR(versions_stat.st_mode):- return None- versions_resolved = versions_dir.resolve(strict=True)-- pointer_install_dir = pointer.get("install_dir")- if not isinstance(pointer_install_dir, str) or not pointer_install_dir:- return None- install_dir = Path(pointer_install_dir).resolve(strict=True)- if versions_resolved not in install_dir.parents:- return None- install_stat = install_dir.lstat()- if _is_reparse_point(install_stat) or not stat.S_ISDIR(install_stat.st_mode):- return None-- metadata_path = self._manifest_metadata_path(install_dir)- metadata_stat = metadata_path.lstat()- if _is_reparse_point(metadata_stat) or not stat.S_ISREG(metadata_stat.st_mode):- return None- metadata = json.loads(metadata_path.read_text(encoding="utf-8"))- if not isinstance(metadata, dict) or metadata.get("provider") != _RUNTIME_SOURCE_MANIFEST:- return None-- runtime_version = metadata.get("runtime_version")- platform_tag = metadata.get("platform")- manifest_sha256 = metadata.get("manifest_sha256")- archive_sha256 = metadata.get("archive_sha256")- archive_name = metadata.get("archive_name")- if not all(- isinstance(value, str) and value- for value in (runtime_version, platform_tag, manifest_sha256, archive_sha256, archive_name)- ):- return None- if platform_tag != _runtime_platform_tag():- return None- if metadata.get("manifest_source") != self._configured_manifest_source():- return None- if not _CONTENT_ADDRESSED_ARCHIVE_RE.fullmatch(f"{manifest_sha256}.tgz"):- return None- if not _CONTENT_ADDRESSED_ARCHIVE_RE.fullmatch(f"{archive_sha256}.tgz"):- return None- pointer_manifest_sha256 = pointer.get("manifest_sha256")- if not isinstance(pointer_manifest_sha256, str) or not _CONTENT_ADDRESSED_ARCHIVE_RE.fullmatch(- f"{pointer_manifest_sha256}.tgz"- ):- return None- # The pointer may name a newer manifest that adopted an old-layout- # install after only another platform changed. The serving identity- # deliberately excludes the whole-manifest digest, so agreement is- # required only for the fields that identify this platform's bytes.- for field in ("runtime_version", "platform", "archive_sha256"):- if pointer.get(field) != metadata.get(field):- return None-- relative_parts = install_dir.relative_to(versions_resolved).parts- expected_prefix = (_safe_path_part(runtime_version), _safe_path_part(platform_tag))- if relative_parts[:2] != expected_prefix:- return None- if len(relative_parts) == 2:- pass- elif len(relative_parts) == 3:- current_fingerprint = hashlib.sha256(- f"{runtime_version}:{platform_tag}:{archive_sha256}".encode("utf-8")- ).hexdigest()[:16]- previous_fingerprint = hashlib.sha256(- f"{manifest_sha256}:{archive_sha256}".encode("utf-8")- ).hexdigest()[:16]- if relative_parts[2] not in {current_fingerprint, previous_fingerprint}:- return None- else:- return None-- cli_path = install_dir / "node_modules" / "@avibe" / "show-runtime" / "dist" / "cli.js"- cli_stat = cli_path.lstat()- if _is_reparse_point(cli_stat) or not stat.S_ISREG(cli_stat.st_mode):- return None- cli_resolved = cli_path.resolve(strict=True)- if install_dir not in cli_resolved.parents:- return None- node = _resolve_node_command()- command = [*node, str(cli_resolved)] if node else None- status_metadata = dict(metadata)- status_metadata["manifest_sha256"] = pointer_manifest_sha256- return _ShowRuntimeDiskInstall(install_dir=install_dir, command=command, metadata=status_metadata)- except (OSError, RuntimeError, TypeError, ValueError):- return None-def _installed_manifest_runtime_command(self, *, offline: bool | None = None) -> list[str] | None:node = _resolve_node_command()if not node:@@ -3313,282 +3016,6 @@ class ShowRuntimeManager:replacement_completed=bool(force and result.get("changed")),)- def _load_runtime_manifest(self, *, offline: bool | None = None) -> ShowRuntimeManifest | None:- payload: bytes | None = None- source = ""- provenance = "configured" if self.manifest_path or self.manifest_url else "packaged"- if self.manifest_path:- try:- exists = self.manifest_path.exists()- payload = self.manifest_path.read_bytes() if exists else None- except OSError:- self._record_install_failure("runtime_manifest_invalid", provenance=provenance)- return None- if payload is None:- self._record_install_failure("runtime_manifest_missing", provenance=provenance)- return None- source = str(self.manifest_path)- elif self.manifest_url:- if self.offline if offline is None else offline:- self._install_reason = "runtime_manifest_unavailable_offline"- return None- try:- payload = fetch_bytes(- self.manifest_url,- timeout=30,- opener=urllib.request.urlopen,- )- source = self.manifest_url- except Exception as exc:- logger.exception("Failed to download Show Runtime manifest from %s", self.manifest_url)- self._record_download_failure(- "runtime_manifest_download_failed",- exc,- self.manifest_url,- provenance="configured",- )- return None- else:- try:- resource = package_resources.files("vibe").joinpath(_RUNTIME_MANIFEST_RESOURCE)- except Exception:- resource = None- try:- payload = resource.read_bytes() if resource is not None and resource.is_file() else None- except OSError:- payload = None- if payload is None:- self._record_install_failure("runtime_manifest_missing", provenance=provenance)- return None- source = _PACKAGED_RUNTIME_MANIFEST_SOURCE- digest = hashlib.sha256(payload).hexdigest()- try:- data = json.loads(payload.decode("utf-8"))- archives = {- platform_tag: ShowRuntimeArchive(- platform=platform_tag,- name=str(item["name"]),- url=str(item["url"]),- sha256=str(item["sha256"]),- size=int(item["size"]) if item.get("size") is not None else None,- )- for platform_tag, item in (data.get("archives") or {}).items()- if isinstance(item, dict)- }- manifest = ShowRuntimeManifest(- schema_version=int(data.get("schema_version")),- runtime_version=str(data.get("runtime_version") or ""),- minimum_node=str(data.get("minimum_node") or "") or None,- archives=archives,- digest=digest,- source=source,- )- except Exception:- self._record_install_failure("runtime_manifest_invalid", provenance=provenance)- return None- if manifest.schema_version != 1 or not manifest.runtime_version or not manifest.archives:- self._record_install_failure("runtime_manifest_invalid", provenance=provenance)- return None- return manifest-- def _manifest_node_supported(self, node: list[str], manifest: ShowRuntimeManifest) -> bool:- if not manifest.minimum_node:- return True- version = _node_version(node)- if _node_satisfies_requirement(version, manifest.minimum_node):- return True- self._install_reason = "runtime_node_unsupported"- return False-- def _manifest_archive_for_platform(self, manifest: ShowRuntimeManifest) -> ShowRuntimeArchive | None:- platform_tag = _runtime_platform_tag()- archive = manifest.archives.get(platform_tag)- if not archive:- self._install_reason = "runtime_platform_unsupported"- return None- return archive-- def _resolve_manifest_archive(- self,- archive: ShowRuntimeArchive,- *,- offline: bool | None = None,- provenance: str,- ) -> Path | None:- cached = self.runtime_dir / "downloads" / f"{archive.sha256}.tgz"- if cached.exists() and self._downloaded_archive_matches(cached, archive):- self._download_error = None- return cached- if self.offline if offline is None else offline:- self._install_reason = "runtime_archive_unavailable_offline"- return None- parsed = urllib.parse.urlparse(archive.url)- if parsed.scheme not in {"https", "file"}:- self._install_reason = "runtime_archive_url_unsupported"- return None- tmp_path = cached.with_suffix(".tmp")- cached.parent.mkdir(parents=True, exist_ok=True)- try:- fetch_to_path(- archive.url,- tmp_path,- timeout=60,- opener=urllib.request.urlopen,- )- if not self._downloaded_archive_matches(tmp_path, archive):- tmp_path.unlink(missing_ok=True)- return None- tmp_path.replace(cached)- self._download_error = None- return cached- except Exception as exc:- logger.exception("Failed to download Show Runtime archive from %s", archive.url)- tmp_path.unlink(missing_ok=True)- self._record_download_failure(- "runtime_archive_download_failed",- exc,- archive.url,- provenance=provenance,- )- return None-- def _downloaded_archive_matches(self, path: Path, archive: ShowRuntimeArchive) -> bool:- if archive.size is not None and path.stat().st_size != archive.size:- self._install_reason = "runtime_archive_size_mismatch"- return False- if _file_sha256(path) != archive.sha256:- self._install_reason = "runtime_archive_checksum_mismatch"- return False- return True-- def _manifest_install_dir(self, manifest: ShowRuntimeManifest, archive: ShowRuntimeArchive) -> Path:- fingerprint = hashlib.sha256(- f"{manifest.runtime_version}:{archive.platform}:{archive.sha256}".encode("utf-8")- ).hexdigest()[:16]- return (- self.runtime_dir- / "versions"- / _safe_path_part(manifest.runtime_version)- / _safe_path_part(archive.platform)- / fingerprint- )-- def _legacy_manifest_install_dir(self, manifest: ShowRuntimeManifest, archive: ShowRuntimeArchive) -> Path:- return self.runtime_dir / "versions" / _safe_path_part(manifest.runtime_version) / _safe_path_part(archive.platform)-- def _manifest_install_candidates(- self,- manifest: ShowRuntimeManifest,- archive: ShowRuntimeArchive,- ) -> Iterator[Path]:- install_dir = self._manifest_install_dir(manifest, archive)- legacy_install_dir = self._legacy_manifest_install_dir(manifest, archive)- yield install_dir- yield legacy_install_dir-- # Releases before the platform-scoped identity used the manifest digest- # in this child directory's fingerprint. Metadata proves that layout.- try:- candidates = sorted(legacy_install_dir.iterdir(), key=lambda path: path.name)- except OSError:- return- for candidate in candidates:- if candidate == install_dir:- continue- try:- payload = json.loads(self._manifest_metadata_path(candidate).read_text(encoding="utf-8"))- except Exception:- continue- previous_manifest_sha256 = payload.get("manifest_sha256")- if not isinstance(previous_manifest_sha256, str) or not _CONTENT_ADDRESSED_ARCHIVE_RE.fullmatch(- f"{previous_manifest_sha256}.tgz"- ):- continue- previous_fingerprint = hashlib.sha256(- f"{previous_manifest_sha256}:{archive.sha256}".encode("utf-8")- ).hexdigest()[:16]- if candidate.name == previous_fingerprint:- yield candidate-- def _manifest_metadata_path(self, install_dir: Path) -> Path:- return install_dir / ".vibe-show-runtime.json"-- def _verified_manifest_runtime_command(- self,- install_dir: Path,- manifest: ShowRuntimeManifest,- archive: ShowRuntimeArchive,- node: list[str],- ) -> list[str] | None:- command = self._manifest_runtime_command(install_dir, node)- if command and self._manifest_install_matches(install_dir, manifest, archive):- return command- return None-- def _verified_manifest_runtime_command_for_manifest(- self,- manifest: ShowRuntimeManifest,- archive: ShowRuntimeArchive,- node: list[str],- ) -> list[str] | None:- for install_dir in self._manifest_install_candidates(manifest, archive):- command = self._verified_manifest_runtime_command(install_dir, manifest, archive, node)- if command:- return command- return None-- def _manifest_install_matches(self, install_dir: Path, manifest: ShowRuntimeManifest, archive: ShowRuntimeArchive) -> bool:- try:- payload = json.loads(self._manifest_metadata_path(install_dir).read_text(encoding="utf-8"))- except Exception:- return False- return (- payload.get("provider") == _RUNTIME_SOURCE_MANIFEST- and payload.get("runtime_version") == manifest.runtime_version- and payload.get("platform") == archive.platform- and payload.get("archive_sha256") == archive.sha256- )-- def _write_manifest_install_metadata(self, install_dir: Path, manifest: ShowRuntimeManifest, archive: ShowRuntimeArchive) -> None:- self._manifest_metadata_path(install_dir).write_text(- json.dumps(- {- "provider": _RUNTIME_SOURCE_MANIFEST,- "manifest_sha256": manifest.digest,- "runtime_version": manifest.runtime_version,- "platform": archive.platform,- "archive_name": archive.name,- "archive_sha256": archive.sha256,- "manifest_source": manifest.source,- },- sort_keys=True,- )- + "\n",- encoding="utf-8",- )-- def _write_current_manifest_pointer(self, manifest: ShowRuntimeManifest, archive: ShowRuntimeArchive, install_dir: Path) -> None:- pointer = self.runtime_dir / "current.json"- pointer.parent.mkdir(parents=True, exist_ok=True)- pointer.write_text(- json.dumps(- {- "provider": _RUNTIME_SOURCE_MANIFEST,- "runtime_version": manifest.runtime_version,- "platform": archive.platform,- "install_dir": str(install_dir),- "manifest_sha256": manifest.digest,- "archive_sha256": archive.sha256,- },- sort_keys=True,- )- + "\n",- encoding="utf-8",- )-- def _manifest_runtime_command(self, install_dir: Path, node: list[str]) -> list[str] | None:- return self._archive_runtime_command(install_dir, node)-def _installed_archive_runtime_command(self) -> list[str] | None:node = _resolve_node_command()if not node:@@ -3609,7 +3036,7 @@ class ShowRuntimeManager:existing_command,replacement_required=force,)- archive_digest = _file_sha256(archive)+ archive_digest = file_sha256(archive)if not force and existing_command and self._archive_manifest_matches(archive_digest):return self._managed_install_operation_command(existing_command,@@ -3618,7 +3045,7 @@ class ShowRuntimeManager:tmp_dir = Path(tempfile.mkdtemp(prefix="prebuilt-", dir=self.runtime_dir))try:with tarfile.open(archive, "r:gz") as tar:- _safe_extract_tar(tar, tmp_dir)+ safe_extract_tar(tar, tmp_dir)command = self._archive_runtime_command(tmp_dir, node)if not command:self._install_reason = "runtime_install_missing_bin"@@ -4043,13 +3470,6 @@ def _auto_install_enabled() -> bool:return value is None or value.strip().lower() not in _FALSE_VALUES-def _env_flag_enabled(name: str, *, default: bool) -> bool:- value = os.environ.get(name)- if value is None:- return default- return value.strip().lower() not in _FALSE_VALUES--def _packaged_runtime_manifest_exists() -> bool:try:resource = package_resources.files("vibe").joinpath(_RUNTIME_MANIFEST_RESOURCE)@@ -4080,23 +3500,15 @@ def _normalize_runtime_source(value: str | None) -> str:return aliases.get(normalized, normalized or _RUNTIME_SOURCE_MANIFEST)-def _manifest_status_payload(- manifest: ManagedRuntimeManifest | ShowRuntimeManifest | None,-) -> dict[str, Any] | None:+def _manifest_status_payload(manifest: ManagedRuntimeManifest | None) -> dict[str, Any] | None:if manifest is None:return None- if isinstance(manifest, ManagedRuntimeManifest):- minimum_node = _ShowManifestRuntimeManager._minimum_node(manifest)- source = manifest.loaded_from- else:- minimum_node = manifest.minimum_node- source = manifest.sourcereturn {"schema_version": manifest.schema_version,"runtime_version": manifest.runtime_version,- "minimum_node": minimum_node,+ "minimum_node": _ShowManifestRuntimeManager._minimum_node(manifest),"sha256": manifest.digest,- "source": source,+ "source": manifest.loaded_from,"platforms": sorted(manifest.archives),}@@ -4135,9 +3547,7 @@ def _runtime_download_error(exc: BaseException, url: str) -> dict[str, Any]:return dependency_error_details(exc, url)-def _archive_status_payload(- archive: ManagedRuntimeArchive | ShowRuntimeArchive | None,-) -> dict[str, Any] | None:+def _archive_status_payload(archive: ManagedRuntimeArchive | None) -> dict[str, Any] | None:if archive is None:return Nonereturn {@@ -4150,72 +3560,13 @@ def _archive_status_payload(def _runtime_archive_name() -> str:- return f"{_RUNTIME_ARCHIVE_PREFIX}-{_runtime_platform_tag()}.tgz"+ return f"{_RUNTIME_ARCHIVE_PREFIX}-{runtime_platform_tag()}.tgz"def _default_runtime_archive_url() -> str:return f"{_RUNTIME_ARCHIVE_RELEASE_BASE_URL}/{_runtime_archive_name()}"-def _runtime_platform_tag() -> str:- raw = get_platform().lower()- machine = raw.rsplit("-", 1)[-1]- if machine == "universal2":- machine = platform.machine().lower()- if machine in {"amd64", "x86_64"}:- arch = "x64"- elif machine in {"arm64", "aarch64"}:- arch = "arm64"- else:- arch = machine- if raw.startswith("macosx"):- os_name = "darwin"- elif raw.startswith("linux"):- os_name = "linux"- elif raw.startswith("win"):- os_name = "win32"- else:- os_name = os.name- return f"{os_name}-{arch}"---def _safe_extract_tar(tar: tarfile.TarFile, destination: Path) -> None:- destination_resolved = destination.resolve()- for member in tar.getmembers():- if not (member.isfile() or member.isdir() or member.issym() or member.islnk()):- raise ValueError(f"Unsafe archive member type: {member.name}")- target = (destination / member.name).resolve()- if target != destination_resolved and destination_resolved not in target.parents:- raise ValueError(f"Unsafe archive member path: {member.name}")- if member.issym():- link_target = (destination / member.name).parent / member.linkname- link_target_resolved = link_target.resolve()- if link_target_resolved != destination_resolved and destination_resolved not in link_target_resolved.parents:- raise ValueError(f"Unsafe archive link target: {member.name}")- elif member.islnk():- link_target = destination / member.linkname- link_target_resolved = link_target.resolve()- if link_target_resolved != destination_resolved and destination_resolved not in link_target_resolved.parents:- raise ValueError(f"Unsafe archive link target: {member.name}")- try:- tar.extractall(destination, filter="data")- except TypeError:- tar.extractall(destination)---def _file_sha256(path: Path) -> str:- digest = hashlib.sha256()- with path.open("rb") as file:- for chunk in iter(lambda: file.read(1024 * 1024), b""):- digest.update(chunk)- return digest.hexdigest()---def _safe_path_part(value: str) -> str:- cleaned = "".join(ch if ch.isalnum() or ch in "._-" else "_" for ch in value.strip())- return cleaned or "main"--def _node_version(node: list[str]) -> tuple[int, int, int] | None:try:result = subprocess.run(diff --git a/tests/test_managed_runtime.py b/tests/test_managed_runtime.pyindex e1683d13b..0a3c421fe 100644--- a/tests/test_managed_runtime.py+++ b/tests/test_managed_runtime.py@@ -11,6 +11,7 @@ import tarfileimport timefrom pathlib import Pathfrom types import SimpleNamespace+from unittest.mock import patchimport pytest@@ -382,11 +383,89 @@ def _install_fixture_runtime_release(version=version,archive_name=archive_name,)- installed = manager.ensure()+ with patch.object(manager, "_clean_after_successful_install"):+ installed = manager.ensure()assert installed["ok"] is Truereturn Path(installed["install_dir"]), manager.runtime_dir / "downloads" / source_archive.name+def test_ensure_invokes_cleanup_only_after_publishing_success(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ manifest_path = tmp_path / "manifest.json"+ _write_fixture_runtime_release(+ tmp_path,+ manifest_path,+ label="published",+ version="1.0.0",+ )+ manager = _fixture_runtime_manager(tmp_path / "runtime", manifest_path=manifest_path)+ observed_install_dirs: list[str] = []++ def observe_cleanup() -> None:+ pointer = json.loads((manager.runtime_dir / "current.json").read_text(encoding="utf-8"))+ observed_install_dirs.append(pointer["install_dir"])++ monkeypatch.setattr(manager, "_clean_after_successful_install", observe_cleanup)++ result = manager.ensure()++ assert result["ok"] is True+ assert result["changed"] is True+ assert observed_install_dirs == [result["install_dir"]]++ reused = manager.ensure()++ assert reused["ok"] is True+ assert reused["changed"] is False+ assert observed_install_dirs == [result["install_dir"]]++ failed_manager = _fixture_runtime_manager(+ tmp_path / "failed-runtime",+ manifest_path=tmp_path / "missing.json",+ offline=True,+ )+ failed_calls: list[None] = []+ monkeypatch.setattr(+ failed_manager,+ "_clean_after_successful_install",+ lambda: failed_calls.append(None),+ )++ failed = failed_manager.ensure()++ assert failed["ok"] is False+ assert failed_calls == []+++def test_ensure_keeps_published_success_when_cleanup_raises(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ manifest_path = tmp_path / "manifest.json"+ _write_fixture_runtime_release(+ tmp_path,+ manifest_path,+ label="cleanup-failure",+ version="1.0.0",+ )+ manager = _fixture_runtime_manager(tmp_path / "runtime", manifest_path=manifest_path)++ def fail_cleanup() -> None:+ raise OSError("cleanup failed")++ monkeypatch.setattr(manager, "_clean_after_successful_install", fail_cleanup)++ result = manager.ensure()++ assert result["ok"] is True+ assert result["changed"] is True+ assert Path(result["path"]).is_file()+ pointer = json.loads((manager.runtime_dir / "current.json").read_text(encoding="utf-8"))+ assert pointer["install_dir"] == result["install_dir"]++def _age_path(path: Path) -> None:stamp = time.time() - 3600os.utime(path, (stamp, stamp))@@ -2298,6 +2377,8 @@ def test_shared_ensure_failure_vocabulary_matches_reachable_reason_literals() ->for node in manager.bodyif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}+ # This post-publish call is exception-isolated and cannot contribute an ensure failure.+ non_failure_calls = {"_clean_after_successful_install"}reachable = {"ensure"}pending = ["ensure"]while pending:@@ -2311,6 +2392,7 @@ def test_shared_ensure_failure_vocabulary_matches_reachable_reason_literals() ->and isinstance(function.value, ast.Name)and function.value.id == "self"and function.attr in methods+ and function.attr not in non_failure_callsand function.attr not in reachable):continuediff --git a/tests/test_managed_runtime_composite_artifacts.py b/tests/test_managed_runtime_composite_artifacts.pyindex 4c76d5c56..ed1c572b8 100644--- a/tests/test_managed_runtime_composite_artifacts.py+++ b/tests/test_managed_runtime_composite_artifacts.py@@ -21,7 +21,6 @@ ESBUILD_PAYLOAD = b"fixture-esbuild\n"Extractor = Callable[[tarfile.TarFile, Path], None]EXTRACTORS: tuple[tuple[str, Extractor], ...] = (("shared", managed_runtime.safe_extract_tar),- ("show", show_runtime._safe_extract_tar),("tmux", tmux_runtime._safe_extract_tar),)@@ -234,7 +233,7 @@ def test_released_show_composite_shape_installs_through_production_adapter(encoding="utf-8",)monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: platform)- monkeypatch.setattr(show_runtime, "_runtime_platform_tag", lambda: platform)+ monkeypatch.setattr(show_runtime, "runtime_platform_tag", lambda: platform)monkeypatch.setattr(show_runtime,"_resolve_command",@@ -509,7 +508,6 @@ def test_shared_fallback_keeps_order_dependent_links_confined(("_name", "extractor"),(("shared", managed_runtime.safe_extract_tar),- ("show", show_runtime._safe_extract_tar),("tarfile", lambda archive, destination: archive.extractall(destination, filter="data")),),)@@ -556,7 +554,6 @@ def test_order_dependent_link_target_stays_confined(("_name", "extractor", "detects_before_extract"),(("shared", managed_runtime.safe_extract_tar, True),- ("show", show_runtime._safe_extract_tar, False),("tmux", tmux_runtime._safe_extract_tar, True),),)diff --git a/tests/test_show_runtime_archive_cleanup.py b/tests/test_show_runtime_archive_cleanup.pyindex 39dc91f47..2f277034f 100644--- a/tests/test_show_runtime_archive_cleanup.py+++ b/tests/test_show_runtime_archive_cleanup.py@@ -165,14 +165,14 @@ def test_clean_is_idempotent_for_archives(tmp_path: Path) -> None:assert second["archives"]["candidate_count"] == 0-def test_clean_after_managed_install_prunes_stale_archives(tmp_path: Path) -> None:+def test_shared_post_install_cleanup_prunes_stale_archives(tmp_path: Path) -> None:manager = ShowRuntimeManager(runtime_dir=tmp_path / "show-runtime", offline=True, runtime_source="manifest-cache")current_install = _write_install_metadata(manager, version="v2", sha256=_sha(1), mtime=0)_write_current_pointer(manager, _sha(1), install_dir=current_install)current_archive = _write_archive(manager, _sha(1), b"current")stale = _write_archive(manager, _sha(2), b"stale")- manager._clean_after_managed_install(["node", str(current_install / "cli.js")])+ manager._shared_manifest_manager(offline=True)._clean_after_successful_install()assert current_archive.exists() # current archive intactassert not stale.exists()@@ -204,7 +204,7 @@ def test_clean_after_custom_manifest_install_prunes_stale_installs(tmp_path: Patrollback_archive = _write_archive(manager, _sha(8), b"rollback")stale_archive = _write_archive(manager, _sha(9), b"stale-custom")- manager._clean_after_managed_install(["node", str(current_install / "cli.js")])+ manager._shared_manifest_manager(offline=True)._clean_after_successful_install()assert current_archive.exists() and current_install.exists()assert rollback_archive.exists() and rollback_install.exists()@@ -240,7 +240,7 @@ def test_clean_after_custom_manifest_prunes_obsolete_sources(tmp_path: Path) ->rollback_archive = _write_archive(manager, _sha(8), b"rollback")stale_archive = _write_archive(manager, _sha(9), b"stale-old-source")- manager._clean_after_managed_install(["node", str(current_install / "cli.js")])+ manager._shared_manifest_manager(offline=True)._clean_after_successful_install()assert current_archive.exists() and current_install.exists()assert rollback_archive.exists() and rollback_install.exists()@@ -326,7 +326,7 @@ def test_cli_clean_dry_run_is_read_only_for_git_runtime(monkeypatch, capsys) ->def test_cleanup_reuses_install_guard_without_deadlock(tmp_path: Path) -> None:- """The post-install cleanup runs inside the installer's guard.+ """Direct-provider cleanup can reuse Show's installer guard.``flock`` is not re-entrant across file handles, so this exercises thedepth-counted reuse: cleaning while the guard is held must complete and@@ -491,7 +491,7 @@ def test_install_guard_unavailable_falls_back_to_verified_install(tmp_path: Path"""A read-only runtime dir must not turn a verified install into a failure."""from core import show_runtime as module- monkeypatch.setattr(module, "_runtime_platform_tag", lambda: "test")+ monkeypatch.setattr(module, "runtime_platform_tag", lambda: "test")monkeypatch.setattr("core.managed_runtime.runtime_platform_tag", lambda: "test")monkeypatch.setattr(module, "_resolve_node_command", lambda: ["node"])manifest_payload = {@@ -513,10 +513,12 @@ def test_install_guard_unavailable_falls_back_to_verified_install(tmp_path: Pathruntime_source="manifest-cache",manifest_path=manifest_path,)- manifest = manager._load_runtime_manifest()+ shared_manager = manager._shared_manifest_manager(offline=True)+ manifest = shared_manager.load_manifest(allow_network=False)assert manifest is not None- archive = manifest.archives["test"]- install_dir = manager._manifest_install_dir(manifest, archive)+ archive = shared_manager.archive_for_platform(manifest)+ assert archive is not None+ install_dir = shared_manager._manifest_install_dir(manifest, archive)install_dir.mkdir(parents=True, exist_ok=True)(install_dir / ".vibe-show-runtime.json").write_text(json.dumps(@@ -654,7 +656,8 @@ def test_candidate_stat_failure_is_an_inspection_failure(tmp_path: Path, monkeypdef test_forced_prepare_fails_structured_when_guard_unavailable(tmp_path: Path, monkeypatch) -> None:from core import show_runtime as module- monkeypatch.setattr(module, "_runtime_platform_tag", lambda: "test")+ monkeypatch.setattr(module, "runtime_platform_tag", lambda: "test")+ monkeypatch.setattr("core.managed_runtime.runtime_platform_tag", lambda: "test")monkeypatch.setattr(module, "_resolve_node_command", lambda: ["node"])manifest_payload = {"schema_version": 1,@@ -697,9 +700,10 @@ def test_forced_prepare_fails_structured_when_guard_unavailable(tmp_path: Path,def test_installed_manifest_command_enforces_node_requirement(tmp_path: Path, monkeypatch) -> None:from core import show_runtime as module- monkeypatch.setattr(module, "_runtime_platform_tag", lambda: "test")+ monkeypatch.setattr(module, "runtime_platform_tag", lambda: "test")+ monkeypatch.setattr("core.managed_runtime.runtime_platform_tag", lambda: "test")monkeypatch.setattr(module, "_resolve_node_command", lambda: ["node"])- monkeypatch.setattr(module, "_node_version", lambda _command: "18.0.0")+ monkeypatch.setattr(module, "_node_version", lambda _command: (18, 0, 0))manifest_payload = {"schema_version": 1,"runtime_version": "v2",@@ -714,10 +718,12 @@ def test_installed_manifest_command_enforces_node_requirement(tmp_path: Path, moruntime_source="manifest-cache",manifest_path=manifest_path,)- manifest = manager._load_runtime_manifest()+ shared_manager = manager._shared_manifest_manager(offline=True)+ manifest = shared_manager.load_manifest(allow_network=False)assert manifest is not None- archive = manifest.archives["test"]- install_dir = manager._manifest_install_dir(manifest, archive)+ archive = shared_manager.archive_for_platform(manifest)+ assert archive is not None+ install_dir = shared_manager._manifest_install_dir(manifest, archive)install_dir.mkdir(parents=True, exist_ok=True)(install_dir / ".vibe-show-runtime.json").write_text(json.dumps(diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex 5cc6a763b..d369e1b78 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -61,10 +61,9 @@ from core.show_runtime import (ShowRuntimeUnavailableError,ShowRuntimeWebSocketTarget,_runtime_download_error,- _runtime_platform_tag,- _safe_extract_tar,set_show_runtime_manager_for_tests,)+from core.managed_runtime import runtime_platform_tag, safe_extract_tarfrom core.show_runtime_failures import (SHOW_RUNTIME_FAILURE_DECLARATIONS,ShowRuntimeFailureClass,@@ -480,7 +479,7 @@ def _write_runtime_manifest("runtime_version": runtime_version,"minimum_node": "^20.19.0 || >=22.12.0","archives": {- _runtime_platform_tag(): {+ runtime_platform_tag(): {"name": archive_path.name,"url": url or archive_path.resolve().as_uri(),"sha256": sha256 or _sha256(archive_path),@@ -528,7 +527,7 @@ def _write_cached_runtime_install(manifest_source: str = "package:show_runtime_manifest.json",mtime: float,) -> tuple[Path, Path]:- install_dir = runtime_dir / "versions" / name / _runtime_platform_tag() / f"fingerprint-{name}"+ install_dir = runtime_dir / "versions" / name / runtime_platform_tag() / f"fingerprint-{name}"return _write_cached_runtime_install_at(install_dir, name, manifest_source=manifest_source, mtime=mtime)@@ -551,7 +550,7 @@ def _write_cached_runtime_install_at("manifest_source": manifest_source,"manifest_sha256": manifest_sha256,"runtime_version": name,- "platform": _runtime_platform_tag(),+ "platform": runtime_platform_tag(),"archive_name": f"{archive_sha256}.tgz","archive_sha256": archive_sha256,}@@ -581,6 +580,16 @@ def _write_cached_runtime_pointer(runtime_dir: Path, install_dir: Path) -> None:)+def _complete_mock_manifest_install(+ manager: ShowRuntimeManager,+ command: list[str],+ *,+ offline: bool,+) -> list[str]:+ manager._shared_manifest_manager(offline=offline)._clean_after_successful_install()+ return command++def test_private_show_page_requires_remote_login(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)@@ -9261,10 +9270,10 @@ def test_show_runtime_manager_uses_managed_runtime_bin(tmp_path):def test_show_runtime_archive_platform_tag_maps_macos_universal2_to_machine(monkeypatch):- monkeypatch.setattr("core.show_runtime.get_platform", lambda: "macosx-14.0-universal2")- monkeypatch.setattr("core.show_runtime.platform.machine", lambda: "arm64")+ monkeypatch.setattr("core.managed_runtime.get_platform", lambda: "macosx-14.0-universal2")+ monkeypatch.setattr("core.managed_runtime.platform.machine", lambda: "arm64")- assert _runtime_platform_tag() == "darwin-arm64"+ assert runtime_platform_tag() == "darwin-arm64"def test_show_runtime_manager_installs_from_prebuilt_archive(monkeypatch, tmp_path):@@ -9336,8 +9345,8 @@ def test_show_runtime_safe_extract_rejects_external_symlink(tmp_path):tar.add(archive_root / "escape", arcname="escape")with tarfile.open(archive_path, "r:gz") as tar:- with pytest.raises(ValueError, match="Unsafe archive link target"):- _safe_extract_tar(tar, tmp_path / "destination")+ with pytest.raises(ValueError, match="Unsafe managed runtime archive link target"):+ safe_extract_tar(tar, tmp_path / "destination")def test_show_runtime_safe_extract_rejects_external_hardlink(tmp_path):@@ -9353,8 +9362,8 @@ def test_show_runtime_safe_extract_rejects_external_hardlink(tmp_path):tar.addfile(hardlink)with tarfile.open(archive_path, "r:gz") as tar:- with pytest.raises(ValueError, match="Unsafe archive link target"):- _safe_extract_tar(tar, tmp_path / "destination")+ with pytest.raises(ValueError, match="Unsafe managed runtime archive link target"):+ safe_extract_tar(tar, tmp_path / "destination")def test_show_runtime_manager_reuses_installed_prebuilt_runtime_without_archive(monkeypatch, tmp_path):@@ -9530,11 +9539,10 @@ def test_show_runtime_manager_installs_from_manifest_cache(monkeypatch, tmp_pathmonkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)result = manager.prepare()- manifest = manager._load_runtime_manifest()+ shared_manager = manager._shared_manifest_manager(offline=True)+ manifest = shared_manager.load_manifest(allow_network=False)assert manifest is not None- archive = manager._manifest_archive_for_platform(manifest)- assert archive is not None- installed_cli = Path(manager._manifest_runtime_command(manager._manifest_install_dir(manifest, archive), ["/bin/node"])[1])+ installed_cli = Path(result["command"][1])assert result["ok"] is Trueassert result["command"] == ["/bin/node", str(installed_cli)]@@ -10054,7 +10062,8 @@ def test_show_runtime_manager_manifest_install_identity_ignores_other_platform_emanifest_path=manifest_path,)initial_result = initial_manager.prepare()- initial_manifest = initial_manager._load_runtime_manifest()+ initial_shared_manager = initial_manager._shared_manifest_manager(offline=True)+ initial_manifest = initial_shared_manager.load_manifest(allow_network=False)assert initial_manifest is not Nonepayload = json.loads(manifest_path.read_text(encoding="utf-8"))@@ -10071,14 +10080,18 @@ def test_show_runtime_manager_manifest_install_identity_ignores_other_platform_emanifest_path=manifest_path,offline=True,)- edited_manifest = edited_manager._load_runtime_manifest()+ edited_shared_manager = edited_manager._shared_manifest_manager(offline=True)+ edited_manifest = edited_shared_manager.load_manifest(allow_network=False)assert edited_manifest is not Noneassert edited_manifest.digest != initial_manifest.digest- def _unexpected_archive_resolution(_archive):+ def _unexpected_archive_resolution(_shared_manager, _archive):raise AssertionError("an unrelated platform edit must not trigger archive resolution")- monkeypatch.setattr(edited_manager, "_resolve_manifest_archive", _unexpected_archive_resolution)+ monkeypatch.setattr(+ "core.show_runtime._ShowManifestRuntimeManager._resolve_manifest_archive",+ _unexpected_archive_resolution,+ )edited_result = edited_manager.prepare()assert edited_result["ok"] is True@@ -10097,18 +10110,24 @@ def test_show_runtime_manager_adopts_previous_fingerprint_and_preserves_gc_proteruntime_dir=runtime_dir,manifest_path=manifest_path,)- previous_manifest = previous_manager._load_runtime_manifest()+ previous_shared_manager = previous_manager._shared_manifest_manager(offline=True)+ previous_manifest = previous_shared_manager.load_manifest(allow_network=False)assert previous_manifest is not None- archive = previous_manager._manifest_archive_for_platform(previous_manifest)+ archive = previous_shared_manager.archive_for_platform(previous_manifest)assert archive is not Noneprevious_fingerprint = hashlib.sha256(f"{previous_manifest.digest}:{archive.sha256}".encode("utf-8")).hexdigest()[:16]- previous_install_dir = previous_manager._legacy_manifest_install_dir(previous_manifest, archive) / previous_fingerprint+ previous_install_dir = previous_shared_manager._manifest_install_dir(previous_manifest, archive).parent / previous_fingerprintprevious_cli = previous_install_dir / "node_modules" / "@avibe" / "show-runtime" / "dist" / "cli.js"previous_cli.parent.mkdir(parents=True)previous_cli.write_text("previous fingerprint runtime\n", encoding="utf-8")- previous_manager._write_manifest_install_metadata(previous_install_dir, previous_manifest, archive)+ previous_shared_manager._write_manifest_install_metadata(+ previous_install_dir,+ previous_manifest,+ archive,+ binary_sha256=None,+ )downloads_dir = runtime_dir / "downloads"downloads_dir.mkdir(parents=True)@@ -10163,21 +10182,26 @@ def test_show_runtime_manager_adopts_previous_fingerprint_and_preserves_gc_protemanifest_path=manifest_path,offline=True,)- current_manifest = manager._load_runtime_manifest()+ shared_manager = manager._shared_manifest_manager(offline=True)+ current_manifest = shared_manager.load_manifest(allow_network=False)assert current_manifest is not None- assert manager._manifest_install_dir(current_manifest, archive) != previous_install_dir+ current_install_dir = shared_manager._manifest_install_dir(current_manifest, archive)+ assert current_install_dir != previous_install_dir- def _unexpected_archive_resolution(_archive):+ def _unexpected_archive_resolution(_shared_manager, _archive):raise AssertionError("a previous-fingerprint install must be adopted without a download")- monkeypatch.setattr(manager, "_resolve_manifest_archive", _unexpected_archive_resolution)+ monkeypatch.setattr(+ "core.show_runtime._ShowManifestRuntimeManager._resolve_manifest_archive",+ _unexpected_archive_resolution,+ )result = manager.prepare()assert result["ok"] is Trueassert result["command"] == ["/bin/node", str(previous_cli)]assert previous_install_dir.exists() is True- assert manager._manifest_install_dir(current_manifest, archive).exists() is False- assert archive.sha256 in manager._protected_archive_sha256s()+ assert current_install_dir.exists() is False+ assert archive.sha256 == shared_manager._current_archive_sha256()current_pointer = json.loads((runtime_dir / "current.json").read_text(encoding="utf-8"))assert current_pointer["runtime_version"] == current_manifest.runtime_versionassert current_pointer["install_dir"] == str(previous_install_dir)@@ -10263,7 +10287,11 @@ def test_show_runtime_prepare_prunes_old_packaged_installs_and_keeps_rollback(momonkeypatch.setattr(manager,"_install_manifest_runtime_locked",- lambda *, force, offline: ["/bin/node", str(current_cli)],+ lambda *, force, offline: _complete_mock_manifest_install(+ manager,+ ["/bin/node", str(current_cli)],+ offline=offline,+ ),)monkeypatch.setattr(manager, "status", lambda **_kwargs: {})@@ -10284,7 +10312,7 @@ def test_show_runtime_prepare_preserves_nested_retained_rollback(monkeypatch, tmold_install, _old_cli = _write_cached_runtime_install(runtime_dir, "old", mtime=10)current_install, current_cli = _write_cached_runtime_install(runtime_dir, "current", mtime=300)_write_cached_runtime_pointer(runtime_dir, current_install)- rollback_parent = runtime_dir / "versions" / "rollback" / _runtime_platform_tag()+ rollback_parent = runtime_dir / "versions" / "rollback" / runtime_platform_tag()_rollback_parent, rollback_parent_cli = _write_cached_runtime_install_at(rollback_parent,"rollback-legacy",@@ -10309,7 +10337,11 @@ def test_show_runtime_prepare_preserves_nested_retained_rollback(monkeypatch, tmmonkeypatch.setattr(manager,"_install_manifest_runtime_locked",- lambda *, force, offline: ["/bin/node", str(current_cli)],+ lambda *, force, offline: _complete_mock_manifest_install(+ manager,+ ["/bin/node", str(current_cli)],+ offline=offline,+ ),)monkeypatch.setattr(manager, "status", lambda **_kwargs: {})@@ -10329,7 +10361,7 @@ def test_show_runtime_prepare_prunes_siblings_under_current_legacy_parent(monkeyruntime_dir = tmp_path / "runtime"old_install, _old_cli = _write_cached_runtime_install(runtime_dir, "old", mtime=100)previous_install, _previous_cli = _write_cached_runtime_install(runtime_dir, "previous", mtime=250)- current_parent = runtime_dir / "versions" / "current" / _runtime_platform_tag()+ current_parent = runtime_dir / "versions" / "current" / runtime_platform_tag()_parent_install, parent_cli = _write_cached_runtime_install_at(current_parent, "current-legacy", mtime=400)current_install, current_cli = _write_cached_runtime_install_at(current_parent / "current-fingerprint",@@ -10351,7 +10383,11 @@ def test_show_runtime_prepare_prunes_siblings_under_current_legacy_parent(monkeymonkeypatch.setattr(manager,"_install_manifest_runtime_locked",- lambda *, force, offline: ["/bin/node", str(current_cli)],+ lambda *, force, offline: _complete_mock_manifest_install(+ manager,+ ["/bin/node", str(current_cli)],+ offline=offline,+ ),)monkeypatch.setattr(manager, "status", lambda **_kwargs: {})@@ -10371,7 +10407,7 @@ def test_show_runtime_prepare_preserves_descendants_of_current_legacy_parent(monruntime_dir = tmp_path / "runtime"old_install, _old_cli = _write_cached_runtime_install(runtime_dir, "old", mtime=100)previous_install, _previous_cli = _write_cached_runtime_install(runtime_dir, "previous", mtime=250)- current_parent = runtime_dir / "versions" / "current" / _runtime_platform_tag()+ current_parent = runtime_dir / "versions" / "current" / runtime_platform_tag()_parent_install, parent_cli = _write_cached_runtime_install_at(current_parent, "current-legacy", mtime=400)_write_cached_runtime_pointer(runtime_dir, current_parent)current_child, current_child_cli = _write_cached_runtime_install_at(@@ -10388,7 +10424,11 @@ def test_show_runtime_prepare_preserves_descendants_of_current_legacy_parent(monmonkeypatch.setattr(manager,"_install_manifest_runtime_locked",- lambda *, force, offline: ["/bin/node", str(parent_cli)],+ lambda *, force, offline: _complete_mock_manifest_install(+ manager,+ ["/bin/node", str(parent_cli)],+ offline=offline,+ ),)monkeypatch.setattr(manager, "status", lambda **_kwargs: {})@@ -10409,7 +10449,7 @@ def test_show_runtime_prepare_preserves_custom_child_under_stale_packaged_parentprevious_install, _previous_cli = _write_cached_runtime_install(runtime_dir, "previous", mtime=250)current_install, current_cli = _write_cached_runtime_install(runtime_dir, "current", mtime=300)_write_cached_runtime_pointer(runtime_dir, current_install)- stale_parent = runtime_dir / "versions" / "stale-parent" / _runtime_platform_tag()+ stale_parent = runtime_dir / "versions" / "stale-parent" / runtime_platform_tag()_parent_install, parent_cli = _write_cached_runtime_install_at(stale_parent, "stale-parent", mtime=80)custom_child, custom_cli = _write_cached_runtime_install_at(stale_parent / "custom-fingerprint",@@ -10431,7 +10471,11 @@ def test_show_runtime_prepare_preserves_custom_child_under_stale_packaged_parentmonkeypatch.setattr(manager,"_install_manifest_runtime_locked",- lambda *, force, offline: ["/bin/node", str(current_cli)],+ lambda *, force, offline: _complete_mock_manifest_install(+ manager,+ ["/bin/node", str(current_cli)],+ offline=offline,+ ),)monkeypatch.setattr(manager, "status", lambda **_kwargs: {})@@ -10533,15 +10577,21 @@ def test_show_runtime_manager_reuses_legacy_manifest_install_offline(monkeypatchoffline=True,)monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)- manifest = manager._load_runtime_manifest()+ shared_manager = manager._shared_manifest_manager(offline=True)+ manifest = shared_manager.load_manifest(allow_network=False)assert manifest is not None- archive = manager._manifest_archive_for_platform(manifest)+ archive = shared_manager.archive_for_platform(manifest)assert archive is not None- legacy_install_dir = manager._legacy_manifest_install_dir(manifest, archive)+ legacy_install_dir = shared_manager._manifest_install_dir(manifest, archive).parentlegacy_cli = legacy_install_dir / "node_modules" / "@avibe" / "show-runtime" / "dist" / "cli.js"legacy_cli.parent.mkdir(parents=True)legacy_cli.write_text("legacy runtime\n", encoding="utf-8")- manager._write_manifest_install_metadata(legacy_install_dir, manifest, archive)+ shared_manager._write_manifest_install_metadata(+ legacy_install_dir,+ manifest,+ archive,+ binary_sha256=None,+ )result = manager.prepare()@@ -10562,11 +10612,17 @@ def test_show_runtime_clean_skips_legacy_parent_of_current_fingerprint(monkeypatresult = manager.prepare()current_install_dir = Path(result["command"][1]).parents[4]legacy_parent = current_install_dir.parent- manifest = manager._load_runtime_manifest()+ shared_manager = manager._shared_manifest_manager(offline=True)+ manifest = shared_manager.load_manifest(allow_network=False)assert manifest is not None- archive = manager._manifest_archive_for_platform(manifest)+ archive = shared_manager.archive_for_platform(manifest)assert archive is not None- manager._write_manifest_install_metadata(legacy_parent, manifest, archive)+ shared_manager._write_manifest_install_metadata(+ legacy_parent,+ manifest,+ archive,+ binary_sha256=None,+ )clean_result = manager.clean(keep_previous=0)@@ -10587,7 +10643,7 @@ def test_show_runtime_manager_rejects_noncanonical_manifest_entrypoint(archive_path = _write_runtime_archive_with_entrypoints(tmp_path, entrypoints)manifest_path = _write_runtime_manifest(tmp_path, archive_path)payload = json.loads(manifest_path.read_text(encoding="utf-8"))- payload["archives"][_runtime_platform_tag()]["bin_path"] = alternate+ payload["archives"][runtime_platform_tag()]["bin_path"] = alternatemanifest_path.write_text(json.dumps(payload), encoding="utf-8")manager = ShowRuntimeManager(workspace_root=tmp_path / "show",@@ -10633,7 +10689,7 @@ def test_show_runtime_status_reports_selected_manifest_archive_error_with_instalmanifest_path=manifest_path,).prepare()payload = json.loads(manifest_path.read_text(encoding="utf-8"))- platform_tag = _runtime_platform_tag()+ platform_tag = runtime_platform_tag()if selection_error == "missing_platform":payload["archives"]["fixture-unsupported"] = payload["archives"].pop(platform_tag)else:@@ -10793,7 +10849,7 @@ def test_show_runtime_manager_installs_manifest_archive_from_verified_offline_cacached.parent.mkdir(parents=True)cached.write_bytes(archive_path.read_bytes())manifest = json.loads(manifest_path.read_text(encoding="utf-8"))- manifest["archives"][_runtime_platform_tag()]["url"] = "https://example.invalid/runtime.tgz"+ manifest["archives"][runtime_platform_tag()]["url"] = "https://example.invalid/runtime.tgz"manifest_path.write_text(json.dumps(manifest), encoding="utf-8")manager = ShowRuntimeManager(workspace_root=tmp_path / "show",@@ -10974,7 +11030,7 @@ def test_show_runtime_automatic_opt_out_does_not_fetch_remote_manifest(monkeypatauto_install=False,)monkeypatch.setattr(- "core.show_runtime.fetch_bytes",+ "core.managed_runtime.fetch_bytes",lambda *_args, **_kwargs: pytest.fail("automatic opt-out must not access the network"),)@@ -10993,7 +11049,7 @@ def test_show_runtime_remote_manifest_install_remains_installed_when_source_is_uauto_install=False,)monkeypatch.setattr(- "core.show_runtime.fetch_bytes",+ "core.managed_runtime.fetch_bytes",lambda *_args, **_kwargs: pytest.fail("policy skip must derive install state from disk"),)@@ -11096,7 +11152,7 @@ def test_show_runtime_status_keeps_installed_identity_separate_from_selected_manauto_install=False,)monkeypatch.setattr(- "core.show_runtime.fetch_bytes",+ "core.managed_runtime.fetch_bytes",lambda url, **_kwargs: selected_manifest.read_bytes()if url == manifest_urlelse pytest.fail(f"unexpected fetch: {url}"),@@ -11130,7 +11186,7 @@ def test_show_runtime_disk_install_fact_does_not_require_node(monkeypatch, tmp_pauto_install=False,)monkeypatch.setattr(- "core.show_runtime.fetch_bytes",+ "core.managed_runtime.fetch_bytes",lambda *_args, **_kwargs: pytest.fail("policy skip must not fetch the manifest"),)@@ -11194,7 +11250,7 @@ def test_show_runtime_disk_install_pointer_fails_closed(monkeypatch, tmp_path, cauto_install=False,)monkeypatch.setattr(- "core.show_runtime.fetch_bytes",+ "core.managed_runtime.fetch_bytes",lambda *_args, **_kwargs: pytest.fail("policy skip must not fetch the manifest"),)