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(show-runtime): unify verified repair and status (#1832)
Call Whiteaa04e465a83c
diff --git a/core/managed_runtime.py b/core/managed_runtime.pyindex 47dfa54f9..19fe98af0 100644--- a/core/managed_runtime.py+++ b/core/managed_runtime.py@@ -64,6 +64,7 @@ _ENSURE_FAILURE_SUFFIXES = frozenset("binary_checksum_mismatch","binary_not_runnable","binary_prepare_failed",+ "candidate_validation_failed","install_already_running","install_claim_failed","install_failed",@@ -184,6 +185,7 @@ class ManagedRuntimeManager:force: bool = False,expected_target: Mapping[str, str] | None = None,on_resolved: Callable[[dict[str, str]], None] | None = None,+ validate_candidate: Callable[[Path], str | None] | None = None,) -> dict[str, Any]:try:file_lock = self._acquire_mutation_lock()@@ -260,6 +262,21 @@ class ManagedRuntimeManager:existing = candidatebreakif existing is not None and not force:+ try:+ validation_reason = validate_candidate(existing) if validate_candidate else None+ except Exception: # noqa: BLE001+ logger.warning(+ "Managed %s runtime candidate validation failed",+ self.spec.runtime_id,+ exc_info=True,+ )+ validation_reason = self._reason("candidate_validation_failed")+ if validation_reason:+ return self._failure(+ validation_reason,+ manifest=manifest,+ archive=archive,+ )return self._reuse_existing_install(existing,existing_install_dir,@@ -353,6 +370,25 @@ class ManagedRuntimeManager:archive,binary_sha256=binary_sha256,)+ try:+ validation_reason = (+ validate_candidate(installed_binary)+ if validate_candidate is not None+ else None+ )+ except Exception: # noqa: BLE001+ logger.warning(+ "Managed %s runtime candidate validation failed",+ self.spec.runtime_id,+ exc_info=True,+ )+ validation_reason = self._reason("candidate_validation_failed")+ if validation_reason:+ return self._failure(+ validation_reason,+ manifest=manifest,+ archive=archive,+ )self._write_current_pointer(install_dir, manifest, archive)candidate_install_dir = Noneself._install_reason = None@@ -377,6 +413,8 @@ class ManagedRuntimeManager:archive=archive,)finally:+ if candidate_install_dir is not None:+ shutil.rmtree(candidate_install_dir, ignore_errors=True)if staging_dir.exists():shutil.rmtree(staging_dir, ignore_errors=True)finally:diff --git a/core/show_runtime.py b/core/show_runtime.pyindex 0882ee80b..0ef34b368 100644--- a/core/show_runtime.py+++ b/core/show_runtime.py@@ -23,10 +23,12 @@ import threadingimport timeimport urllib.parseimport urllib.request+import weakreffrom dataclasses import dataclass, replacefrom enum import Enumfrom pathlib import Path-from typing import Any, Iterable, Iterator, Mapping+from typing import IO, Any, Callable, Iterable, Iterator, Mapping+from uuid import uuid4import httpx@@ -40,6 +42,7 @@ from storage.lock import ()from config import paths+from config.atomic_io import write_atomicfrom core.dependency_network import dependency_error_details, fetch_to_path, probe_url, redact_urlfrom core.managed_runtime import (ManagedRuntimeArchive,@@ -91,6 +94,9 @@ _SKIPPED_ARCHIVE_REASON_REMOVAL_FAILED = "archive_removal_failed"# enumeration test in tests/test_show_runtime_archive_cleanup.py pins CLI and# Doctor rendering to it, so a new outcome fails the test until wired._ARCHIVE_CLEANUP_OUTCOMES = frozenset({"cleaned", "partial", "skipped"})+_INSTALL_REFERENCE_RE = re.compile(r"^[0-9a-f]{32}\.lock$")+_INSTALL_REFERENCE_LOCKS: dict[tuple[str, str], "_ShowRuntimeInstallReference"] = {}+_INSTALL_REFERENCE_LOCKS_GUARD = threading.Lock()class _ArchiveMetadataError(Exception):@@ -101,6 +107,42 @@ class _ArchiveInspectionError(Exception):"""The archive cache itself could not be inspected; cleanup must abort."""+@dataclass+class _ShowRuntimeInstallReference:+ marker: Path+ handle: IO[str]+ owners: set[str]+++def _unlock_install_reference(handle: IO[str]) -> None:+ try:+ if os.name == "nt":+ handle.seek(0)+ unlock_windows_exclusive_lock(handle.fileno())+ else:+ import fcntl++ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)+ finally:+ handle.close()+++def _release_install_reference_owner(owner: str) -> None:+ released: list[_ShowRuntimeInstallReference] = []+ with _INSTALL_REFERENCE_LOCKS_GUARD:+ for key, reference in list(_INSTALL_REFERENCE_LOCKS.items()):+ reference.owners.discard(owner)+ if reference.owners:+ continue+ released.append(reference)+ _INSTALL_REFERENCE_LOCKS.pop(key, None)+ for reference in released:+ try:+ _unlock_install_reference(reference.handle)+ finally:+ reference.marker.unlink(missing_ok=True)++def _is_exclusive_regular_file(info: os.stat_result) -> bool:"""True only for a one-link regular file that is not a reparse point."""if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:@@ -145,6 +187,50 @@ _STARTUP_ATTEMPT_FAILED_REASON = "runtime_start_attempt_failed"_MISSING = object()+class ShowRuntimeStartabilityState(str, Enum):+ STARTABLE = "startable"+ NOT_STARTABLE = "not_startable"+ UNDETERMINED = "undetermined"+++@dataclass(frozen=True)+class ShowRuntimeStartability:+ state: ShowRuntimeStartabilityState+ reason: str | None = None+ detail: str | None = None++ def __post_init__(self) -> None:+ if self.state is ShowRuntimeStartabilityState.STARTABLE and (self.reason or self.detail):+ raise ValueError("startable outcome cannot carry failure evidence")+ if self.state is ShowRuntimeStartabilityState.NOT_STARTABLE and (+ not self.reason or self.detail+ ):+ raise ValueError("not-startable outcome requires only a reason")+ if self.state is ShowRuntimeStartabilityState.UNDETERMINED and (+ self.reason or not self.detail+ ):+ raise ValueError("undetermined outcome requires only a detail")++ @classmethod+ def startable(cls) -> "ShowRuntimeStartability":+ return cls(ShowRuntimeStartabilityState.STARTABLE)++ @classmethod+ def not_startable(cls, reason: str) -> "ShowRuntimeStartability":+ return cls(ShowRuntimeStartabilityState.NOT_STARTABLE, reason=reason)++ @classmethod+ def undetermined(cls, detail: str) -> "ShowRuntimeStartability":+ return cls(ShowRuntimeStartabilityState.UNDETERMINED, detail=detail)++ def as_payload(self) -> dict[str, str | None]:+ return {+ "state": self.state.value,+ "reason": self.reason,+ "detail": self.detail,+ }++class ShowRuntimeContext(str, Enum):PRIVATE = "private"SHARED = "shared"@@ -432,7 +518,6 @@ _SHOW_MANAGED_RUNTIME_SPEC = ManagedRuntimeSpec(metadata_filename_override=".vibe-show-runtime.json",allow_legacy_missing_runtime_id=True,staging_prefixes=("install-", "manifest-"),- replace_target_on_force=True,)@@ -695,10 +780,25 @@ class _ShowManifestRuntimeManager(ManagedRuntimeManager):previous_fingerprint = hashlib.sha256(f"{manifest_sha256}:{archive_sha256}".encode("utf-8")).hexdigest()[:16]- return parts[2] in {current_fingerprint, previous_fingerprint}+ for fingerprint in (current_fingerprint, previous_fingerprint):+ if parts[2] == fingerprint:+ return True+ prefix = f"{fingerprint}-"+ suffix = parts[2][len(prefix) :] if parts[2].startswith(prefix) else ""+ if len(suffix) == 8 and all(+ character.isascii() and (character.isalnum() or character == "_")+ for character in suffix+ ):+ return True+ return False- def _retention_ranked_installs(self, installs, protected):+ def _retention_ranked_installs(self, installs: list[Any], protected: set[Path]) -> list[Any]:resolved_by_path = {install.path: install.path.resolve() for install in installs}+ protected.update(+ resolved+ for resolved in resolved_by_path.values()+ if self.owner._install_dir_has_live_reference(resolved)+ )return [installfor install in installs@@ -797,6 +897,12 @@ class ShowRuntimeManager:self._capability_retry_deadline = 0.0self._capability_retry_attempt = 0self._capability_generation = 0+ self._install_reference_owner = uuid4().hex+ self._install_reference_finalizer = weakref.finalize(+ self,+ _release_install_reference_owner,+ self._install_reference_owner,+ )@propertydef _install_reason(self) -> str | None:@@ -1526,6 +1632,7 @@ class ShowRuntimeManager:force: bool,offline: bool,automatic: bool,+ candidate_validator: Callable[[list[str]], ShowRuntimeStartability] | None = None,) -> tuple[ShowRuntimeAvailability, _ShowRuntimeOperationOutcome]:admission: ShowRuntimeAvailability | None = Noneoperation: _ShowRuntimeOperationOutcome | None = None@@ -1578,10 +1685,17 @@ class ShowRuntimeManager:if preflight is not None:admission, operation = preflightelse:- raw_attempt = self._install_managed_runtime_locked(- force=force,- offline=offline,- )+ if candidate_validator is None:+ raw_attempt = self._install_managed_runtime_locked(+ force=force,+ offline=offline,+ )+ else:+ raw_attempt = self._install_managed_runtime_locked(+ force=force,+ offline=offline,+ candidate_validator=candidate_validator,+ )attempt = (raw_attemptif isinstance(raw_attempt, _ManagedInstallAttempt)@@ -1849,14 +1963,38 @@ class ShowRuntimeManager:*,force: bool,offline: bool,+ candidate_validator: Callable[[list[str]], ShowRuntimeStartability] | None = None,) -> _ManagedInstallAttempt:command: list[str] | Noneif self.runtime_source == _RUNTIME_SOURCE_MANIFEST:- command = self._install_manifest_runtime_locked(force=force, offline=offline)+ command = (+ self._install_manifest_runtime_locked(force=force, offline=offline)+ if candidate_validator is None+ else self._install_manifest_runtime_locked(+ force=force,+ offline=offline,+ candidate_validator=candidate_validator,+ )+ )elif self.runtime_source == _RUNTIME_SOURCE_ARCHIVE:- command = self._install_archive_runtime(force=force, offline=offline)+ command = (+ self._install_archive_runtime(force=force, offline=offline)+ if candidate_validator is None+ else self._install_archive_runtime(+ force=force,+ offline=offline,+ candidate_validator=candidate_validator,+ )+ )elif self.runtime_source == _RUNTIME_SOURCE_NPM:- command = self._install_npm_runtime(force=force)+ command = (+ self._install_npm_runtime(force=force)+ if candidate_validator is None+ else self._install_npm_runtime(+ force=force,+ candidate_validator=candidate_validator,+ )+ )else:self._install_reason = "runtime_source_unsupported"return _ManagedInstallAttempt(None, self._install_reason)@@ -1872,7 +2010,8 @@ class ShowRuntimeManager:return self._installed_archive_runtime_command()if self.runtime_source == _RUNTIME_SOURCE_NPM:resolved = _resolve_executable_path(self._managed_bin_path())- return [resolved] if resolved else None+ command = [resolved] if resolved else None+ return command if command and self._retain_managed_command(command) else Nonereturn Nonedef _safe_installed_managed_runtime_command(self, *, offline: bool) -> list[str] | None:@@ -1886,7 +2025,256 @@ class ShowRuntimeManager:self._install_evidence = evidenceself._download_error = download_error+ def _managed_install_dir_for_command(self, command: Iterable[str]) -> Path | None:+ try:+ runtime_root = self.runtime_dir.resolve(strict=True)+ except (OSError, RuntimeError):+ return None+ legacy_roots = {+ runtime_root / "prebuilt" / "current",+ runtime_root / "package",+ }+ for value in reversed(tuple(command)):+ try:+ candidate = Path(value).expanduser().resolve(strict=True)+ except (OSError, RuntimeError):+ continue+ parents = (candidate, *candidate.parents) if candidate.is_dir() else candidate.parents+ for parent in parents:+ if parent == runtime_root:+ break+ if runtime_root not in parent.parents:+ continue+ if parent in legacy_roots or (parent / ".vibe-show-runtime.json").is_file():+ return parent+ return None++ def _install_reference_dir(self, install_dir: Path) -> Path:+ identity = hashlib.sha256(str(install_dir).encode("utf-8")).hexdigest()+ return self.runtime_dir / "references" / identity++ def _install_reference_key(self, install_dir: Path) -> tuple[str, str] | None:+ try:+ resolved = install_dir.resolve(strict=True)+ runtime_root = self.runtime_dir.resolve(strict=True)+ except (OSError, RuntimeError):+ return None+ if runtime_root not in resolved.parents:+ return None+ return str(runtime_root), str(resolved)++ def _owns_install_reference(self, key: tuple[str, str]) -> bool:+ with _INSTALL_REFERENCE_LOCKS_GUARD:+ reference = _INSTALL_REFERENCE_LOCKS.get(key)+ return bool(+ reference is not None+ and self._install_reference_owner in reference.owners+ )++ def _release_install_reference(self, key: tuple[str, str]) -> None:+ released: _ShowRuntimeInstallReference | None = None+ with _INSTALL_REFERENCE_LOCKS_GUARD:+ reference = _INSTALL_REFERENCE_LOCKS.get(key)+ if (+ reference is None+ or self._install_reference_owner not in reference.owners+ ):+ return+ reference.owners.remove(self._install_reference_owner)+ if not reference.owners:+ released = _INSTALL_REFERENCE_LOCKS.pop(key)+ if released is None:+ return+ try:+ _unlock_install_reference(released.handle)+ except OSError:+ logger.warning("Failed to release Show Runtime install reference", exc_info=True)+ try:+ released.marker.unlink(missing_ok=True)+ except OSError:+ logger.warning("Failed to remove Show Runtime install reference", exc_info=True)++ @staticmethod+ def _reference_path_matches_handle(path: Path, handle: IO[str]) -> bool:+ try:+ path_info = path.lstat()+ open_info = os.fstat(handle.fileno())+ except OSError:+ return False+ return (+ _is_exclusive_regular_file(path_info)+ and _is_exclusive_regular_file(open_info)+ and (path_info.st_dev, path_info.st_ino) == (open_info.st_dev, open_info.st_ino)+ )++ def _retain_managed_command(self, command: list[str]) -> bool:+ install_dir = self._managed_install_dir_for_command(command)+ if install_dir is None:+ return True+ with self._install_guard_locked(timeout_seconds=None) as (acquired, reason):+ if not acquired:+ self._install_reason = reason or "runtime_install_guard_unavailable"+ return False+ return self._retain_install_dir_locked(install_dir)++ def _retain_install_dir_locked(self, install_dir: Path) -> bool:+ key = self._install_reference_key(install_dir)+ if key is None:+ return False+ runtime_root = Path(key[0])+ resolved = Path(key[1])+ with _INSTALL_REFERENCE_LOCKS_GUARD:+ existing = _INSTALL_REFERENCE_LOCKS.get(key)+ if existing is not None:+ existing.owners.add(self._install_reference_owner)+ return True++ reference_dir = self._install_reference_dir(resolved)+ try:+ reference_dir.mkdir(parents=True, exist_ok=True)+ reference_info = reference_dir.lstat()+ if _is_reparse_point(reference_info) or not stat.S_ISDIR(reference_info.st_mode):+ raise OSError("reference directory is not confined")+ marker = reference_dir / f"{uuid4().hex}.lock"+ flags = os.O_RDWR | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0)+ if hasattr(os, "O_NOFOLLOW"):+ flags |= os.O_NOFOLLOW+ fd = os.open(marker, flags, 0o600)+ handle = os.fdopen(fd, "r+", encoding="utf-8")+ acquired = False+ try:+ if not self._reference_path_matches_handle(marker, handle):+ raise OSError("reference marker path changed")+ handle.seek(0)+ if not storage_lock_try_lock(handle):+ raise OSError("fresh reference marker is already locked")+ acquired = True+ handle.seek(0)+ handle.write(str(os.getpid()))+ handle.flush()+ _INSTALL_REFERENCE_LOCKS[key] = _ShowRuntimeInstallReference(+ marker=marker,+ handle=handle,+ owners={self._install_reference_owner},+ )+ return True+ except BaseException:+ if acquired:+ _unlock_install_reference(handle)+ else:+ handle.close()+ marker.unlink(missing_ok=True)+ raise+ except Exception:+ logger.warning(+ "Failed to retain Show Runtime install %s",+ resolved,+ exc_info=True,+ )+ self._install_reason = "runtime_install_guard_unavailable"+ return False++ def _install_dir_has_live_reference(self, install_dir: Path) -> bool:+ try:+ resolved = install_dir.resolve(strict=True)+ runtime_root = self.runtime_dir.resolve(strict=True)+ except (OSError, RuntimeError):+ return True+ key = (str(runtime_root), str(resolved))+ with _INSTALL_REFERENCE_LOCKS_GUARD:+ local_markers = {+ reference.marker+ for reference_key, reference in _INSTALL_REFERENCE_LOCKS.items()+ if reference_key == key+ }+ if local_markers:+ return True++ reference_dir = self._install_reference_dir(resolved)+ try:+ info = reference_dir.lstat()+ except FileNotFoundError:+ return False+ except OSError:+ return True+ if _is_reparse_point(info) or not stat.S_ISDIR(info.st_mode):+ return True+ try:+ with os.scandir(reference_dir) as entries:+ markers = sorted(+ reference_dir / entry.name+ for entry in entries+ if _INSTALL_REFERENCE_RE.fullmatch(entry.name)+ )+ except OSError:+ return True+ for marker in markers:+ try:+ marker_info = marker.lstat()+ if not _is_exclusive_regular_file(marker_info):+ return True+ flags = os.O_RDWR | getattr(os, "O_BINARY", 0)+ if hasattr(os, "O_NOFOLLOW"):+ flags |= os.O_NOFOLLOW+ fd = os.open(marker, flags)+ handle = os.fdopen(fd, "r+", encoding="utf-8")+ except FileNotFoundError:+ continue+ except OSError:+ return True+ handle.seek(0)+ if not storage_lock_try_lock(handle):+ handle.close()+ return True+ if not self._reference_path_matches_handle(marker, handle):+ _unlock_install_reference(handle)+ return True+ _unlock_install_reference(handle)+ marker.unlink(missing_ok=True)+ try:+ reference_dir.rmdir()+ except OSError:+ pass+ return False+def status(self, *, offline: bool | None = None) -> dict[str, Any]:+ """Inspect install state without turning an unreadable state into absence."""+ try:+ return self._status(offline=offline)+ except (OSError, RecursionError, UnicodeError) as exc:+ logger.warning("Show Runtime status inspection failed", exc_info=True)+ reason = "runtime_install_inspection_failed"+ evidence = ShowRuntimeFailureEvidence(+ ShowRuntimeFailureDimension.INSTALL,+ reason,+ )+ availability = ShowRuntimeAvailability.from_install(+ install_reason=reason,+ install_evidence=evidence,+ )+ payload = availability.as_payload()+ detail = str(exc).strip() or type(exc).__name__+ return {+ "provider": self.runtime_source,+ "platform": runtime_platform_tag(),+ "explicit_command": self.command if self._command_explicit else None,+ "node_available": None,+ "node_version": None,+ "node_supported": None,+ "manifest": None,+ "archive": None,+ "install": payload["install"],+ "runtime": payload["runtime"],+ "command": None,+ "reason": reason,+ "download_error": None,+ "inspection_error": {+ "kind": type(exc).__name__,+ "message": detail,+ },+ }++ def _status(self, *, offline: bool | None = None) -> dict[str, Any]:explicit_availability = (self._resolve_explicit_command_availability()if self._command_explicit@@ -1909,8 +2297,10 @@ class ShowRuntimeManager:if manifest_manager is not None and manifest is not Noneelse None)- manifest_reason = manifest_manager._install_reason if manifest_manager is not None else None- manifest_download_error = (+ source_manifest_reason = (+ manifest_manager._install_reason if manifest_manager is not None else None+ )+ source_manifest_download_error = (manifest_manager._download_error if manifest_manager is not None else None)disk_install = (@@ -1918,6 +2308,18 @@ class ShowRuntimeManager:if manifest_manager is not Noneelse None)+ disk_install_reason = (+ manifest_manager._install_reason if manifest_manager is not None else None+ )+ manifest_reason = (+ disk_install_reason+ if disk_install_reason == "runtime_install_inspection_failed"+ else source_manifest_reason+ )+ manifest_download_error = (+ source_manifest_download_error+ or (manifest_manager._download_error if manifest_manager is not None else None)+ )platform_tag = runtime_platform_tag()node = _resolve_node_command()node_version = _node_version(node) if node else None@@ -1941,10 +2343,19 @@ class ShowRuntimeManager:installed_dir = disk_install.install_dirinstalled_command = disk_install.commandinstalled_runtime_version = _persisted_manifest_runtime_version(disk_install.metadata)+ if manifest is not None and archive is not None:+ installed_matches = (+ manifest_manager.verified_entrypoint(+ disk_install.install_dir,+ manifest,+ archive,+ )+ is not None+ )if manifest_status is None:manifest_status = _persisted_manifest_status_payload(disk_install.metadata)archive_status = _persisted_archive_status_payload(disk_install.metadata)- if archive:+ if archive and disk_install is None:for candidate in manifest_manager.install_candidates(manifest, archive):entrypoint = manifest_manager.verified_entrypoint(candidate, manifest, archive)if entrypoint is None:@@ -1973,9 +2384,22 @@ class ShowRuntimeManager:managed = _resolve_executable_path(self._managed_bin_path())installed_command = [managed] if managed else Noneinstalled = installed_command is not None+ installed_dir = self._package_install_dir() if installed else Noneif installed and manifest is not None and archive is not None and installed_matches is not True:installed_matches = False- if explicit_availability is not None:+ if (+ explicit_availability is None+ and manifest_reason == "runtime_install_inspection_failed"+ ):+ evidence = ShowRuntimeFailureEvidence(+ ShowRuntimeFailureDimension.INSTALL,+ manifest_reason,+ )+ status_availability = ShowRuntimeAvailability.from_install(+ install_reason=manifest_reason,+ install_evidence=evidence,+ )+ elif explicit_availability is not None:status_availability = explicit_availabilityelse:status_availability = ShowRuntimeAvailability.from_install(@@ -2280,7 +2704,31 @@ class ShowRuntimeManager:return {"dry_run": dry_run, **result}removed: list[str] = []try:- return self._clean_locked(keep_previous=keep_previous, dry_run=dry_run, removed=removed)+ if dry_run:+ return self._clean_locked(+ keep_previous=keep_previous,+ dry_run=True,+ removed=removed,+ )+ with self._install_guard_locked(timeout_seconds=1.0) as (acquired, reason):+ if not acquired:+ skipped_reason = (+ _SKIPPED_ARCHIVE_REASON_INSPECTION_FAILED+ if reason == "runtime_install_guard_unavailable"+ else _SKIPPED_ARCHIVE_REASON_INSTALL_RUNNING+ )+ return {+ "ok": False,+ "dry_run": False,+ "removed": [],+ "reason": reason,+ "archives": self._skipped_archive_report(skipped_reason),+ }+ return self._clean_locked(+ keep_previous=keep_previous,+ dry_run=False,+ removed=removed,+ )except Exception:# A planning failure (e.g. an install dir disappearing mid-scan)# must return the structured inspection-failure report, never an@@ -2327,6 +2775,22 @@ class ShowRuntimeManager:if not dry_run:shutil.rmtree(path, ignore_errors=True)removed.append(str(path))+ if self.runtime_source == _RUNTIME_SOURCE_ARCHIVE:+ self._clean_provider_install_dirs(+ self.runtime_dir / "prebuilt",+ provider=_RUNTIME_SOURCE_ARCHIVE,+ keep_previous=keep_previous,+ dry_run=dry_run,+ removed=removed,+ )+ elif self.runtime_source == _RUNTIME_SOURCE_NPM:+ self._clean_provider_install_dirs(+ self.runtime_dir / "package",+ provider=_RUNTIME_SOURCE_NPM,+ keep_previous=keep_previous,+ dry_run=dry_run,+ removed=removed,+ )archives = self._clean_downloaded_archives(dry_run=dry_run)if dry_run and self._preview_raced_busy():return {@@ -2342,6 +2806,82 @@ class ShowRuntimeManager:"archives": archives,}+ def _clean_provider_install_dirs(+ self,+ namespace: Path,+ *,+ provider: str,+ keep_previous: int,+ dry_run: bool,+ removed: list[str],+ ) -> None:+ versions_dir = namespace / "versions"+ try:+ versions_info = versions_dir.lstat()+ except FileNotFoundError:+ return+ if _is_reparse_point(versions_info) or not stat.S_ISDIR(versions_info.st_mode):+ raise OSError(f"runtime versions directory is not confined: {versions_dir}")+ pointer_path = namespace / "current.json"+ try:+ pointer = json.loads(pointer_path.read_text(encoding="utf-8"))+ current = Path(pointer["install_dir"]).expanduser().resolve(strict=True)+ resolved_versions = versions_dir.resolve(strict=True)+ except FileNotFoundError:+ return+ except (KeyError, OSError, RuntimeError, TypeError, UnicodeError, ValueError) as exc:+ raise OSError(f"runtime pointer is unreadable: {pointer_path}") from exc+ if pointer.get("provider") != provider or current.parent != resolved_versions:+ raise OSError(f"runtime pointer is not confined: {pointer_path}")++ records: list[tuple[Path, float]] = []+ with os.scandir(versions_dir) as entries:+ for entry in entries:+ try:+ if not entry.is_dir(follow_symlinks=False):+ continue+ path = Path(entry.path)+ resolved = path.resolve(strict=True)+ if resolved.parent != resolved_versions:+ continue+ metadata = json.loads(+ (path / ".vibe-show-runtime.json").read_text(encoding="utf-8")+ )+ if (+ metadata.get("provider") != provider+ or metadata.get("runtime_id") != "show-runtime"+ ):+ continue+ records.append((path, entry.stat(follow_symlinks=False).st_mtime))+ except FileNotFoundError:+ continue+ except (OSError, RuntimeError, UnicodeError, ValueError) as exc:+ raise OSError(f"runtime install cannot be inspected: {entry.path}") from exc++ protected = {current}+ ranked: list[tuple[Path, float]] = []+ for path, mtime in records:+ resolved = path.resolve(strict=True)+ if self._install_dir_has_live_reference(resolved):+ protected.add(resolved)+ else:+ ranked.append((path, mtime))+ rollback = sorted(+ (item for item in ranked if item[0].resolve(strict=True) != current),+ key=lambda item: item[1],+ reverse=True,+ )+ protected.update(+ path.resolve(strict=True)+ for path, _mtime in rollback[: max(0, keep_previous)]+ )+ for path, _mtime in records:+ if path.resolve(strict=True) in protected:+ continue+ if not dry_run:+ shutil.rmtree(path)+ removed.append(str(path))+def archive_cache_status(self, *, keep_previous: int = 1) -> dict[str, Any]:"""Report reclaimable content-addressed archives without deleting anything.@@ -2742,13 +3282,35 @@ class ShowRuntimeManager:offline: bool | None = None,automatic: bool = False,) -> dict[str, Any]:- effective_force = self.force_install if force is None else force- effective_offline = self.offline if offline is None else offline- admission, operation = self._attempt_managed_install(- force=effective_force,- offline=effective_offline,+ return self._prepare(+ force=force,+ offline=offline,automatic=automatic,)++ def _prepare(+ self,+ *,+ force: bool | None,+ offline: bool | None,+ automatic: bool,+ candidate_validator: Callable[[list[str]], ShowRuntimeStartability] | None = None,+ ) -> dict[str, Any]:+ effective_force = self.force_install if force is None else force+ effective_offline = self.offline if offline is None else offline+ if candidate_validator is None:+ admission, operation = self._attempt_managed_install(+ force=effective_force,+ offline=effective_offline,+ automatic=automatic,+ )+ else:+ admission, operation = self._attempt_managed_install(+ force=effective_force,+ offline=effective_offline,+ automatic=automatic,+ candidate_validator=candidate_validator,+ )payload = admission.as_payload()payload["ok"] = operation.okif not operation.ok:@@ -2763,6 +3325,212 @@ class ShowRuntimeManager:)return payload+ def _verify_startability(self, command_value: Any) -> ShowRuntimeStartability:+ command = command_value if isinstance(command_value, list) else []+ if not command:+ return ShowRuntimeStartability.not_startable("runtime_command_missing")+ try:+ with tempfile.TemporaryDirectory(+ prefix="avibe-show-runtime-repair-"+ ) as verification_root_value:+ verification_root = Path(verification_root_value)+ verifier = ShowRuntimeManager(+ command=shlex.join(str(part) for part in command),+ workspace_root=verification_root / "show",+ runtime_dir=verification_root / "runtime",+ auto_install=False,+ )+ try:+ result = asyncio.run(verifier.ensure())+ finally:+ verifier.stop()+ except Exception as exc: # noqa: BLE001+ detail = str(exc).strip() or type(exc).__name__+ return ShowRuntimeStartability.undetermined(detail)+ if result.available:+ return ShowRuntimeStartability.startable()+ return ShowRuntimeStartability.not_startable(+ result.reason or "runtime_start_failed"+ )++ def repair(self) -> dict[str, Any]:+ """Verify startability, then publish only a startable replacement."""++ before = self.status()+ before_install = (+ before.get("install") if isinstance(before.get("install"), dict) else {}+ )+ before_installed = before_install.get("state") == "installed"+ before_install_dir = before_install.get("install_dir")+ provider = before.get("provider")+ platform_tag = before.get("platform")++ def outcome(+ state: str,+ *,+ ok: bool,+ reason: str | None = None,+ verification: ShowRuntimeStartability | None = None,+ verification_phase: str | None = None,+ repair_attempted: bool = False,+ prepared: Mapping[str, Any] | None = None,+ ) -> dict[str, Any]:+ prepared_status = (+ prepared.get("status")+ if prepared is not None and isinstance(prepared.get("status"), dict)+ else {}+ )+ prepared_install = (+ prepared_status.get("install")+ if isinstance(prepared_status.get("install"), dict)+ else before_install+ )+ download_error = (+ prepared_status.get("download_error")+ if isinstance(prepared_status.get("download_error"), dict)+ else before.get("download_error")+ )+ return {+ "ok": ok,+ "outcome": state,+ "reason": reason,+ "verification": verification.as_payload() if verification else None,+ "verification_phase": verification_phase,+ "repair_attempted": repair_attempted,+ "was_installed": before_installed,+ "provider": (+ prepared.get("provider") if prepared is not None else provider+ ),+ "platform": (+ prepared.get("platform") if prepared is not None else platform_tag+ ),+ "install_dir": prepared_install.get("install_dir"),+ "installed": prepared_install.get("state") == "installed",+ "command": (+ prepared_status.get("command")+ if prepared is not None+ else before.get("command")+ ),+ "download_error": download_error,+ "start_error": verification.detail if verification else None,+ "explicit_command": before.get("explicit_command"),+ "archive_url": (+ before.get("archive", {}).get("url")+ if isinstance(before.get("archive"), dict)+ else None+ ),+ "before_install_dir": before_install_dir,+ "inspection_error": before.get("inspection_error"),+ }++ if (+ before_install.get("state") == "failed"+ and before.get("reason") == "runtime_install_inspection_failed"+ ):+ return outcome(+ "failed",+ ok=False,+ reason="runtime_install_inspection_failed",+ )++ if before_installed:+ command = before.get("command")+ if isinstance(command, list) and not self._retain_managed_command(command):+ verification = ShowRuntimeStartability.undetermined(+ self._install_reason or "runtime_install_guard_unavailable"+ )+ return outcome(+ "failed",+ ok=False,+ reason="runtime_start_verification_failed",+ verification=verification,+ verification_phase="before",+ )+ verification = self._verify_startability(command)+ if verification.state is ShowRuntimeStartabilityState.UNDETERMINED:+ return outcome(+ "failed",+ ok=False,+ reason="runtime_start_verification_failed",+ verification=verification,+ verification_phase="before",+ )+ if verification.state is ShowRuntimeStartabilityState.STARTABLE:+ return outcome(+ "healthy",+ ok=True,+ verification=verification,+ verification_phase="before",+ )+ if before.get("explicit_command"):+ return outcome(+ "failed",+ ok=False,+ reason=verification.reason or "runtime_start_failed",+ verification=verification,+ verification_phase="before",+ )++ archive = before.get("archive") if isinstance(before.get("archive"), dict) else {}+ archive_url = str(archive.get("url") or "")+ if (+ before.get("provider") == _RUNTIME_SOURCE_ARCHIVE+ and "github.com/avibe-bot/vibe-show-runtime/releases/latest/download/"+ in archive_url+ ):+ return outcome(+ "failed",+ ok=False,+ reason="runtime_legacy_archive_unavailable",+ verification=(verification if before_installed else None),+ verification_phase=("before" if before_installed else None),+ )++ candidate_verification: ShowRuntimeStartability | None = None++ def validate_candidate(command: list[str]) -> ShowRuntimeStartability:+ nonlocal candidate_verification+ candidate_verification = self._verify_startability(command)+ return candidate_verification++ prepared = self._prepare(+ force=before_installed,+ offline=None,+ automatic=False,+ candidate_validator=validate_candidate,+ )+ if prepared.get("ok") and candidate_verification is not None:+ return outcome(+ "repaired",+ ok=True,+ verification=candidate_verification,+ verification_phase="after",+ repair_attempted=True,+ prepared=prepared,+ )+ reason = str(prepared.get("reason") or "runtime_prepare_failed")+ return outcome(+ "failed",+ ok=False,+ reason=reason,+ verification=(+ candidate_verification+ if candidate_verification is not None+ else verification+ if before_installed+ else None+ ),+ verification_phase=(+ "after"+ if candidate_verification is not None+ else "before"+ if before_installed+ else None+ ),+ repair_attempted=True,+ prepared=prepared,+ )+def _configured_manifest_source(self) -> str:if self.manifest_path is not None:return str(self.manifest_path)@@ -2778,7 +3546,8 @@ class ShowRuntimeManager:entrypoint = manager.resolve_selected_entrypoint()if entrypoint is not None:self._adopt_shared_manifest_evidence(manager)- return [*node, str(entrypoint)]+ command = [*node, str(entrypoint)]+ return command if self._retain_managed_command(command) else Nonesource_reason = manager._install_reasonsource_download_error = manager._download_error@@ -2795,7 +3564,8 @@ class ShowRuntimeManager:manager._install_reason = source_reasonmanager._download_error = source_download_errorself._adopt_shared_manifest_evidence(manager)- return disk_install.command if disk_install else None+ command = disk_install.command if disk_install else None+ return command if command and self._retain_managed_command(command) else Nonedef _shared_manifest_disk_install(self,@@ -2858,7 +3628,7 @@ class ShowRuntimeManager:self._install_reason = None@contextlib.contextmanager- def _install_guard_locked(self, *, timeout_seconds: float = 0.0):+ def _install_guard_locked(self, *, timeout_seconds: float | None = 0.0):"""Serialize installs and archive cleanup, across processes too.Yields a ``(acquired, reason)`` pair. ``acquired`` is True when the@@ -2936,7 +3706,11 @@ class ShowRuntimeManager:returnfile_lock = MigrationFileLock(self._install_guard_path, timeout_seconds=timeout_seconds)file_lock._handle = os.fdopen(lock_fd, "a+", encoding="utf-8")- deadline = time.monotonic() + timeout_seconds+ deadline = (+ None+ if timeout_seconds is None+ else time.monotonic() + timeout_seconds+ )while True:file_lock._handle.seek(0)if storage_lock_try_lock(file_lock._handle):@@ -2945,7 +3719,7 @@ class ShowRuntimeManager:file_lock._handle.write(str(os.getpid()))file_lock._handle.flush()break- if time.monotonic() >= deadline:+ if deadline is not None and time.monotonic() >= deadline:file_lock._handle.close()yield busyreturn@@ -2986,7 +3760,13 @@ class ShowRuntimeManager:except Exception:logger.warning("Failed to release Show Runtime install guard", exc_info=True)- def _install_manifest_runtime_locked(self, *, force: bool, offline: bool) -> list[str] | None:+ def _install_manifest_runtime_locked(+ self,+ *,+ force: bool,+ offline: bool,+ candidate_validator: Callable[[list[str]], ShowRuntimeStartability] | None = None,+ ) -> list[str] | None:node = _resolve_node_command()if not node:self._install_reason = "runtime_node_missing"@@ -2994,7 +3774,34 @@ class ShowRuntimeManager:if force:self._invalidate_managed_runtime_projection()manager = self._shared_manifest_manager(offline=offline)- result = manager.ensure(force=force)+ retained_publication_key: tuple[str, str] | None = None++ def validate_entrypoint(entrypoint: Path) -> str | None:+ nonlocal retained_publication_key+ command = [*node, str(entrypoint)]+ if candidate_validator is not None:+ outcome = candidate_validator(command)+ if outcome.state is ShowRuntimeStartabilityState.NOT_STARTABLE:+ return outcome.reason or "runtime_start_failed"+ if outcome.state is ShowRuntimeStartabilityState.UNDETERMINED:+ return "runtime_start_verification_failed"+ install_dir = self._managed_install_dir_for_command(command)+ key = self._install_reference_key(install_dir) if install_dir else None+ if key is None:+ return "runtime_install_guard_unavailable"+ already_owned = self._owns_install_reference(key)+ if not self._retain_install_dir_locked(install_dir):+ return self._install_reason or "runtime_install_guard_unavailable"+ if not already_owned:+ retained_publication_key = key+ return None++ result = manager.ensure(+ force=force,+ validate_candidate=validate_entrypoint,+ )+ if not result.get("ok") and retained_publication_key is not None:+ self._release_install_reference(retained_publication_key)self._adopt_shared_manifest_evidence(manager, result)entrypoint = manager.installed_result_entrypoint(result)if (@@ -3013,9 +3820,16 @@ class ShowRuntimeManager:node = _resolve_node_command()if not node:return None- return self._archive_runtime_command(self._archive_install_dir(), node)+ command = self._archive_runtime_command(self._archive_install_dir(), node)+ return command if command and self._retain_managed_command(command) else None- def _install_archive_runtime(self, *, force: bool, offline: bool | None = None) -> list[str] | None:+ def _install_archive_runtime(+ self,+ *,+ force: bool,+ offline: bool | None = None,+ candidate_validator: Callable[[list[str]], ShowRuntimeStartability] | None = None,+ ) -> list[str] | None:node = _resolve_node_command()if not node:self._install_reason = "runtime_node_missing"@@ -3023,6 +3837,8 @@ class ShowRuntimeManager:self.runtime_dir.mkdir(parents=True, exist_ok=True)install_dir = self._archive_install_dir()existing_command = self._archive_runtime_command(install_dir, node)+ if existing_command and not self._retain_managed_command(existing_command):+ existing_command = Nonearchive = self._resolve_prebuilt_archive(offline=offline)if not archive:return self._managed_install_operation_command(@@ -3031,11 +3847,18 @@ class ShowRuntimeManager:)archive_digest = file_sha256(archive)if not force and existing_command and self._archive_manifest_matches(archive_digest):+ if candidate_validator is not None:+ validation = candidate_validator(existing_command)+ if validation.state is not ShowRuntimeStartabilityState.STARTABLE:+ self._install_reason = self._startability_failure_reason(validation)+ return Nonereturn self._managed_install_operation_command(existing_command,replacement_required=False,)tmp_dir = Path(tempfile.mkdtemp(prefix="prebuilt-", dir=self.runtime_dir))+ candidate_dir: Path | None = None+ retained_publication_key: tuple[str, str] | None = Nonetry:with tarfile.open(archive, "r:gz") as tar:safe_extract_tar(tar, tmp_dir)@@ -3046,20 +3869,51 @@ class ShowRuntimeManager:existing_command,replacement_required=force,)- if os.path.lexists(install_dir):- if not self._remove_managed_runtime_tree_for_replacement(install_dir, label="archive"):+ versions_dir = self.runtime_dir / "prebuilt" / "versions"+ versions_dir.mkdir(parents=True, exist_ok=True)+ candidate_dir = Path(+ tempfile.mkdtemp(+ prefix=f"{archive_digest[:16]}-",+ dir=versions_dir,+ )+ )+ candidate_dir.rmdir()+ shutil.move(str(tmp_dir), str(candidate_dir))+ self._write_archive_manifest(archive_digest, install_dir=candidate_dir)+ installed_command = self._archive_runtime_command(candidate_dir, node)+ if not installed_command:+ self._install_reason = "runtime_install_missing_bin"+ return self._managed_install_operation_command(+ existing_command,+ replacement_required=force,+ )+ if candidate_validator is not None:+ validation = candidate_validator(installed_command)+ if validation.state is not ShowRuntimeStartabilityState.STARTABLE:+ self._install_reason = self._startability_failure_reason(validation)return self._managed_install_operation_command(- None,+ existing_command,replacement_required=force,)- existing_command = None- install_dir.parent.mkdir(parents=True, exist_ok=True)- shutil.move(str(tmp_dir), str(install_dir))- self._write_archive_manifest(archive_digest)- installed_command = self._archive_runtime_command(install_dir, node)- if not installed_command:- self._install_reason = "runtime_install_missing_bin"- # The staged tree was moved onto the managed identity before this command resolved.+ reference_key = self._install_reference_key(candidate_dir)+ already_owned = bool(+ reference_key is not None+ and self._owns_install_reference(reference_key)+ )+ if not self._retain_managed_command(installed_command):+ self._install_reason = self._install_reason or "runtime_install_guard_unavailable"+ return self._managed_install_operation_command(+ existing_command,+ replacement_required=force,+ )+ if reference_key is not None and not already_owned:+ retained_publication_key = reference_key+ self._write_provider_pointer(+ self.runtime_dir / "prebuilt",+ candidate_dir,+ provider=_RUNTIME_SOURCE_ARCHIVE,+ )+ candidate_dir = Nonereturn self._managed_install_operation_command(installed_command,replacement_required=force,@@ -3073,6 +3927,10 @@ class ShowRuntimeManager:replacement_required=force,)finally:+ if candidate_dir is not None:+ if retained_publication_key is not None:+ self._release_install_reference(retained_publication_key)+ shutil.rmtree(candidate_dir, ignore_errors=True)if tmp_dir.exists():shutil.rmtree(tmp_dir, ignore_errors=True)@@ -3132,29 +3990,42 @@ class ShowRuntimeManager:return targetdef _archive_install_dir(self) -> Path:- return self.runtime_dir / "prebuilt" / "current"+ return self._selected_provider_install_dir(+ self.runtime_dir / "prebuilt",+ legacy=self.runtime_dir / "prebuilt" / "current",+ provider=_RUNTIME_SOURCE_ARCHIVE,+ )- def _archive_manifest_path(self) -> Path:- return self._archive_install_dir() / ".vibe-show-runtime.json"+ def _archive_manifest_path(self, install_dir: Path | None = None) -> Path:+ return (install_dir or self._archive_install_dir()) / ".vibe-show-runtime.json"- def _archive_manifest_matches(self, archive_digest: str) -> bool:+ def _archive_manifest_matches(+ self,+ archive_digest: str,+ *,+ install_dir: Path | None = None,+ ) -> bool:try:- payload = json.loads(self._archive_manifest_path().read_text(encoding="utf-8"))+ payload = json.loads(+ self._archive_manifest_path(install_dir).read_text(encoding="utf-8")+ )except Exception:return Falsereturn payload.get("archive_name") == _runtime_archive_name() and payload.get("sha256") == archive_digest- def _write_archive_manifest(self, archive_digest: str) -> None:- self._archive_manifest_path().write_text(+ def _write_archive_manifest(self, archive_digest: str, *, install_dir: Path) -> None:+ write_atomic(+ self._archive_manifest_path(install_dir),json.dumps({+ "provider": _RUNTIME_SOURCE_ARCHIVE,+ "runtime_id": "show-runtime","archive_name": _runtime_archive_name(),"sha256": archive_digest,},sort_keys=True,)+ "\n",- encoding="utf-8",)def _archive_runtime_command(self, install_dir: Path, node: list[str]) -> list[str] | None:@@ -3163,7 +4034,12 @@ class ShowRuntimeManager:return Nonereturn [*node, str(cli_path)]- def _install_npm_runtime(self, *, force: bool | None = None) -> list[str] | None:+ def _install_npm_runtime(+ self,+ *,+ force: bool | None = None,+ candidate_validator: Callable[[list[str]], ShowRuntimeStartability] | None = None,+ ) -> list[str] | None:replacement_required = self.force_install if force is None else forcetry:npm = _resolve_command("npm")@@ -3176,18 +4052,15 @@ class ShowRuntimeManager:replacement_required=replacement_required,)self.runtime_dir.mkdir(parents=True, exist_ok=True)- install_root = self.runtime_dir / "package"- install_root.mkdir(parents=True, exist_ok=True)- package_json = install_root / "package.json"- if not package_json.exists():- package_json.write_text('{"private":true,"type":"module"}\n', encoding="utf-8")- if replacement_required:- managed_tree = install_root / "node_modules"- if not self._remove_managed_runtime_tree_for_replacement(managed_tree, label="npm"):- return self._managed_install_operation_command(- None,- replacement_required=True,- )+ existing_command_value = _resolve_executable_path(self._managed_bin_path())+ existing_command = [existing_command_value] if existing_command_value else None+ if existing_command and not self._retain_managed_command(existing_command):+ existing_command = None+ staging_root = Path(tempfile.mkdtemp(prefix="npm-", dir=self.runtime_dir))+ package_json = staging_root / "package.json"+ package_json.write_text('{"private":true,"type":"module"}\n', encoding="utf-8")+ candidate_dir: Path | None = None+ retained_publication_key: tuple[str, str] | None = Nonetry:with self.install_log_path.open("w", encoding="utf-8") as log:result = subprocess.run(@@ -3195,7 +4068,7 @@ class ShowRuntimeManager:*npm,"install","--prefix",- str(install_root),+ str(staging_root),"--no-audit","--no-fund",self.package_spec,@@ -3210,33 +4083,149 @@ class ShowRuntimeManager:except (OSError, subprocess.SubprocessError):logger.warning("Failed to install the npm Show Runtime", exc_info=True)self._install_reason = "runtime_install_failed"+ shutil.rmtree(staging_root, ignore_errors=True)return self._managed_install_operation_command(- None,+ existing_command,replacement_required=replacement_required,)if result.returncode != 0:self._install_reason = "runtime_install_failed"+ shutil.rmtree(staging_root, ignore_errors=True)return self._managed_install_operation_command(- None,+ existing_command,replacement_required=replacement_required,)- resolved = _resolve_executable_path(self._managed_bin_path())- if not resolved:- self._install_reason = "runtime_install_missing_bin"+ try:+ resolved = _resolve_executable_path(self._npm_bin_path(staging_root))+ if not resolved:+ self._install_reason = "runtime_install_missing_bin"+ return self._managed_install_operation_command(+ existing_command,+ replacement_required=replacement_required,+ )+ versions_dir = self.runtime_dir / "package" / "versions"+ versions_dir.mkdir(parents=True, exist_ok=True)+ candidate_dir = Path(tempfile.mkdtemp(prefix="npm-", dir=versions_dir))+ candidate_dir.rmdir()+ shutil.move(str(staging_root), str(candidate_dir))+ installed_value = _resolve_executable_path(self._npm_bin_path(candidate_dir))+ if not installed_value:+ self._install_reason = "runtime_install_missing_bin"+ return self._managed_install_operation_command(+ existing_command,+ replacement_required=replacement_required,+ )+ installed_command = [installed_value]+ write_atomic(+ candidate_dir / ".vibe-show-runtime.json",+ json.dumps(+ {+ "provider": _RUNTIME_SOURCE_NPM,+ "runtime_id": "show-runtime",+ "package_spec": self.package_spec,+ },+ sort_keys=True,+ )+ + "\n",+ )+ if candidate_validator is not None:+ validation = candidate_validator(installed_command)+ if validation.state is not ShowRuntimeStartabilityState.STARTABLE:+ self._install_reason = self._startability_failure_reason(validation)+ return self._managed_install_operation_command(+ existing_command,+ replacement_required=replacement_required,+ )+ reference_key = self._install_reference_key(candidate_dir)+ already_owned = bool(+ reference_key is not None+ and self._owns_install_reference(reference_key)+ )+ if not self._retain_managed_command(installed_command):+ self._install_reason = self._install_reason or "runtime_install_guard_unavailable"+ return self._managed_install_operation_command(+ existing_command,+ replacement_required=replacement_required,+ )+ if reference_key is not None and not already_owned:+ retained_publication_key = reference_key+ self._write_provider_pointer(+ self.runtime_dir / "package",+ candidate_dir,+ provider=_RUNTIME_SOURCE_NPM,+ )+ candidate_dir = Nonereturn self._managed_install_operation_command(- None,+ installed_command,replacement_required=replacement_required,+ replacement_completed=replacement_required,)- # A forced install starts with no node_modules tree, so this command proves replacement.- return self._managed_install_operation_command(- [resolved],- replacement_required=replacement_required,- replacement_completed=replacement_required,- )+ finally:+ if candidate_dir is not None:+ if retained_publication_key is not None:+ self._release_install_reference(retained_publication_key)+ shutil.rmtree(candidate_dir, ignore_errors=True)+ if staging_root.exists():+ shutil.rmtree(staging_root, ignore_errors=True)def _managed_bin_path(self) -> Path:+ return self._npm_bin_path(self._package_install_dir())++ def _package_install_dir(self) -> Path:+ return self._selected_provider_install_dir(+ self.runtime_dir / "package",+ legacy=self.runtime_dir / "package",+ provider=_RUNTIME_SOURCE_NPM,+ )++ @staticmethod+ def _npm_bin_path(install_dir: Path) -> Path:suffix = ".cmd" if os.name == "nt" else ""- return self.runtime_dir / "package" / "node_modules" / ".bin" / f"{_RUNTIME_BIN}{suffix}"+ return install_dir / "node_modules" / ".bin" / f"{_RUNTIME_BIN}{suffix}"++ @staticmethod+ def _startability_failure_reason(validation: ShowRuntimeStartability) -> str:+ if validation.state is ShowRuntimeStartabilityState.NOT_STARTABLE:+ return validation.reason or "runtime_start_failed"+ return "runtime_start_verification_failed"++ def _selected_provider_install_dir(+ self,+ namespace: Path,+ *,+ legacy: Path,+ provider: str,+ ) -> Path:+ pointer_path = namespace / "current.json"+ try:+ payload = json.loads(pointer_path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return legacy+ except (OSError, UnicodeError, ValueError) as exc:+ raise OSError(f"runtime pointer is unreadable: {pointer_path}") from exc+ try:+ install_dir = Path(payload["install_dir"]).expanduser().resolve(strict=True)+ versions_dir = (namespace / "versions").resolve(strict=True)+ except (KeyError, OSError, RuntimeError, TypeError) as exc:+ raise OSError(f"runtime pointer is unreadable: {pointer_path}") from exc+ if payload.get("provider") != provider or install_dir.parent != versions_dir:+ raise OSError(f"runtime pointer is not confined: {pointer_path}")+ return install_dir++ @staticmethod+ def _write_provider_pointer(namespace: Path, install_dir: Path, *, provider: str) -> None:+ write_atomic(+ namespace / "current.json",+ json.dumps(+ {+ "provider": provider,+ "runtime_id": "show-runtime",+ "install_dir": str(install_dir),+ },+ sort_keys=True,+ )+ + "\n",+ )_manager: ShowRuntimeManager | None = Nonediff --git a/core/show_runtime_failures.py b/core/show_runtime_failures.pyindex 35e376cbd..7a358a718 100644--- a/core/show_runtime_failures.py+++ b/core/show_runtime_failures.py@@ -191,6 +191,42 @@ _FAILURE_DECLARATION_ROWS = (ShowRuntimeFailureClass.UNCLASSIFIED,ShowRuntimeRecoveryAction.REPAIR,),+ ShowRuntimeFailureDeclaration(+ "runtime_install_inspection_failed",+ ShowRuntimeFailureDimension.INSTALL,+ "runtime-status",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.NO_LOCAL_ACTION,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_start_verification_failed",+ ShowRuntimeFailureDimension.INSTALL,+ "verified-repair",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.NO_LOCAL_ACTION,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_start_failed",+ ShowRuntimeFailureDimension.INSTALL,+ "verified-repair-candidate",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_prepare_failed",+ ShowRuntimeFailureDimension.INSTALL,+ "verified-repair",+ ShowRuntimeFailureClass.UNCLASSIFIED,+ ShowRuntimeRecoveryAction.REPAIR,+ ),+ ShowRuntimeFailureDeclaration(+ "runtime_legacy_archive_unavailable",+ ShowRuntimeFailureDimension.INSTALL,+ "legacy-archive-provider",+ ShowRuntimeFailureClass.CONFIGURED,+ ShowRuntimeRecoveryAction.CHANGE_SETTING,+ True,+ ),ShowRuntimeFailureDeclaration("runtime_install_failed",ShowRuntimeFailureDimension.INSTALL,diff --git a/docs/plans/show-runtime-verified-repair.md b/docs/plans/show-runtime-verified-repair.mdnew file mode 100644index 000000000..12ec5b1fa--- /dev/null+++ b/docs/plans/show-runtime-verified-repair.md@@ -0,0 +1,57 @@+# Show Runtime Verified Repair and Status++## Background++At `origin/master` commit `1aae3e0e02c1ae30391a047886480032269fa37f`,+the Settings dependency job and Doctor did not share one repair contract:++- Settings called `ShowRuntimeManager.prepare(force=True)` directly. A healthy+ managed runtime could therefore be replaced without first observing a start+ failure.+- Doctor privately implemented isolated startability verification before and+ after installation. That policy was unavailable to other callers.+- `dependencies_status()` caught every exception raised while inspecting Show+ Runtime and fabricated `install.state=absent`. Settings consequently exposed+ an absence-based install action when the actual state was unknown.++The managed manifest installer already staged downloads before publishing its+`current.json` pointer, but Show Runtime selected destructive same-identity+replacement on force. Direct archive and npm compatibility providers also+installed into mutable fixed paths. Cleanup did not retain paths referenced by+cached commands or live managers.++## Goal++Make `ShowRuntimeManager` the single owner of authoritative status and verified+repair for both Settings and Doctor. Repair must mutate an installation only+after an observed start failure. Inspection or verification uncertainty must be+non-destructive, and a replacement must start successfully before publication.++## Contract++1. `status()` converts expected operational inspection failures into structured+ `install.state=failed` evidence. Programming defects still propagate.+2. `repair()` verifies an installed command in an isolated workspace. A healthy+ runtime is returned unchanged; an undetermined check never installs; only an+ observed start failure authorizes replacement.+3. Candidate verification runs before pointer publication. Manifest, archive,+ and npm replacements use immutable generation directories so a failed+ candidate leaves the prior installation available.+4. Commands returned by a manager retain their generation. Cleanup preserves+ current, live, and cached references across identities while applying the+ existing rollback budget only to unreferenced generations.+5. Settings keeps its asynchronous job and polling surface, and Doctor remains+ a presentation adapter. Neither caller reimplements verification or status+ projection semantics.++## Validation++- Shared manager tests cover pre-publication validation and failure vocabulary.+- Show Runtime tests cover healthy, failed, and undetermined verification;+ immutable failed replacement; pointer preservation; cached/live references;+ and identity-specific cleanup.+- API and CLI tests exercise both callers through the same real manager owner.+- Settings API and component tests distinguish structured inspection failure+ from true absence, preserve evidence, and suppress unsafe actions.+- Focused backend tests, changed-file Ruff checks, UI tests, UI build, exact-head+ Codex review, and required GitHub Actions checks gate delivery.diff --git a/tests/test_local_deps.py b/tests/test_local_deps.pyindex d96cf0495..1bd6325ba 100644--- a/tests/test_local_deps.py+++ b/tests/test_local_deps.py@@ -1396,6 +1396,177 @@ def test_dependencies_status_projects_show_runtime_identity_without_pairing(monkassert {key: entry[key] for key in expected} == expected+def _stub_dependency_status_neighbors(monkeypatch) -> None:+ import core.tmux_runtime as tmux_runtime++ monkeypatch.setattr(+ api,+ "askill_update_status",+ lambda **_: {+ "installed": True,+ "version": "0.1.14",+ "latest_version": None,+ "has_update": False,+ "status": "ready",+ },+ )+ monkeypatch.setattr(+ api,+ "avault_status",+ lambda: {"installed": True, "version": "0.0.1", "status": "ready"},+ )+ monkeypatch.setattr(+ api,+ "_memory_dependencies_status",+ lambda **_: (+ {"id": "memory-package", "status": "not_required"},+ {"id": "memory-runtime", "status": "not_required"},+ ),+ )+ monkeypatch.setattr(+ tmux_runtime,+ "tmux_status",+ lambda: {"installed": False, "version": None, "status": "missing"},+ )+++def test_dependencies_status_preserves_show_runtime_inspection_failure(monkeypatch, tmp_path):+ import core.show_runtime as show_runtime++ _stub_dependency_status_neighbors(monkeypatch)+ runtime_dir = tmp_path / "runtime"+ pointer = runtime_dir / "prebuilt" / "current.json"+ pointer.parent.mkdir(parents=True)+ pointer.write_text(+ json.dumps(+ {+ "provider": "archive",+ "runtime_id": "show-runtime",+ "install_dir": str(runtime_dir / "prebuilt" / "versions" / "missing"),+ }+ ),+ encoding="utf-8",+ )+ manager = show_runtime.ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=runtime_dir,+ runtime_source="archive",+ )+ monkeypatch.setattr(show_runtime, "get_show_runtime_manager", lambda: manager)+ pointer_before = pointer.read_bytes()++ entry = next(+ item+ for item in api.dependencies_status()["deps"]+ if item["id"] == "show-runtime"+ )++ assert entry["installed"] is None+ assert entry["status"] == "error"+ assert entry["action_class"] == "operator_only"+ assert entry["reason"] == "runtime_install_inspection_failed"+ assert entry["inspection_error"]["kind"] == "OSError"+ repair = manager.repair()+ assert repair["reason"] == "runtime_install_inspection_failed"+ assert repair["repair_attempted"] is False+ assert pointer.read_bytes() == pointer_before+++def test_dependencies_status_keeps_true_show_runtime_absence_installable(monkeypatch, tmp_path):+ import core.show_runtime as show_runtime++ _stub_dependency_status_neighbors(monkeypatch)+ manager = show_runtime.ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="archive",+ archive_path=tmp_path / "runtime.tgz",+ )+ monkeypatch.setattr(show_runtime, "get_show_runtime_manager", lambda: manager)++ entry = next(+ item+ for item in api.dependencies_status()["deps"]+ if item["id"] == "show-runtime"+ )++ assert entry["installed"] is False+ assert entry["status"] == "missing"+ assert entry["action_class"] == "repairable"+ assert entry["reason"] is None+++def test_dependencies_status_keeps_node_ready_for_explicit_runtime_config_failure(+ monkeypatch,+ tmp_path,+):+ import core.show_runtime as show_runtime++ _stub_dependency_status_neighbors(monkeypatch)+ monkeypatch.setattr(+ show_runtime,+ "_resolve_command",+ lambda command: ["node"] if command == "node" else None,+ )+ manager = show_runtime.ShowRuntimeManager(+ command=str(tmp_path / "missing-runtime"),+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )+ monkeypatch.setattr(show_runtime, "get_show_runtime_manager", lambda: manager)++ by_id = {item["id"]: item for item in api.dependencies_status()["deps"]}++ assert by_id["show-runtime"]["installed"] is None+ assert by_id["show-runtime"]["status"] == "error"+ assert by_id["show-runtime"]["reason"] == "runtime_command_missing"+ assert by_id["show-runtime"]["action_class"] == "operator_only"+ assert by_id["node"]["installed"] is True+ assert by_id["node"]["status"] == "ready"+++def test_show_runtime_status_does_not_hide_programming_defects(monkeypatch, tmp_path):+ from core.show_runtime import ShowRuntimeManager++ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )+ monkeypatch.setattr(manager, "_status", lambda **_kwargs: (_ for _ in ()).throw(TypeError("bug")))++ with pytest.raises(TypeError, match="bug"):+ manager.status()+++def test_settings_and_doctor_consume_the_same_verified_repair_owner(monkeypatch, tmp_path):+ import core.show_runtime as show_runtime+ from vibe import cli++ manager = show_runtime.ShowRuntimeManager(+ command="/bin/echo",+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ auto_install=False,+ )+ verification_calls = []++ def verify(command):+ verification_calls.append(command)+ return show_runtime.ShowRuntimeStartability.startable()++ monkeypatch.setattr(manager, "_verify_startability", verify)+ monkeypatch.setattr(show_runtime, "get_show_runtime_manager", lambda: manager)+ monkeypatch.setattr(show_runtime, "ShowRuntimeManager", lambda: manager)++ settings = api._prepare_show_runtime_job()+ doctor = cli._repair_show_runtime()++ assert settings["outcome"] == "healthy"+ assert settings["changed"] is False+ assert doctor["status"] == "skipped"+ assert verification_calls == [["/bin/echo"], ["/bin/echo"]]++@pytest.mark.parametrize(("runtime", "expected"),[@@ -1990,7 +2161,13 @@ def test_dependencies_status_node_unsupported_not_ready(monkeypatch):class _Mgr:def status(self):- return {"installed": False, "manifest": None, "node_available": True, "node_supported": False, "node_version": "16.0"}+ return {+ "install": {"state": "absent"},+ "manifest": None,+ "node_available": True,+ "node_supported": False,+ "node_version": "16.0",+ }monkeypatch.setattr(srt_mod, "get_show_runtime_manager", lambda: _Mgr())by = {d["id"]: d for d in api.dependencies_status()["deps"]}@@ -2907,22 +3084,16 @@ def test_prepare_show_runtime_job_surfaces_retry_diagnostics(monkeypatch):import core.show_runtime as show_runtimemanager = Mock()- manager.prepare.return_value = {+ manager.repair.return_value = {"ok": False,+ "outcome": "failed","reason": "runtime_archive_download_failed",- "install": {- "state": "failed",- "reason": "runtime_archive_download_failed",- "failure_class": "transient",- },- "status": {- "download_error": {- "kind": "timeout",- "message": "Connection timed out",- "url": "https://example.test/runtime.tgz",- "retryable": True,- "attempts": 3,- }+ "download_error": {+ "kind": "timeout",+ "message": "Connection timed out",+ "url": "https://example.test/runtime.tgz",+ "retryable": True,+ "attempts": 3,},}monkeypatch.setattr(show_runtime, "get_show_runtime_manager", lambda: manager)@@ -2939,17 +3110,12 @@ def test_prepare_show_runtime_job_reports_failed_replacement_with_old_install(moimport core.show_runtime as show_runtimemanager = Mock()- manager.prepare.return_value = {+ manager.repair.return_value = {"ok": False,+ "outcome": "failed","reason": "runtime_archive_download_failed",- "install": {- "state": "installed",- "reason": None,- },- "status": {- "installed": True,- "command": ["node", "runtime-cli.js"],- },+ "installed": True,+ "command": ["node", "runtime-cli.js"],}monkeypatch.setattr(show_runtime, "get_show_runtime_manager", lambda: manager)@@ -2960,6 +3126,24 @@ def test_prepare_show_runtime_job_reports_failed_replacement_with_old_install(moassert "runtime_archive_download_failed" in result["message"]+def test_prepare_show_runtime_job_reports_healthy_runtime_without_change(monkeypatch):+ import core.show_runtime as show_runtime++ manager = Mock()+ manager.repair.return_value = {"ok": True, "outcome": "healthy"}+ monkeypatch.setattr(show_runtime, "get_show_runtime_manager", lambda: manager)++ result = api._prepare_show_runtime_job()++ assert result == {+ "ok": True,+ "message": "Show Runtime starts successfully; no repair is needed.",+ "output": None,+ "outcome": "healthy",+ "changed": False,+ }++def test_start_dependency_install_job_runs_askill(monkeypatch):import time as _tdiff --git a/tests/test_managed_runtime.py b/tests/test_managed_runtime.pyindex eb85d1b69..db325af85 100644--- a/tests/test_managed_runtime.py+++ b/tests/test_managed_runtime.py@@ -223,6 +223,62 @@ def test_force_install_uses_sibling_target_by_default(assert Path(installed["install_dir"]).is_dir()+def test_force_candidate_is_validated_before_pointer_publication(tmp_path: Path) -> None:+ manifest_path = tmp_path / "manifest.json"+ _write_fixture_runtime_release(+ tmp_path,+ manifest_path,+ label="validated-force",+ version="1.0.0",+ )+ manager = _fixture_runtime_manager(tmp_path / "runtime", manifest_path=manifest_path)+ installed = manager.ensure()+ pointer_path = manager.runtime_dir / "current.json"+ pointer_before = pointer_path.read_bytes()+ observed_candidate: Path | None = None++ def validate_candidate(candidate: Path) -> str | None:+ nonlocal observed_candidate+ observed_candidate = candidate+ assert candidate.is_file()+ assert candidate != Path(installed["path"])+ assert pointer_path.read_bytes() == pointer_before+ return None++ refreshed = manager.ensure(force=True, validate_candidate=validate_candidate)++ assert refreshed["ok"] is True+ assert observed_candidate == Path(refreshed["path"])+ assert pointer_path.read_bytes() != pointer_before+ assert Path(installed["path"]).is_file()+++def test_force_candidate_rejection_preserves_published_install(tmp_path: Path) -> None:+ manifest_path = tmp_path / "manifest.json"+ _write_fixture_runtime_release(+ tmp_path,+ manifest_path,+ label="rejected-force",+ version="1.0.0",+ )+ manager = _fixture_runtime_manager(tmp_path / "runtime", manifest_path=manifest_path)+ installed = manager.ensure()+ pointer_path = manager.runtime_dir / "current.json"+ pointer_before = pointer_path.read_bytes()+ versions_before = set((manager.runtime_dir / "versions").glob("**/install.json"))++ rejected = manager.ensure(+ force=True,+ validate_candidate=lambda _candidate: "fixture_candidate_validation_failed",+ )++ assert rejected["ok"] is False+ assert rejected["reason"] == "fixture_candidate_validation_failed"+ assert pointer_path.read_bytes() == pointer_before+ assert Path(installed["path"]).read_text(encoding="utf-8") == "1.0.0"+ assert set((manager.runtime_dir / "versions").glob("**/install.json")) == versions_before++def test_force_target_replacement_failure_does_not_publish_success(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex df0fb27f8..96b7f351d 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -58,6 +58,7 @@ from core.show_runtime import (ShowRuntimeProtocolEnvelope,ShowRuntimeRequestTimeoutError,ShowRuntimeServingState,+ ShowRuntimeStartability,ShowRuntimeUnavailableError,ShowRuntimeWebSocketTarget,_runtime_download_error,@@ -9056,7 +9057,7 @@ def test_provider_install_entrypoints_converge_on_single_admission_owner():isinstance(node, ast.Attribute) and node.attr == "_attempt_managed_install" for node in ast.walk(function))}- assert admission_callers == {"_resolve_managed_availability", "prepare"}+ assert admission_callers == {"_resolve_managed_availability", "_prepare"}def test_explicit_command_resolution_has_one_owner_and_four_consumers():@@ -9095,7 +9096,7 @@ def test_explicit_command_resolution_has_one_owner_and_four_consumers():"_admit_runtime_start","_managed_install_preflight","_resolve_managed_availability",- "status",+ "_status",}@@ -9774,10 +9775,12 @@ def test_show_runtime_manager_installs_from_prebuilt_archive(monkeypatch, tmp_pa)monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)- assert manager._install_managed_runtime_locked(force=False, offline=False).command == [- "/bin/node",- str(tmp_path / "runtime" / "prebuilt" / "current" / "node_modules" / "@avibe" / "show-runtime" / "dist" / "cli.js"),- ]+ command = manager._install_managed_runtime_locked(force=False, offline=False).command++ assert command is not None+ assert command[0] == "/bin/node"+ assert Path(command[1]).parent.parent.parent.parent.parent.parent == tmp_path / "runtime" / "prebuilt" / "versions"+ assert json.loads((tmp_path / "runtime" / "prebuilt" / "current.json").read_text())["install_dir"] in command[1]assert manager._install_reason is None@@ -9809,10 +9812,8 @@ def test_show_runtime_manager_installs_prebuilt_archive_with_internal_symlinks(mcommand = manager._install_managed_runtime_locked(force=False, offline=False).commandassert command is not None- assert command == [- "/bin/node",- str(tmp_path / "runtime" / "prebuilt" / "current" / "node_modules" / "@avibe" / "show-runtime" / "dist" / "cli.js"),- ]+ assert command[0] == "/bin/node"+ assert "/prebuilt/versions/" in command[1]assert Path(command[1]).resolve().read_text(encoding="utf-8") == "#!/usr/bin/env node\n"assert manager._install_reason is None@@ -9976,8 +9977,12 @@ def test_show_runtime_manager_refreshes_stale_prebuilt_archive(monkeypatch, tmp_)monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)- assert asyncio.run(manager._resolve_managed_command()) == ["/bin/node", str(installed_cli)]- assert installed_cli.read_text(encoding="utf-8") == "new runtime\n"+ command = asyncio.run(manager._resolve_managed_command())++ assert command is not None+ assert command != ["/bin/node", str(installed_cli)]+ assert Path(command[1]).read_text(encoding="utf-8") == "new runtime\n"+ assert installed_cli.read_text(encoding="utf-8") == "old runtime\n"def test_show_runtime_manager_force_refreshes_matching_prebuilt_archive(monkeypatch, tmp_path):@@ -10005,7 +10010,9 @@ def test_show_runtime_manager_force_refreshes_matching_prebuilt_archive(monkeyparepaired = manager.prepare(force=True)assert repaired["ok"] is True- assert installed_cli.read_text(encoding="utf-8") == "healthy runtime\n"+ assert repaired["command"] != first["command"]+ assert Path(repaired["command"][1]).read_text(encoding="utf-8") == "healthy runtime\n"+ assert installed_cli.read_text(encoding="utf-8") == "corrupt runtime\n"def test_show_runtime_manager_installs_from_manifest_cache(monkeypatch, tmp_path):@@ -10096,18 +10103,251 @@ def test_show_runtime_manager_force_refreshes_matching_manifest_install(monkeypareplaced = manager.prepare(force=True)assert replaced["ok"] is True- assert installed_cli.read_text(encoding="utf-8") == "healthy runtime\n"+ assert replaced["command"] != installed["command"]+ assert Path(replaced["command"][1]).read_text(encoding="utf-8") == "healthy runtime\n"+ assert installed_cli.read_text(encoding="utf-8") == "corrupt runtime\n"+++def test_show_runtime_repair_skips_healthy_install_without_replacement(monkeypatch, tmp_path):+ archive_path = _write_runtime_archive(tmp_path)+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ manifest_path=manifest_path,+ )+ monkeypatch.setattr(+ "core.show_runtime._resolve_command",+ lambda command: ["/bin/node"] if command == "node" else None,+ )+ installed = manager.prepare()+ versions_before = set((tmp_path / "runtime" / "versions").glob("**/.vibe-show-runtime.json"))+ monkeypatch.setattr(manager, "_verify_startability", lambda _command: ShowRuntimeStartability.startable())++ result = manager.repair()++ assert result["outcome"] == "healthy"+ assert result["repair_attempted"] is False+ assert result["command"] == installed["command"]+ assert set((tmp_path / "runtime" / "versions").glob("**/.vibe-show-runtime.json")) == versions_before+++def test_show_runtime_repair_does_not_mutate_when_verification_is_undetermined(monkeypatch, tmp_path):+ archive_path = _write_runtime_archive(tmp_path)+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ manifest_path=manifest_path,+ )+ monkeypatch.setattr(+ "core.show_runtime._resolve_command",+ lambda command: ["/bin/node"] if command == "node" else None,+ )+ installed = manager.prepare()+ pointer_before = (tmp_path / "runtime" / "current.json").read_bytes()+ monkeypatch.setattr(+ manager,+ "_verify_startability",+ lambda _command: ShowRuntimeStartability.undetermined("verification workspace denied"),+ )++ result = manager.repair()++ assert result["ok"] is False+ assert result["reason"] == "runtime_start_verification_failed"+ assert result["repair_attempted"] is False+ assert result["command"] == installed["command"]+ assert (tmp_path / "runtime" / "current.json").read_bytes() == pointer_before+++def test_show_runtime_repair_publishes_only_a_startable_immutable_candidate(monkeypatch, tmp_path):+ archive_path = _write_runtime_archive(tmp_path, text="healthy bytes\n")+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ manifest_path=manifest_path,+ )+ monkeypatch.setattr(+ "core.show_runtime._resolve_command",+ lambda command: ["/bin/node"] if command == "node" else None,+ )+ installed = manager.prepare()+ old_cli = Path(installed["command"][1])+ old_cli.write_text("broken bytes\n", encoding="utf-8")+ outcomes = iter(+ [+ ShowRuntimeStartability.not_startable("runtime_start_health_timeout"),+ ShowRuntimeStartability.startable(),+ ]+ )+ monkeypatch.setattr(manager, "_verify_startability", lambda _command: next(outcomes))++ result = manager.repair()++ assert result["outcome"] == "repaired"+ assert result["repair_attempted"] is True+ assert result["command"] != installed["command"]+ assert Path(result["command"][1]).read_text(encoding="utf-8") == "healthy bytes\n"+ assert old_cli.read_text(encoding="utf-8") == "broken bytes\n"-def test_show_runtime_manager_force_publication_failure_invalidates_cached_command_and_repairs(+def test_show_runtime_repair_rejects_unverified_candidate_and_preserves_old_install(+ monkeypatch,+ tmp_path,+):+ archive_path = _write_runtime_archive(tmp_path)+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)+ runtime_dir = tmp_path / "runtime"+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=runtime_dir,+ manifest_path=manifest_path,+ )+ monkeypatch.setattr(+ "core.show_runtime._resolve_command",+ lambda command: ["/bin/node"] if command == "node" else None,+ )+ installed = manager.prepare()+ old_cli = Path(installed["command"][1])+ pointer_before = (runtime_dir / "current.json").read_bytes()+ outcomes = iter(+ [+ ShowRuntimeStartability.not_startable("runtime_start_health_timeout"),+ ShowRuntimeStartability.undetermined("candidate probe crashed"),+ ]+ )+ monkeypatch.setattr(manager, "_verify_startability", lambda _command: next(outcomes))++ result = manager.repair()++ assert result["ok"] is False+ assert result["reason"] == "runtime_start_verification_failed"+ assert result["verification_phase"] == "after"+ assert result["command"] == installed["command"]+ assert old_cli.exists()+ assert (runtime_dir / "current.json").read_bytes() == pointer_before+ assert len(list((runtime_dir / "versions").glob("**/.vibe-show-runtime.json"))) == 1++[email protected]("provider", ("manifest-cache", "archive", "npm"))+def test_show_runtime_candidate_reference_failure_never_publishes_pointer(+ monkeypatch,+ tmp_path,+ provider,+):+ runtime_dir = tmp_path / "runtime"+ archive_path = _write_runtime_archive(tmp_path)+ manager_kwargs = {+ "workspace_root": tmp_path / "show",+ "runtime_dir": runtime_dir,+ "runtime_source": provider,+ }+ if provider == "manifest-cache":+ manager_kwargs["manifest_path"] = _write_runtime_manifest(tmp_path, archive_path)+ pointer = runtime_dir / "current.json"+ elif provider == "archive":+ manager_kwargs["archive_path"] = archive_path+ pointer = runtime_dir / "prebuilt" / "current.json"+ else:+ pointer = runtime_dir / "package" / "current.json"++ def install_npm(argv, **_kwargs):+ prefix = Path(argv[argv.index("--prefix") + 1])+ binary = ShowRuntimeManager._npm_bin_path(prefix)+ binary.parent.mkdir(parents=True)+ binary.write_text("#!/bin/sh\n", encoding="utf-8")+ binary.chmod(0o755)+ return SimpleNamespace(returncode=0)++ monkeypatch.setattr("core.show_runtime.subprocess.run", install_npm)++ monkeypatch.setattr(+ "core.show_runtime._resolve_command",+ lambda command: [command] if command in {"node", "npm"} else None,+ )+ manager = ShowRuntimeManager(**manager_kwargs)+ monkeypatch.setattr(manager, "_retain_install_dir_locked", lambda _install_dir: False)+ monkeypatch.setattr(manager, "_retain_managed_command", lambda _command: False)++ result = manager.prepare()++ assert result["ok"] is False+ assert result["reason"] == "runtime_install_guard_unavailable"+ assert pointer.exists() is False+ assert list(runtime_dir.rglob(".vibe-show-runtime.json")) == []+++def test_show_runtime_live_cached_install_survives_distinct_identity_cleanup(monkeypatch, tmp_path):+ runtime_dir = tmp_path / "runtime"+ monkeypatch.setattr(+ "core.show_runtime._resolve_command",+ lambda command: [sys.executable] if command == "node" else None,+ )++ def install(version: str, text: str) -> tuple[ShowRuntimeManager, Path]:+ source_dir = tmp_path / version+ archive = _write_runtime_archive(source_dir, text=text)+ manifest = _write_runtime_manifest(+ source_dir,+ archive,+ runtime_version=version,+ )+ runtime_manager = ShowRuntimeManager(+ workspace_root=tmp_path / f"show-{version}",+ runtime_dir=runtime_dir,+ manifest_path=manifest,+ )+ prepared = runtime_manager.prepare()+ assert prepared["ok"] is True+ return runtime_manager, Path(prepared["command"][1])++ live_manager, live_cli = install("runtime-v1", "runtime-v1\n")+ gate = tmp_path / "read-now"+ reader = subprocess.Popen(+ [+ sys.executable,+ "-c",+ "import pathlib,sys,time\n"+ "gate=pathlib.Path(sys.argv[1])\n"+ "while not gate.exists():\n"+ " time.sleep(.01)\n"+ "print(pathlib.Path(sys.argv[2]).read_text(), end='')\n",+ str(gate),+ str(live_cli),+ ],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ )+ second_manager, second_cli = install("runtime-v2", "runtime-v2\n")+ second_manager._install_reference_finalizer()+ third_manager, _third_cli = install("runtime-v3", "runtime-v3\n")+ third_manager._install_reference_finalizer()+ fourth_manager, _fourth_cli = install("runtime-v4", "runtime-v4\n")++ gate.write_text("go\n", encoding="utf-8")+ stdout, stderr = reader.communicate(timeout=5)++ assert reader.returncode == 0, stderr+ assert stdout == "runtime-v1\n"+ assert live_cli.exists()+ assert not second_cli.exists()+ live_manager._install_reference_finalizer()+ fourth_manager._install_reference_finalizer()+++def test_show_runtime_manager_force_publication_failure_preserves_cached_command(monkeypatch,tmp_path,):archive_path = _write_runtime_archive(tmp_path, text="healthy runtime\n")manifest_path = _write_runtime_manifest(tmp_path, archive_path)+ runtime_dir = tmp_path / "runtime"manager = ShowRuntimeManager(workspace_root=tmp_path / "show",- runtime_dir=tmp_path / "runtime",+ runtime_dir=runtime_dir,manifest_path=manifest_path,)monkeypatch.setattr(@@ -10136,9 +10376,10 @@ def test_show_runtime_manager_force_publication_failure_invalidates_cached_commaassert failed["ok"] is Falseassert failed["reason"] == "runtime_install_failed"- assert failed["command"] is None- assert manager._managed_command is None- assert not installed_cli.exists()+ assert failed["command"] == installed["command"]+ assert manager._managed_command == installed["command"]+ assert installed_cli.exists()+ assert len(list((runtime_dir / "references").glob("*/*.lock"))) == 1repaired = manager.prepare()@@ -10733,6 +10974,7 @@ def test_show_runtime_clean_prunes_stale_manifest_fingerprints(monkeypatch, tmp_new_result = new_manager.prepare()new_install_dir = Path(new_result["command"][1]).parents[4]+ old_manager._install_reference_finalizer()result = new_manager.clean(keep_previous=0)assert result["ok"] is True@@ -11958,7 +12200,10 @@ def test_show_runtime_destructive_replacement_invalidates_cached_install_before_assert manager._remove_managed_runtime_tree_for_replacement(managed_tree, label="test") is True-def test_show_runtime_manager_forced_npm_replacement_fails_when_old_tree_remains(monkeypatch, tmp_path):+def test_show_runtime_manager_forced_npm_replacement_preserves_old_tree_on_failed_install(+ monkeypatch,+ tmp_path,+):runtime_dir = tmp_path / "runtime"managed_bin = runtime_dir / "package" / "node_modules" / ".bin" / "avibe-show-runtime"managed_bin.parent.mkdir(parents=True)@@ -11975,10 +12220,9 @@ def test_show_runtime_manager_forced_npm_replacement_fails_when_old_tree_remains"core.show_runtime._resolve_command",lambda command: ["/bin/npm"] if command == "npm" else None,)- monkeypatch.setattr("core.show_runtime.shutil.rmtree", lambda _path: None)monkeypatch.setattr("core.show_runtime.subprocess.run",- lambda *_args, **_kwargs: install_calls.append(True) or SimpleNamespace(returncode=0),+ lambda *_args, **_kwargs: install_calls.append(True) or SimpleNamespace(returncode=1),)result = manager.prepare(force=True)@@ -11987,10 +12231,10 @@ def test_show_runtime_manager_forced_npm_replacement_fails_when_old_tree_remainsassert result["reason"] == "runtime_install_failed"assert result["status"]["install"]["state"] == "installed"assert managed_bin.read_text(encoding="utf-8") == "old runtime\n"- assert install_calls == []+ assert install_calls == [True]-def test_show_runtime_manager_forced_npm_replacement_removes_old_tree_before_install(monkeypatch, tmp_path):+def test_show_runtime_manager_forced_npm_replacement_publishes_immutable_tree(monkeypatch, tmp_path):runtime_dir = tmp_path / "runtime"managed_bin = runtime_dir / "package" / "node_modules" / ".bin" / "avibe-show-runtime"managed_bin.parent.mkdir(parents=True)@@ -12007,19 +12251,23 @@ def test_show_runtime_manager_forced_npm_replacement_removes_old_tree_before_inslambda command: ["/bin/npm"] if command == "npm" else None,)- def install_after_removal(*_args, **_kwargs):- assert not managed_bin.parent.parent.exists()- managed_bin.parent.mkdir(parents=True)- managed_bin.write_text("new runtime\n", encoding="utf-8")- managed_bin.chmod(0o755)+ def install_without_removing_old(command, **_kwargs):+ assert managed_bin.read_text(encoding="utf-8") == "old runtime\n"+ prefix = Path(command[command.index("--prefix") + 1])+ installed_bin = manager._npm_bin_path(prefix)+ installed_bin.parent.mkdir(parents=True)+ installed_bin.write_text("new runtime\n", encoding="utf-8")+ installed_bin.chmod(0o755)return SimpleNamespace(returncode=0)- monkeypatch.setattr("core.show_runtime.subprocess.run", install_after_removal)+ monkeypatch.setattr("core.show_runtime.subprocess.run", install_without_removing_old)result = manager.prepare(force=True)assert result["ok"] is True- assert managed_bin.read_text(encoding="utf-8") == "new runtime\n"+ assert result["command"] != [str(managed_bin)]+ assert Path(result["command"][0]).read_text(encoding="utf-8") == "new runtime\n"+ assert managed_bin.read_text(encoding="utf-8") == "old runtime\n"@pytest.mark.parametrize(@@ -12054,7 +12302,7 @@ def test_show_runtime_manager_forced_npm_replacement_reports_delegate_exception(def fail_install(*_args, **_kwargs):install_calls.append(True)- assert not managed_bin.parent.parent.exists()+ assert managed_bin.read_text(encoding="utf-8") == "old runtime\n"raise install_errormonkeypatch.setattr("core.show_runtime.subprocess.run", fail_install)@@ -12064,13 +12312,12 @@ def test_show_runtime_manager_forced_npm_replacement_reports_delegate_exception(assert result["ok"] is Falseassert result["reason"] == "runtime_install_failed"- assert result["install"]["state"] == "failed"- assert result["status"]["install"]["state"] == "absent"- assert retried["ok"] is False- assert retried["reason"] == "runtime_install_failed"- assert manager._managed_command is None- assert install_calls == [True, True]- assert managed_bin.exists() is False+ assert result["install"]["state"] == "installed"+ assert result["status"]["install"]["state"] == "installed"+ assert retried["ok"] is True+ assert manager._managed_command == [str(managed_bin)]+ assert install_calls == [True]+ assert managed_bin.read_text(encoding="utf-8") == "old runtime\n"def test_show_runtime_shutdown_stops_manager():diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex cf58142a1..43119d3f7 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -2445,418 +2445,126 @@ def test_show_runtime_doctor_identifies_legacy_upstream_fallback(monkeypatch):assert "repair" not in next(item for item in items if item.get("code") == "show_runtime.not_ready")-def test_repair_show_runtime_returns_structured_download_failure(monkeypatch):- archive_url = "https://github.com/avibe-bot/avibe/releases/download/v-test/runtime.tgz"- manager = SimpleNamespace(- status=lambda: {- "provider": "manifest-cache",- "platform": "linux-x64",- "archive": {"url": archive_url},- "install": {"state": "absent", "install_dir": None},- },- prepare=lambda force=False: {- "ok": False,- "provider": "manifest-cache",- "platform": "linux-x64",- "reason": "runtime_archive_download_failed",- "status": {- "download_error": {- "kind": "timeout",- "message": "Connection timed out",- "url": archive_url,- }- },- },- )- monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda **_kwargs: manager)-- result = cli._repair_show_runtime()-- assert result["status"] == "failed"- assert result["reason"] == "runtime_archive_download_failed"- assert result["download_error"]["kind"] == "timeout"- assert archive_url in result["message"]---def test_repair_show_runtime_prepares_missing_runtime(monkeypatch, tmp_path):- prepared = []- stopped = []-- async def ensure():- return SimpleNamespace(available=True, reason=None)-- def prepare(force=False):- prepared.append(force)- return {- "ok": True,- "provider": "manifest-cache",- "platform": "linux-x64",- "command": [str(tmp_path / "runtime-cli")],- "status": {"install": {"state": "installed", "install_dir": str(tmp_path / "runtime")}},- }-- manager = SimpleNamespace(- status=lambda: {- "provider": "manifest-cache",- "platform": "linux-x64",- "archive": {"url": "https://github.com/avibe-bot/avibe/releases/download/v-test/runtime.tgz"},- "install": {"state": "absent", "install_dir": None},- },- prepare=prepare,- ensure=ensure,- stop=lambda: stopped.append(True),- )- monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda **_kwargs: manager)-- result = cli._repair_show_runtime()-- assert result["status"] == "repaired"- assert result["install_dir"] == str(tmp_path / "runtime")- assert result["message"] == "Installed and started Show Runtime."- assert prepared == [False]- assert stopped == [True]---def test_repair_show_runtime_does_not_reinstall_startable_runtime(monkeypatch, tmp_path):- constructor_calls = []- verifier_stops = []-- manager = SimpleNamespace(- status=lambda: {- "provider": "manifest-cache",- "platform": "linux-x64",- "install": {"state": "installed", "install_dir": str(tmp_path / "installed")},- "archive": {"url": "https://github.com/avibe-bot/avibe/releases/download/v-test/runtime.tgz"},- "command": [str(tmp_path / "node"), str(tmp_path / "runtime-cli.js")],- },- prepare=lambda force=False: pytest.fail("startable runtime must not be reinstalled"),- )- verifier = SimpleNamespace(- ensure=lambda: asyncio.sleep(0, result=SimpleNamespace(available=True, reason=None)),- stop=lambda: verifier_stops.append(True),- )-- def manager_factory(**kwargs):- constructor_calls.append(kwargs)- return verifier if kwargs else manager-- monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", manager_factory)-- result = cli._repair_show_runtime()-- assert result["status"] == "skipped"- assert result["install_dir"] == str(tmp_path / "installed")- assert "no repair is needed" in result["message"]- assert verifier_stops == [True]- assert len(constructor_calls) == 2- verification_call = constructor_calls[1]- assert verification_call["auto_install"] is False- assert verification_call["workspace_root"].name == "show"- assert verification_call["runtime_dir"].name == "runtime"- assert verification_call["workspace_root"].parent == verification_call["runtime_dir"].parent--@pytest.mark.parametrize(- ("language", "message_fragment"),- [("en", "Fix or remove the override"), ("zh", "\u4fee\u590d\u6216\u79fb\u9664\u8be5\u8986\u76d6")],+ ("owner_result", "expected_status", "message_fragment"),+ [+ (+ {+ "ok": True,+ "outcome": "healthy",+ "provider": "manifest-cache",+ "platform": "linux-x64",+ "install_dir": "/runtime/old",+ },+ "skipped",+ "no repair is needed",+ ),+ (+ {+ "ok": True,+ "outcome": "repaired",+ "was_installed": True,+ "provider": "manifest-cache",+ "platform": "linux-x64",+ "install_dir": "/runtime/new",+ },+ "repaired",+ "Reinstalled and started",+ ),+ (+ {+ "ok": False,+ "outcome": "failed",+ "reason": "runtime_start_verification_failed",+ "verification": {"state": "undetermined", "detail": "probe failed"},+ "verification_phase": "before",+ "installed": True,+ },+ "failed",+ "no reinstall was attempted",+ ),+ (+ {+ "ok": False,+ "outcome": "failed",+ "reason": "runtime_start_health_timeout",+ "verification": {+ "state": "not_startable",+ "reason": "runtime_start_health_timeout",+ },+ "verification_phase": "after",+ "was_installed": True,+ "installed": True,+ },+ "failed",+ "reinstalled but could not start",+ ),+ ],)-def test_repair_show_runtime_refuses_explicit_command_before_hypothetical_recovery(- monkeypatch, tmp_path, language, message_fragment+def test_repair_show_runtime_renders_manager_owned_outcomes(+ monkeypatch,+ owner_result,+ expected_status,+ message_fragment,):- prepared = []- verification_calls = []- verification_results = [- SimpleNamespace(available=False, reason="runtime_start_health_timeout"),- SimpleNamespace(available=True, reason=None),- ]- explicit_command = str(tmp_path / "explicit-runtime")- manager = SimpleNamespace(- status=lambda: {- "provider": "command",- "platform": "linux-x64",- "install": {"state": "installed", "install_dir": None},- "command": [explicit_command],- "explicit_command": explicit_command,- },- prepare=lambda force=False: prepared.append(force),- )-- def manager_factory(**kwargs):- if not kwargs:- return manager-- async def ensure():- index = len(verification_calls)- verification_calls.append(index)- return verification_results[index]-- return SimpleNamespace(ensure=ensure, stop=lambda: None)-- monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", manager_factory)- monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)+ manager = SimpleNamespace(repair=lambda: owner_result)+ monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda: manager)result = cli._repair_show_runtime()- assert result["status"] == "failed"- assert result["reason"] == "runtime_start_health_timeout"- assert result["explicit_command"] == explicit_command- assert "VIBE_SHOW_RUNTIME_BIN" in result["message"]+ assert result["status"] == expected_statusassert message_fragment in result["message"]- assert prepared == []- assert verification_calls == [0]--def test_repair_show_runtime_reinstalls_unstartable_runtime_and_verifies_recovery(monkeypatch, tmp_path):- prepared = []- verifier_results = iter(- [- SimpleNamespace(available=False, reason="runtime_start_health_timeout"),- SimpleNamespace(available=True, reason=None),- ]- )- def prepare(force=False):- prepared.append(force)- return {- "ok": True,- "provider": "manifest-cache",- "platform": "linux-x64",- "command": [str(tmp_path / "node"), str(tmp_path / "runtime-cli.js")],- "status": {"install": {"state": "installed", "install_dir": str(tmp_path / "installed")}},- }-- manager = SimpleNamespace(- status=lambda: {- "provider": "manifest-cache",- "platform": "linux-x64",- "install": {"state": "installed", "install_dir": str(tmp_path / "installed")},- "archive": {"url": "https://github.com/avibe-bot/avibe/releases/download/v-test/runtime.tgz"},- "command": [str(tmp_path / "node"), str(tmp_path / "runtime-cli.js")],- },- prepare=prepare,- )-- def manager_factory(**kwargs):- if not kwargs:- return manager- return SimpleNamespace(- ensure=lambda: asyncio.sleep(0, result=next(verifier_results)),- stop=lambda: None,- )-- monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", manager_factory)-- result = cli._repair_show_runtime()-- assert result["status"] == "repaired"- assert result["message"] == "Reinstalled and started Show Runtime."- assert prepared == [True]---def test_repair_show_runtime_reports_runtime_that_still_cannot_start(monkeypatch, tmp_path):- prepared = []- verifier_stops = []-- def prepare(force=False):- prepared.append(force)- return {- "ok": True,- "provider": "manifest-cache",- "platform": "linux-x64",- "command": [str(tmp_path / "node"), str(tmp_path / "runtime-cli.js")],- "status": {"install": {"state": "installed", "install_dir": str(tmp_path / "installed")}},- }-- manager = SimpleNamespace(- status=lambda: {- "provider": "manifest-cache",- "platform": "linux-x64",- "install": {"state": "installed", "install_dir": str(tmp_path / "installed")},- "archive": {"url": "https://github.com/avibe-bot/avibe/releases/download/v-test/runtime.tgz"},- "command": [str(tmp_path / "node"), str(tmp_path / "runtime-cli.js")],- },- prepare=prepare,- )-- def manager_factory(**kwargs):- if not kwargs:- return manager- return SimpleNamespace(- ensure=lambda: asyncio.sleep(- 0,- result=SimpleNamespace(available=False, reason="runtime_start_health_timeout"),- ),- stop=lambda: verifier_stops.append(True),- )-- monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", manager_factory)-- result = cli._repair_show_runtime()-- assert result["status"] == "failed"- assert result["reason"] == "runtime_start_health_timeout"- assert result["message"] == "Show Runtime was reinstalled but could not start: runtime_start_health_timeout"- assert prepared == [True]- assert verifier_stops == [True, True]---def test_repair_show_runtime_reports_first_install_that_cannot_start(monkeypatch, tmp_path):+def test_repair_show_runtime_returns_structured_download_failure(monkeypatch):+ archive_url = "https://github.com/avibe-bot/avibe/releases/download/v-test/runtime.tgz"manager = SimpleNamespace(- status=lambda: {- "provider": "manifest-cache",- "platform": "linux-x64",- "archive": {"url": str(tmp_path / "runtime.tgz")},- "install": {"state": "absent", "install_dir": None},- },- prepare=lambda force=False: {- "ok": True,- "provider": "manifest-cache",- "platform": "linux-x64",- "command": [str(tmp_path / "node"), str(tmp_path / "runtime-cli.js")],- "status": {"install": {"state": "installed", "install_dir": str(tmp_path / "installed")}},- },- )-- def manager_factory(**kwargs):- if not kwargs:- return manager- return SimpleNamespace(- ensure=lambda: asyncio.sleep(- 0,- result=SimpleNamespace(available=False, reason="runtime_start_health_timeout"),- ),- stop=lambda: None,- )-- monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", manager_factory)-- result = cli._repair_show_runtime()-- assert result["status"] == "failed"- assert result["reason"] == "runtime_start_health_timeout"- assert result["message"] == "Show Runtime was installed but could not start: runtime_start_health_timeout"---def test_repair_show_runtime_preserves_undetermined_post_repair_verification(monkeypatch, tmp_path):- prepared = []- verification_index = 0- verifier_results = iter(- [- SimpleNamespace(available=False, reason="runtime_start_health_timeout"),- SimpleNamespace(available=True, reason=None),- ]- )-- class VerificationDirectory:- def __init__(self, *args, **kwargs):- nonlocal verification_index- del args, kwargs- verification_index += 1- self.index = verification_index-- def __enter__(self):- root = tmp_path / f"verification-{self.index}"- root.mkdir()- return str(root)-- def __exit__(self, exc_type, exc, traceback):- del exc_type, exc, traceback- if self.index == 2:- raise OSError("post-repair verification cleanup failed")- return False-- def prepare(force=False):- prepared.append(force)- return {- "ok": True,+ repair=lambda: {+ "ok": False,+ "outcome": "failed",+ "reason": "runtime_archive_download_failed","provider": "manifest-cache","platform": "linux-x64",- "command": [str(tmp_path / "node"), str(tmp_path / "runtime-cli.js")],- "status": {"install": {"state": "installed", "install_dir": str(tmp_path / "installed")}},+ "download_error": {+ "kind": "timeout",+ "message": "Connection timed out",+ "url": archive_url,+ },}-- manager = SimpleNamespace(- status=lambda: {- "provider": "manifest-cache",- "platform": "linux-x64",- "install": {"state": "installed", "install_dir": str(tmp_path / "installed")},- "archive": {"url": str(tmp_path / "runtime.tgz")},- "command": [str(tmp_path / "node"), str(tmp_path / "runtime-cli.js")],- },- prepare=prepare,)-- def manager_factory(**kwargs):- if not kwargs:- return manager- return SimpleNamespace(- ensure=lambda: asyncio.sleep(0, result=next(verifier_results)),- stop=lambda: None,- )-- monkeypatch.setattr(cli.tempfile, "TemporaryDirectory", VerificationDirectory)- monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", manager_factory)+ monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda: manager)result = cli._repair_show_runtime()assert result["status"] == "failed"- assert result["reason"] == "runtime_start_verification_failed"- assert result["start_error"] == "post-repair verification cleanup failed"- assert "preparation completed" in result["message"]- assert prepared == [True]+ assert result["reason"] == "runtime_archive_download_failed"+ assert result["download_error"]["kind"] == "timeout"+ assert archive_url in result["message"]-def test_repair_show_runtime_reports_failed_replacement_while_old_runtime_remains_installed([email protected](("language", "message_fragment"), [("en", "Fix or remove"), ("zh", "\u4fee\u590d\u6216\u79fb\u9664")])+def test_repair_show_runtime_renders_explicit_command_failure(monkeypatch,- tmp_path,+ language,+ message_fragment,):- prepared = []-- def prepare(force=False):- prepared.append(force)- return {+ manager = SimpleNamespace(+ repair=lambda: {"ok": False,- "reason": "runtime_archive_download_failed",- "provider": "archive",- "platform": "linux-x64",- "command": None,- "status": {- "install": {"state": "installed", "install_dir": str(tmp_path / "installed")},- "command": [str(tmp_path / "node"), str(tmp_path / "runtime-cli.js")],- },+ "outcome": "failed",+ "reason": "runtime_start_health_timeout",+ "explicit_command": "/custom/runtime",+ "installed": True,}-- manager = SimpleNamespace(- status=lambda: {- "provider": "archive",- "platform": "linux-x64",- "install": {"state": "installed", "install_dir": str(tmp_path / "installed")},- "archive": {"url": str(tmp_path / "runtime.tgz")},- "command": [str(tmp_path / "node"), str(tmp_path / "runtime-cli.js")],- },- prepare=prepare,)-- def manager_factory(**kwargs):- if not kwargs:- return manager- return SimpleNamespace(- ensure=lambda: asyncio.sleep(- 0,- result=SimpleNamespace(available=False, reason="runtime_start_health_timeout"),- ),- stop=lambda: None,- )-- monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", manager_factory)+ monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda: manager)+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)result = cli._repair_show_runtime()assert result["status"] == "failed"- assert result["reason"] == "runtime_archive_download_failed"- assert result["installed"] is True- assert result["install_dir"] == str(tmp_path / "installed")- assert prepared == [True]+ assert result["explicit_command"] == "/custom/runtime"+ assert message_fragment in result["message"]def test_runtime_prepare_strict_does_not_report_policy_skip_as_ready(monkeypatch, capsys):@@ -3450,68 +3158,6 @@ def test_runtime_manager_migrates_legacy_source_to_packaged_manifest(][email protected]("failure_phase", ["temporary_directory", "verifier", "cleanup"])-def test_repair_show_runtime_reports_verification_workspace_failures(monkeypatch, tmp_path, failure_phase):- prepared = []-- class VerificationDirectory:- def __init__(self, *args, **kwargs):- if failure_phase == "temporary_directory":- raise OSError("verification workspace failed")-- def __enter__(self):- root = tmp_path / "verification"- root.mkdir(exist_ok=True)- return str(root)-- def __exit__(self, exc_type, exc, traceback):- if failure_phase == "cleanup":- raise OSError("verification workspace failed")- return False-- def prepare(force=False):- prepared.append(force)- return {- "ok": True,- "provider": "archive",- "platform": "linux-x64",- "command": [str(tmp_path / "node"), str(tmp_path / "runtime-cli.js")],- "status": {"install": {"state": "installed", "install_dir": str(tmp_path / "installed")}},- }-- manager = SimpleNamespace(- status=lambda: {- "provider": "archive",- "platform": "linux-x64",- "install": {"state": "installed", "install_dir": str(tmp_path / "installed")},- "archive": {"url": str(tmp_path / "runtime.tgz")},- "command": [str(tmp_path / "node"), str(tmp_path / "runtime-cli.js")],- },- prepare=prepare,- )-- def manager_factory(**kwargs):- if not kwargs:- return manager- if failure_phase == "verifier":- raise OSError("verification workspace failed")- return SimpleNamespace(- ensure=lambda: asyncio.sleep(0, result=SimpleNamespace(available=True, reason=None)),- stop=lambda: None,- )-- monkeypatch.setattr(cli.tempfile, "TemporaryDirectory", VerificationDirectory)- monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", manager_factory)-- result = cli._repair_show_runtime()-- assert result["status"] == "failed"- assert result["reason"] == "runtime_start_verification_failed"- assert result["start_error"] == "verification workspace failed"- assert "no reinstall was attempted" in result["message"]- assert prepared == []--def test_doctor_repair_refreshes_diagnostics_after_repair(monkeypatch):paths.ensure_data_dirs()restart_path = runtime.get_restart_status_path()diff --git a/ui/src/components/settings/SettingsDependenciesPage.test.ts b/ui/src/components/settings/SettingsDependenciesPage.test.tsindex f3b7df88c..74e68d7be 100644--- a/ui/src/components/settings/SettingsDependenciesPage.test.ts+++ b/ui/src/components/settings/SettingsDependenciesPage.test.ts@@ -8,6 +8,7 @@ describe('dependencyHasInstallAction', () => {expect(dependencyHasInstallAction({ id: 'memory-runtime', status: 'not_required' })).toBe(false);expect(dependencyHasInstallAction({ id: 'memory-runtime', status: 'error', action_class: 'operator_only' })).toBe(false);expect(dependencyHasInstallAction({ id: 'memory-runtime', status: 'missing', action_class: 'none' })).toBe(false);+ expect(dependencyHasInstallAction({ id: 'show-runtime', status: 'error', action_class: 'operator_only' })).toBe(false);});it('keeps supported dependency actions unchanged', () => {@@ -19,6 +20,7 @@ describe('dependencyHasInstallAction', () => {expect(dependencyHasInstallAction({ id: 'memory-runtime', status: 'missing' })).toBe(true);expect(dependencyHasInstallAction({ id: 'memory-runtime', status: 'ready', action_class: 'repairable' })).toBe(true);expect(dependencyHasInstallAction({ id: 'show-runtime', status: 'ready' })).toBe(true);+ expect(dependencyHasInstallAction({ id: 'show-runtime', status: 'missing', action_class: 'repairable' })).toBe(true);expect(dependencyHasInstallAction({ id: 'node', status: 'missing' })).toBe(false);});});diff --git a/ui/src/components/settings/SettingsDependenciesPage.test.tsx b/ui/src/components/settings/SettingsDependenciesPage.test.tsxindex 88086e22b..e103e729c 100644--- a/ui/src/components/settings/SettingsDependenciesPage.test.tsx+++ b/ui/src/components/settings/SettingsDependenciesPage.test.tsx@@ -66,6 +66,48 @@ afterEach(() => {vi.clearAllMocks();});+describe('SettingsDependenciesPage Show Runtime status', () => {+ it('renders inspection failure without authorizing install or repair', async () => {+ api.listDependencies.mockResolvedValue({+ ok: true,+ deps: [dependency({+ id: 'show-runtime',+ installed: null,+ status: 'error',+ action_class: 'operator_only',+ version: null,+ reason: 'runtime_install_inspection_failed',+ })],+ });++ renderPage();++ expect(await screen.findByText('settings.dependencies.statusError')).toBeTruthy();+ expect(screen.getByRole('alert').textContent).toBe('errors.runtime_install_inspection_failed');+ expect(screen.queryByRole('button', { name: 'settings.dependencies.install' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'settings.dependencies.repair' })).toBeNull();+ expect(api.installDependency).not.toHaveBeenCalled();+ });++ it('keeps a proven absence installable', async () => {+ api.listDependencies.mockResolvedValue({+ ok: true,+ deps: [dependency({+ id: 'show-runtime',+ installed: false,+ status: 'missing',+ action_class: 'repairable',+ version: null,+ })],+ });++ renderPage();+ await userEvent.click(await screen.findByRole('button', { name: 'settings.dependencies.install' }));++ await waitFor(() => expect(api.installDependency).toHaveBeenCalledWith('show-runtime'));+ });+});+describe('SettingsDependenciesPage Memory runtime', () => {it('routes repairable Python package bootstrap through its own dependency action', async () => {api.listDependencies.mockResolvedValue({diff --git a/ui/src/components/settings/SettingsDependenciesPage.tsx b/ui/src/components/settings/SettingsDependenciesPage.tsxindex d99e46fbd..fa25e8747 100644--- a/ui/src/components/settings/SettingsDependenciesPage.tsx+++ b/ui/src/components/settings/SettingsDependenciesPage.tsx@@ -168,7 +168,7 @@ export const SettingsDependenciesPage: React.FC = () => {const sidecarRunning = isMemoryRuntime && memoryRuntimeSidecarRunning(memoryStatus);const repairBlockedBySidecar = isMemoryRuntime && (!memoryStatusLoaded || sidecarRunning);const dependencyOperationBusy = busy !== null;- const persistedFailure = isMemoryRuntime && d.status === 'error' && d.reason+ const persistedFailure = d.status === 'error' && d.reason? localizedReason(d.reason, t('settings.dependencies.installFailed')): null;return (diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex a2d8c8653..599d86adf 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -1893,6 +1893,7 @@ export type DependencyItem = {reason?: string | null;release_state?: 'published' | 'unavailable' | null;download_error?: DependencyDownloadError | null;+ inspection_error?: { kind: string; message: string } | null;};export type DependenciesResult = { ok: boolean; deps: DependencyItem[] };diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 06acd9298..05818a202 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1920,6 +1920,7 @@"retry": "Retry"},"errors": {+ "runtime_install_inspection_failed": "Show Runtime status could not be inspected. No install or repair was attempted.","task_owner_session_unavailable": "This Task's managing Session is no longer available. Create a replacement Task from an available Agent Session.","share_id_taken": "That custom link is already taken. Pick another.","invalid_share_id": "A custom link may use only 3–64 letters, numbers, dash, or underscore, starting and ending with a letter or number.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex b36821958..9e4be8052 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1920,6 +1920,7 @@"retry": "重试"},"errors": {+ "runtime_install_inspection_failed": "无法检查 Show Runtime 状态。未执行安装或修复。","task_owner_session_unavailable": "这个 Task 的管理 Session 已不可用。请从可用的 Agent Session 创建替代 Task。","share_id_taken": "这个自定义链接已被占用,换一个。","invalid_share_id": "自定义链接只能用 3–64 位字母、数字、短横线或下划线,且首尾为字母或数字。",diff --git a/vibe/api.py b/vibe/api.pyindex 1ed7d9938..85a37d30e 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -9104,22 +9104,22 @@ def dependencies_status(*, offline: bool = False) -> dict:})- try:- from core.show_runtime import ShowRuntimeManager, get_show_runtime_manager+ from core.show_runtime import ShowRuntimeManager, get_show_runtime_manager- srt_manager = ShowRuntimeManager(offline=True) if offline else get_show_runtime_manager()- srt = srt_manager.status()- except Exception as exc: # noqa: BLE001- srt = {- "install": {"state": "absent", "runtime_version": None, "matches_manifest": None},- "node_available": None,- "node_version": None,- "reason": str(exc),- }+ srt_manager = ShowRuntimeManager(offline=True) if offline else get_show_runtime_manager()+ srt = srt_manager.status()manifest = srt.get("manifest") if isinstance(srt.get("manifest"), dict) else {}install = srt.get("install") if isinstance(srt.get("install"), dict) else {}- srt_installed = install.get("state") == "installed"+ install_state = install.get("state")+ srt_installed = True if install_state == "installed" else False if install_state == "absent" else Noneinstalled_matches_manifest = install.get("matches_manifest")+ recovery_action = install.get("recovery_action")+ srt_status = "ready" if srt_installed is True else "missing" if srt_installed is False else "error"+ action_class = (+ "repairable"+ if srt_status in {"ready", "missing"} or recovery_action == "repair"+ else "operator_only"+ )deps.append({"id": "show-runtime",@@ -9128,10 +9128,12 @@ def dependencies_status(*, offline: bool = False) -> dict:"installed": srt_installed,"version": install.get("runtime_version"),"latest_version": manifest.get("runtime_version"),- "has_update": bool(srt_installed and installed_matches_manifest is False),- "status": "ready" if srt_installed else "missing",+ "has_update": bool(srt_installed is True and installed_matches_manifest is False),+ "status": srt_status,+ "action_class": action_class,"reason": srt.get("reason"),"download_error": srt.get("download_error"),+ "inspection_error": srt.get("inspection_error"),})@@ -9159,7 +9161,15 @@ def dependencies_status(*, offline: bool = False) -> dict:# Node present but below the Show Runtime minimum (node_supported is False)# is not actually usable — don't show it green while runtime repair fails.- node_ok = bool(srt.get("node_available")) and srt.get("node_supported") is not False+ node_inspection_failed = (+ install_state == "failed"+ and srt.get("reason") == "runtime_install_inspection_failed"+ )+ node_ok = (+ None+ if node_inspection_failed+ else bool(srt.get("node_available")) and srt.get("node_supported") is not False+ )deps.append({"id": "node",@@ -9167,7 +9177,7 @@ def dependencies_status(*, offline: bool = False) -> dict:"required": True,"installed": node_ok,"version": srt.get("node_version"),- "status": "ready" if node_ok else "missing",+ "status": "error" if node_ok is None else "ready" if node_ok else "missing",})@@ -9202,22 +9212,29 @@ def _prepare_show_runtime_job() -> dict:from core.show_runtime import get_show_runtime_managerfrom vibe.i18n import t as i18n_t- payload = get_show_runtime_manager().prepare(force=True)- install = payload.get("install") if isinstance(payload.get("install"), dict) else {}+ payload = get_show_runtime_manager().repair()ok = bool(payload.get("ok"))- reason = payload.get("reason") or install.get("reason")+ reason = payload.get("reason")+ healthy = payload.get("outcome") == "healthy"result = {"ok": ok,"message": (- i18n_t("runtime.prepare.prepared")+ i18n_t("doctor.repair.showRuntimeHealthy")+ if healthy+ else i18n_t("runtime.prepare.prepared")if okelse i18n_t("runtime.prepare.failed", reason=reason or "unknown")),"output": None,+ "outcome": payload.get("outcome"),+ "changed": payload.get("outcome") == "repaired",}if not ok:- status = payload.get("status") if isinstance(payload.get("status"), dict) else {}- download_error = status.get("download_error") if isinstance(status.get("download_error"), dict) else None+ download_error = (+ payload.get("download_error")+ if isinstance(payload.get("download_error"), dict)+ else None+ )result["reason"] = reasonresult["download_error"] = download_errorif download_error:diff --git a/vibe/cli.py b/vibe/cli.pyindex fe4b14ea4..e8e6be37f 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -23,7 +23,6 @@ import urllib.parseimport urllib.requestfrom dataclasses import dataclassfrom datetime import datetime, timedelta, timezone-from enum import Enumfrom pathlib import Pathfrom textwrap import dedentfrom typing import Any, Callable, Mapping, NamedTuple, Optional@@ -211,6 +210,7 @@ DOCTOR_DISPLAY_PROJECTIONS = {"binary_checksum_mismatch": "doctor.repair.dependencyBinaryVerificationFailed","binary_not_runnable": "doctor.repair.dependencyBinaryNotRunnable","binary_prepare_failed": "doctor.repair.dependencyBinaryPrepareFailed",+ "candidate_validation_failed": "doctor.repair.dependencyCandidateValidationFailed","install_missing_binary": "doctor.repair.dependencyInstallMissingBinary","install_failed": "doctor.repair.installError","install_lock_failed": "doctor.repair.dependencyInstallLockFailed",@@ -11452,6 +11452,28 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:)install = _show_runtime_install(status)+ if (+ install.get("state") == "failed"+ and status.get("reason") == "runtime_install_inspection_failed"+ ):+ inspection = (+ status.get("inspection_error")+ if isinstance(status.get("inspection_error"), dict)+ else {}+ )+ _add_doctor_item(+ items,+ "fail",+ i18n_t(+ "doctor.item.showRuntimeStatusFailed",+ doctor_language,+ reason=inspection.get("message") or status.get("reason"),+ ),+ i18n_t("doctor.action.showRuntimeStatusFailed", doctor_language),+ code="show_runtime.status_failed",+ status_reason=status.get("reason"),+ )+ return itemsinstalled = install.get("state") == "installed"provider = str(status.get("provider") or "unknown")display_provider = _doctor_display_value(provider, "show_runtime_provider", doctor_language)@@ -12564,39 +12586,6 @@ def _doctor_repair_result(target: str, status: str, message: str, **details) ->return payload-class _ShowRuntimeStartabilityState(str, Enum):- STARTABLE = "startable"- NOT_STARTABLE = "not_startable"- UNDETERMINED = "undetermined"---@dataclass(frozen=True)-class _ShowRuntimeStartability:- state: _ShowRuntimeStartabilityState- reason: str | None = None- detail: str | None = None-- def __post_init__(self) -> None:- if self.state is _ShowRuntimeStartabilityState.STARTABLE and (self.reason or self.detail):- raise ValueError("startable outcome cannot carry failure evidence")- if self.state is _ShowRuntimeStartabilityState.NOT_STARTABLE and (not self.reason or self.detail):- raise ValueError("not-startable outcome requires only a reason")- if self.state is _ShowRuntimeStartabilityState.UNDETERMINED and (self.reason or not self.detail):- raise ValueError("undetermined outcome requires only a detail")-- @classmethod- def startable(cls) -> "_ShowRuntimeStartability":- return cls(_ShowRuntimeStartabilityState.STARTABLE)-- @classmethod- def not_startable(cls, reason: str) -> "_ShowRuntimeStartability":- return cls(_ShowRuntimeStartabilityState.NOT_STARTABLE, reason=reason)-- @classmethod- def undetermined(cls, detail: str) -> "_ShowRuntimeStartability":- return cls(_ShowRuntimeStartabilityState.UNDETERMINED, detail=detail)--def _write_refreshed_runtime_status() -> None:# Asked, not re-derived. A repair that wrote its own idea of the state word# would be the second place deciding one fact -- and the one that persists@@ -13025,162 +13014,90 @@ def _repair_show_runtime(*, dry_run: bool = False) -> dict:i18n_t(DOCTOR_REPAIR_DRY_RUN_I18N_KEYS[target], language),)- manager = ShowRuntimeManager()- before = manager.status()- before_install = _show_runtime_install(before)- before_installed = before_install.get("state") == "installed"- before_install_dir = before_install.get("install_dir")-- def verify_startability(command_value: Any) -> _ShowRuntimeStartability:- command = command_value if isinstance(command_value, list) else []- if not command:- return _ShowRuntimeStartability.not_startable("runtime_command_missing")- try:- with tempfile.TemporaryDirectory(prefix="avibe-show-runtime-doctor-") as verification_root_value:- verification_root = Path(verification_root_value)- verifier = ShowRuntimeManager(- command=shlex.join(str(part) for part in command),- workspace_root=verification_root / "show",- runtime_dir=verification_root / "runtime",- auto_install=False,- )- try:- result = asyncio.run(verifier.ensure())- finally:- verifier.stop()- except Exception as exc: # noqa: BLE001- detail = str(exc).strip() or type(exc).__name__- return _ShowRuntimeStartability.undetermined(detail)- if result.available:- return _ShowRuntimeStartability.startable()- return _ShowRuntimeStartability.not_startable(result.reason or "runtime_start_failed")-- if before_installed:- startability = verify_startability(before.get("command"))- if startability.state is _ShowRuntimeStartabilityState.UNDETERMINED:- return _doctor_repair_result(- target,- "failed",- i18n_t("doctor.repair.showRuntimeVerificationFailed", language, detail=startability.detail),- provider=before.get("provider"),- platform=before.get("platform"),- install_dir=before_install_dir,- installed=True,- reason="runtime_start_verification_failed",- start_error=startability.detail,- )- if startability.state is _ShowRuntimeStartabilityState.STARTABLE:- return _doctor_repair_result(- target,- "skipped",- i18n_t("doctor.repair.showRuntimeHealthy", language),- provider=before.get("provider"),- platform=before.get("platform"),- install_dir=before_install_dir,- )- if startability.state is not _ShowRuntimeStartabilityState.NOT_STARTABLE:- raise AssertionError(f"Unhandled Show Runtime startability: {startability.state}")- if before.get("explicit_command"):- reason = startability.reason or "runtime_start_failed"- return _doctor_repair_result(- target,- "failed",- i18n_t("doctor.repair.showRuntimeExplicitFailed", language, reason=reason),- provider=before.get("provider"),- platform=before.get("platform"),- install_dir=before_install_dir,- installed=True,- reason=reason,- explicit_command=before.get("explicit_command"),- )-- archive = before.get("archive") if isinstance(before.get("archive"), dict) else {}- archive_url = str(archive.get("url") or "")- if (- before.get("provider") == "archive"- and "github.com/avibe-bot/vibe-show-runtime/releases/latest/download/" in archive_url- ):+ result = ShowRuntimeManager().repair()+ outcome = result.get("outcome")+ verification = (+ result.get("verification")+ if isinstance(result.get("verification"), dict)+ else {}+ )+ if outcome == "healthy":return _doctor_repair_result(target,- "failed",- i18n_t("doctor.repair.showRuntimeLegacyUnavailable", language),- provider=before.get("provider"),- archive_url=archive_url,+ "skipped",+ i18n_t("doctor.repair.showRuntimeHealthy", language),+ provider=result.get("provider"),+ platform=result.get("platform"),+ install_dir=result.get("install_dir"),)-- result = manager.prepare(force=before_installed)- status = result.get("status") if isinstance(result.get("status"), dict) else {}- status_install = _show_runtime_install(status)- install_dir = status_install.get("install_dir")- status_installed = status_install.get("state") == "installed"- if result.get("ok"):- startability = verify_startability(result.get("command"))- if startability.state is _ShowRuntimeStartabilityState.STARTABLE:- return _doctor_repair_result(- target,- "repaired",- i18n_t(- (- "doctor.repair.showRuntimeReinstalled"- if before_installed- else "doctor.repair.showRuntimeInstalled"- ),- language,- ),- provider=result.get("provider"),- platform=result.get("platform"),- install_dir=install_dir,- )- if startability.state is _ShowRuntimeStartabilityState.NOT_STARTABLE:- reason = startability.reason or "runtime_start_failed"- return _doctor_repair_result(- target,- "failed",- i18n_t(- (- "doctor.repair.showRuntimeReinstallStartFailed"- if before_installed- else "doctor.repair.showRuntimeInstallStartFailed"- ),- language,- reason=reason,+ if outcome == "repaired":+ return _doctor_repair_result(+ target,+ "repaired",+ i18n_t(+ (+ "doctor.repair.showRuntimeReinstalled"+ if result.get("was_installed")+ else "doctor.repair.showRuntimeInstalled"),- provider=result.get("provider"),- platform=result.get("platform"),- install_dir=install_dir,- reason=reason,- )- if startability.state is _ShowRuntimeStartabilityState.UNDETERMINED:- return _doctor_repair_result(- target,- "failed",- i18n_t("doctor.repair.showRuntimePostVerificationFailed", language, detail=startability.detail),- provider=result.get("provider"),- platform=result.get("platform"),- install_dir=install_dir,- reason="runtime_start_verification_failed",- start_error=startability.detail,- )- raise AssertionError(f"Unhandled Show Runtime startability: {startability.state}")+ language,+ ),+ provider=result.get("provider"),+ platform=result.get("platform"),+ install_dir=result.get("install_dir"),+ )reason = str(result.get("reason") or "runtime_prepare_failed")- download_error = status.get("download_error") if isinstance(status.get("download_error"), dict) else None- if download_error:- detail = str(download_error.get("message") or reason)- if download_error.get("url"):- detail = f"{detail}: {download_error['url']}"+ message_kwargs: dict[str, object]+ if result.get("explicit_command"):+ message_key = "doctor.repair.showRuntimeExplicitFailed"+ message_kwargs = {"reason": reason}+ elif reason == "runtime_legacy_archive_unavailable":+ message_key = "doctor.repair.showRuntimeLegacyUnavailable"+ message_kwargs = {}+ elif verification.get("state") == "undetermined":+ message_key = (+ "doctor.repair.showRuntimePostVerificationFailed"+ if result.get("verification_phase") == "after"+ else "doctor.repair.showRuntimeVerificationFailed"+ )+ message_kwargs = {"detail": verification.get("detail") or reason}+ elif result.get("verification_phase") == "after" and verification.get("state") == "not_startable":+ message_key = (+ "doctor.repair.showRuntimeReinstallStartFailed"+ if result.get("was_installed")+ else "doctor.repair.showRuntimeInstallStartFailed"+ )+ message_kwargs = {"reason": verification.get("reason") or reason}else:- detail = reason+ download_error = (+ result.get("download_error")+ if isinstance(result.get("download_error"), dict)+ else None+ )+ detail = str(download_error.get("message") or reason) if download_error else reason+ if download_error and download_error.get("url"):+ detail = f"{detail}: {download_error['url']}"+ message_key = "doctor.repair.showRuntimePrepareFailed"+ message_kwargs = {"detail": detail}+ download_error = (+ result.get("download_error")+ if isinstance(result.get("download_error"), dict)+ else None+ )return _doctor_repair_result(target,"failed",- i18n_t("doctor.repair.showRuntimePrepareFailed", language, detail=detail),+ i18n_t(message_key, language, **message_kwargs),provider=result.get("provider"),platform=result.get("platform"),- install_dir=install_dir,- installed=status_installed,+ install_dir=result.get("install_dir"),+ installed=result.get("installed"),reason=reason,download_error=download_error,+ start_error=result.get("start_error"),+ explicit_command=result.get("explicit_command"),+ archive_url=result.get("archive_url"),)diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 372b5993f..a0fb0ac1d 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1382,6 +1382,7 @@"dependencyBinaryVerificationFailed": "The {target} binary failed checksum verification.","dependencyBinaryNotRunnable": "The {target} binary is not runnable.","dependencyBinaryPrepareFailed": "The {target} binary could not be prepared.",+ "dependencyCandidateValidationFailed": "The {target} installation candidate could not be validated.","dependencyInstallMissingBinary": "The {target} archive did not contain its binary.","dependencyInstallLockFailed": "The {target} installation lock could not be acquired: {error}.","dependencyInstallClaimFailed": "The {target} installation claim could not be recorded: {error}.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 3e52807df..61fa972ea 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1382,6 +1382,7 @@"dependencyBinaryVerificationFailed": "{target} 二进制校验和验证失败。","dependencyBinaryNotRunnable": "{target} 二进制无法运行。","dependencyBinaryPrepareFailed": "无法准备 {target} 二进制。",+ "dependencyCandidateValidationFailed": "无法验证 {target} 安装候选项。","dependencyInstallMissingBinary": "{target} 归档不包含其二进制文件。","dependencyInstallLockFailed": "无法获取 {target} 安装锁:{error}。","dependencyInstallClaimFailed": "无法记录 {target} 安装声明:{error}。",