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
feat(deps): unify retry and Doctor diagnostics (#913)
Call White869f07bcbb96
diff --git a/core/dependency_network.py b/core/dependency_network.pynew file mode 100644index 000000000..cfc9f8706--- /dev/null+++ b/core/dependency_network.py@@ -0,0 +1,294 @@+"""Shared network reliability and diagnostics for managed dependencies."""++from __future__ import annotations++import errno+import http.client+import logging+import shutil+import socket+import ssl+import time+import urllib.error+import urllib.parse+import urllib.request+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable, TypeVar+++logger = logging.getLogger(__name__)+++@dataclass(frozen=True)+class RetryPolicy:+ max_attempts: int+ initial_delay: float+ max_delay: float+++DOWNLOAD_RETRY_POLICY = RetryPolicy(max_attempts=3, initial_delay=1.0, max_delay=4.0)+PROBE_RETRY_POLICY = RetryPolicy(max_attempts=2, initial_delay=0.5, max_delay=0.5)+++class DependencyNetworkError(RuntimeError):+ """A dependency request that exhausted its retry policy."""++ def __init__(self, details: dict[str, Any]):+ self.details = details+ super().__init__(str(details.get("message") or "Dependency network request failed"))+++def redact_url(url: str) -> str:+ parsed = urllib.parse.urlparse(url)+ if parsed.scheme not in {"http", "https", "file"}:+ return f"{parsed.scheme}:" if parsed.scheme else ""+ if parsed.scheme == "file":+ return urllib.parse.urlunparse((parsed.scheme, "", parsed.path, "", "", ""))+ hostname = parsed.hostname or ""+ if ":" in hostname and not hostname.startswith("["):+ hostname = f"[{hostname}]"+ try:+ port = parsed.port+ except ValueError:+ port = None+ netloc = f"{hostname}:{port}" if port else hostname+ return urllib.parse.urlunparse((parsed.scheme, netloc, parsed.path, "", "", ""))+++def dependency_error_details(exc: BaseException, url: str, *, attempts: int = 1) -> dict[str, Any]:+ if isinstance(exc, DependencyNetworkError):+ return dict(exc.details)++ safe_url = redact_url(url)+ host = urllib.parse.urlparse(url).hostname+ error: dict[str, Any] = {+ "kind": "unknown",+ "message": "Unexpected dependency request failure",+ "url": safe_url,+ "host": host,+ "exception_type": type(exc).__name__,+ "retryable": False,+ "attempts": attempts,+ }+ if isinstance(exc, urllib.error.HTTPError):+ retryable = exc.code in {408, 425, 429, 500, 502, 503, 504}+ error.update(+ kind="http",+ message=f"HTTP {exc.code} {exc.reason or ''}".strip(),+ http_status=exc.code,+ retryable=retryable,+ )+ retry_after = _retry_after_seconds(exc)+ if retry_after is not None:+ error["retry_after_seconds"] = retry_after+ return error++ root = exc.reason if isinstance(exc, urllib.error.URLError) else exc+ error["exception_type"] = type(root).__name__+ if isinstance(root, socket.gaierror):+ error.update(kind="dns", message=f"DNS lookup failed for {host or 'dependency host'}", retryable=True)+ elif isinstance(root, (ssl.SSLCertVerificationError, ssl.CertificateError)):+ error.update(kind="tls", message="TLS certificate verification failed")+ elif isinstance(root, ssl.SSLError):+ error.update(kind="tls", message="TLS negotiation failed")+ elif isinstance(root, (TimeoutError, socket.timeout)):+ error.update(kind="timeout", message="Connection timed out", retryable=True)+ elif isinstance(root, PermissionError):+ error.update(kind="permission", message="Permission denied while storing the dependency")+ elif isinstance(root, OSError) and root.errno == errno.ENOSPC:+ error.update(kind="disk", message="No space left while storing the dependency")+ elif isinstance(root, (ConnectionError, http.client.IncompleteRead, http.client.RemoteDisconnected)):+ error.update(kind="network", message=f"Network request failed ({type(root).__name__})", retryable=True)+ elif isinstance(root, OSError) and root.errno in {+ errno.ECONNABORTED,+ errno.ECONNREFUSED,+ errno.ECONNRESET,+ errno.EHOSTUNREACH,+ errno.ENETDOWN,+ errno.ENETUNREACH,+ errno.ETIMEDOUT,+ }:+ error.update(kind="network", message=f"Network request failed ({type(root).__name__})", retryable=True)+ elif urllib.parse.urlparse(url).scheme == "file" and isinstance(root, OSError):+ error.update(kind="io", message=f"Local dependency file access failed ({type(root).__name__})")+ elif isinstance(exc, urllib.error.URLError):+ error.update(kind="network", message=f"Network request failed ({type(root).__name__})", retryable=True)+ elif isinstance(root, OSError):+ error.update(kind="io", message=f"Local or network I/O failed ({type(root).__name__})")+ return error+++def dependency_error_message(error: dict[str, Any] | None, *, label: str) -> str:+ details = error or {}+ attempts = int(details.get("attempts") or 1)+ attempt_text = f" after {attempts} attempts" if attempts > 1 else ""+ message = str(details.get("message") or details.get("kind") or "request failed")+ url = str(details.get("url") or "")+ suffix = f" ({url})" if url else ""+ return f"{label} failed{attempt_text}: {message}{suffix}"+++def fetch_bytes(+ request: str | urllib.request.Request,+ *,+ timeout: float,+ policy: RetryPolicy = DOWNLOAD_RETRY_POLICY,+ opener: Callable[..., Any] | None = None,+) -> bytes:+ resolved_opener = opener or urllib.request.urlopen++ def operation() -> bytes:+ with resolved_opener(request, timeout=timeout) as response:+ return response.read()++ return _run_with_retry(request, operation, policy=policy)+++def fetch_to_path(+ request: str | urllib.request.Request,+ target: Path,+ *,+ timeout: float,+ policy: RetryPolicy = DOWNLOAD_RETRY_POLICY,+ opener: Callable[..., Any] | None = None,+) -> None:+ resolved_opener = opener or urllib.request.urlopen++ def operation() -> None:+ _unlink_quietly(target)+ with resolved_opener(request, timeout=timeout) as response, target.open("wb") as destination:+ shutil.copyfileobj(response, destination)++ try:+ _run_with_retry(request, operation, policy=policy)+ except BaseException:+ _unlink_quietly(target)+ raise+++def probe_url(+ url: str,+ *,+ timeout: float = 10.0,+ policy: RetryPolicy = PROBE_RETRY_POLICY,+ opener: Callable[..., Any] | None = None,+ user_agent: str = "avibe-dependency-doctor",+) -> dict[str, Any]:+ parsed = urllib.parse.urlparse(url)+ if parsed.scheme == "file":+ path = Path(urllib.request.url2pathname(parsed.path))+ if path.is_file():+ return {+ "ok": True,+ "checked": True,+ "kind": "local_file",+ "url": redact_url(url),+ "path": str(path),+ "reason": None,+ }+ error = dependency_error_details(FileNotFoundError(errno.ENOENT, "dependency file not found", path), url)+ return {+ "ok": False,+ "checked": True,+ "kind": "local_file",+ "url": redact_url(url),+ "path": str(path),+ "reason": "dependency_file_missing",+ "download_error": error,+ }++ request = urllib.request.Request(url, headers={"User-Agent": user_agent}, method="HEAD")+ resolved_opener = opener or urllib.request.urlopen++ def operation() -> tuple[int, str]:+ with resolved_opener(request, timeout=timeout) as response:+ status_code = getattr(response, "status", None) or response.getcode()+ final_url = response.geturl() if hasattr(response, "geturl") else url+ return int(status_code), str(final_url)++ try:+ status_code, final_url = _run_with_retry(request, operation, policy=policy)+ except DependencyNetworkError as exc:+ error = dict(exc.details)+ if error.get("kind") == "http" and error.get("http_status") in {405, 501}:+ return {+ "ok": False,+ "checked": False,+ "kind": "head_unsupported",+ "http_status": error.get("http_status"),+ "url": redact_url(url),+ "reason": "dependency_probe_unsupported",+ "download_error": error,+ }+ return {+ "ok": False,+ "checked": True,+ "reason": "dependency_download_failed",+ "download_error": error,+ }+ return {+ "ok": 200 <= status_code < 400,+ "checked": True,+ "kind": "reachable",+ "http_status": status_code,+ "url": redact_url(url),+ "final_host": urllib.parse.urlparse(final_url).hostname,+ "reason": None,+ }+++T = TypeVar("T")+++def _run_with_retry(+ request: str | urllib.request.Request,+ operation: Callable[[], T],+ *,+ policy: RetryPolicy,+) -> T:+ if policy.max_attempts < 1:+ raise ValueError("retry policy must allow at least one attempt")+ url = request.full_url if isinstance(request, urllib.request.Request) else str(request)+ for attempt in range(1, policy.max_attempts + 1):+ try:+ return operation()+ except Exception as exc: # noqa: BLE001+ details = dependency_error_details(exc, url, attempts=attempt)+ close = getattr(exc, "close", None)+ if callable(close):+ close()+ if not details.get("retryable") or attempt >= policy.max_attempts:+ raise DependencyNetworkError(details) from exc+ delay = details.get("retry_after_seconds")+ if not isinstance(delay, (int, float)):+ delay = min(policy.initial_delay * (2 ** (attempt - 1)), policy.max_delay)+ delay = min(max(0.0, float(delay)), policy.max_delay)+ logger.warning(+ "Dependency request attempt %d/%d failed for %s (%s); retrying in %.1fs",+ attempt,+ policy.max_attempts,+ redact_url(url),+ details.get("kind"),+ delay,+ )+ time.sleep(delay)+ raise AssertionError("retry loop exhausted without returning or raising")+++def _retry_after_seconds(exc: urllib.error.HTTPError) -> float | None:+ headers = getattr(exc, "headers", None)+ value = headers.get("Retry-After") if headers is not None else None+ if value is None:+ return None+ try:+ return max(0.0, float(value))+ except (TypeError, ValueError):+ return None+++def _unlink_quietly(path: Path) -> None:+ try:+ path.unlink(missing_ok=True)+ except OSError:+ passdiff --git a/core/managed_runtime.py b/core/managed_runtime.pyindex e41fc3639..fb1b245f2 100644--- a/core/managed_runtime.py+++ b/core/managed_runtime.py@@ -20,6 +20,14 @@ from pathlib import Path, PurePosixPath, PureWindowsPathfrom sysconfig import get_platformfrom typing import Any+from core.dependency_network import (+ dependency_error_details,+ dependency_error_message,+ fetch_bytes,+ fetch_to_path,+ probe_url,+ redact_url,+)from storage.lock import MigrationFileLock, MigrationLockTimeout@@ -84,6 +92,7 @@ class ManagedRuntimeManager:self.manifest_url = manifest_urlself.offline = offlineself._install_reason: str | None = None+ self._download_error: dict[str, Any] | None = Noneself._install_lock = install_lock_for(spec.runtime_id)self._install_file_lock_path = self.runtime_dir / ".install.lock"@@ -241,8 +250,36 @@ class ManagedRuntimeManager:"manifest": self._manifest_status_payload(manifest),"archive": self._archive_status_payload(archive),"reason": self._install_reason,+ "download_error": self._download_error,}+ def probe_archive_reachability(self, *, timeout: float = 10.0) -> dict[str, Any]:+ manifest = self._load_manifest(allow_network=not self.offline)+ if manifest is None:+ return {+ "ok": False,+ "checked": bool(self._download_error),+ "reason": self._install_reason or self._reason("manifest_missing"),+ "download_error": self._download_error,+ }+ archive = self._manifest_archive_for_platform(manifest)+ if archive is None:+ return {"ok": False, "checked": False, "reason": self._install_reason}+ parsed = urllib.parse.urlparse(archive.url)+ if parsed.scheme not in {"https", "file"}:+ return {+ "ok": False,+ "checked": False,+ "reason": self._reason("archive_url_unsupported"),+ "url": redact_url(archive.url),+ }+ return probe_url(+ archive.url,+ timeout=timeout,+ opener=urllib.request.urlopen,+ user_agent=f"avibe-{self.spec.runtime_id}-doctor",+ )+def clean(self, *, keep_previous: int = 1) -> dict[str, Any]:try:file_lock = self._acquire_mutation_lock()@@ -338,11 +375,15 @@ class ManagedRuntimeManager:self._install_reason = self._reason("manifest_url_unsupported")return Nonetry:- with urllib.request.urlopen(self.manifest_url, timeout=30) as response:- payload = response.read()- except Exception: # noqa: BLE001+ payload = fetch_bytes(+ self.manifest_url,+ timeout=30,+ opener=urllib.request.urlopen,+ )+ except Exception as exc: # noqa: BLE001logger.exception("Failed to download %s manifest", self.spec.runtime_id)self._install_reason = self._reason("manifest_download_failed")+ self._download_error = dependency_error_details(exc, self.manifest_url)return Noneloaded_from = self.manifest_urlcache_remote = True@@ -453,18 +494,24 @@ class ManagedRuntimeManager:cached.parent.mkdir(parents=True, exist_ok=True)temporary = cached.with_suffix(cached.suffix + ".tmp")try:- with urllib.request.urlopen(archive.url, timeout=60) as response, temporary.open("wb") as destination:- shutil.copyfileobj(response, destination)+ fetch_to_path(+ archive.url,+ temporary,+ timeout=60,+ opener=urllib.request.urlopen,+ )+ self._download_error = Noneif not self._downloaded_archive_matches(temporary, archive):temporary.unlink(missing_ok=True)return Nonetemporary.replace(cached)self._install_reason = Nonereturn cached- except Exception: # noqa: BLE001+ except Exception as exc: # noqa: BLE001logger.exception("Failed to download %s archive", self.spec.runtime_id)temporary.unlink(missing_ok=True)self._install_reason = self._reason("archive_download_failed")+ self._download_error = dependency_error_details(exc, archive.url)return Nonedef _downloaded_archive_matches(self, path: Path, archive: ManagedRuntimeArchive) -> bool:@@ -598,7 +645,7 @@ class ManagedRuntimeManager:return {"platform": archive.platform,"name": archive.name,- "url": archive.url,+ "url": redact_url(archive.url),"sha256": archive.sha256,"binary_sha256": archive.binary_sha256,"size": archive.size,@@ -638,6 +685,7 @@ class ManagedRuntimeManager:*,changed: bool,) -> dict[str, Any]:+ self._download_error = Nonereturn {"ok": True,"installed": True,@@ -664,10 +712,16 @@ class ManagedRuntimeManager:"changed": False,"skipped": skipped,"reason": reason,- "message": message or reason,+ "message": message+ or (+ dependency_error_message(self._download_error, label=f"{self.spec.runtime_id} dependency download")+ if self._download_error+ else reason+ ),"version": manifest.runtime_version if manifest else None,"platform": archive.platform if archive else runtime_platform_tag(),"path": None,+ "download_error": self._download_error,}def _reason(self, suffix: str) -> str:diff --git a/core/show_runtime.py b/core/show_runtime.pyindex 921993df8..4a948e182 100644--- a/core/show_runtime.py+++ b/core/show_runtime.py@@ -25,6 +25,7 @@ from typing import Anyimport httpxfrom config import paths+from core.dependency_network import dependency_error_details, fetch_bytes, fetch_to_path, probe_url, redact_urlfrom core.show_pages import SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDSfrom core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree@@ -132,6 +133,7 @@ class ShowRuntimeManager:self.cache_root = self.runtime_dir / "vite-cache"self._install_attempted = Falseself._install_reason: str | None = None+ self._download_error: dict[str, Any] | None = Noneself._managed_command: list[str] | None = Noneself._process: subprocess.Popen[str] | None = Noneself._base_url: str | None = None@@ -388,6 +390,7 @@ class ShowRuntimeManager:self._install_reason = "runtime_source_unsupported"return Noneif command:+ self._download_error = Noneself._clean_after_managed_install(command)return command@@ -421,6 +424,7 @@ class ShowRuntimeManager:installed_command: list[str] | None = configured_commandinstalled_dir: Path | None = Nonearchive: ShowRuntimeArchive | None = None+ archive_status: dict[str, Any] | None = Noneinstalled_matches = Falseif not configured_command and manifest:archive = manifest.archives.get(platform_tag)@@ -432,6 +436,14 @@ class ShowRuntimeManager:elif not configured_command and self.runtime_source == _RUNTIME_SOURCE_ARCHIVE:installed_dir = self._archive_install_dir()installed_command = self._archive_runtime_command(installed_dir, node or ["node"])+ archive_status = {+ "platform": platform_tag,+ "name": _runtime_archive_name(),+ "url": _redact_download_url(self.archive_url) if not self.archive_path else None,+ "path": str(self.archive_path) if self.archive_path else None,+ "sha256": None,+ "size": None,+ }elif not configured_command and self.runtime_source == _RUNTIME_SOURCE_GITHUB:installed_dir = self._github_source_dir()installed_command = self._github_runtime_command(installed_dir, node or ["node"])@@ -446,14 +458,83 @@ class ShowRuntimeManager:"node_version": _format_semver(node_version),"node_supported": node_supported,"manifest": _manifest_status_payload(manifest),- "archive": _archive_status_payload(archive),+ "archive": archive_status or _archive_status_payload(archive),"installed": installed_command is not None,"installed_matches_manifest": installed_matches,"install_dir": str(installed_dir) if installed_dir else None,"command": installed_command,"reason": self._install_reason,+ "download_error": self._download_error,}+ def probe_archive_reachability(self, *, timeout: float = 10.0) -> dict[str, Any]:+ """Check the selected archive without downloading its body or mutating the cache."""+ archive_url: str | None = None+ if self.runtime_source == _RUNTIME_SOURCE_MANIFEST:+ manifest = self._load_runtime_manifest()+ if not manifest:+ return {+ "ok": False,+ "checked": False,+ "reason": self._install_reason or "runtime_manifest_missing",+ "download_error": self._download_error,+ }+ archive = self._manifest_archive_for_platform(manifest)+ if not archive:+ return {+ "ok": False,+ "checked": False,+ "reason": self._install_reason or "runtime_platform_unsupported",+ }+ archive_url = archive.url+ elif self.runtime_source == _RUNTIME_SOURCE_ARCHIVE:+ if self.archive_path:+ return {+ "ok": self.archive_path.is_file(),+ "checked": True,+ "kind": "local_file",+ "path": str(self.archive_path),+ "reason": None if self.archive_path.is_file() else "runtime_archive_missing",+ }+ archive_url = self.archive_url+ else:+ return {+ "ok": False,+ "checked": False,+ "reason": "runtime_archive_probe_not_applicable",+ "provider": self.runtime_source,+ }++ parsed = urllib.parse.urlparse(archive_url)+ if parsed.scheme == "file":+ path = Path(urllib.request.url2pathname(parsed.path))+ return {+ "ok": path.is_file(),+ "checked": True,+ "kind": "local_file",+ "url": _redact_download_url(archive_url),+ "reason": None if path.is_file() else "runtime_archive_missing",+ }+ if parsed.scheme != "https":+ return {+ "ok": False,+ "checked": False,+ "url": _redact_download_url(archive_url),+ "reason": "runtime_archive_url_unsupported",+ }++ result = probe_url(+ archive_url,+ timeout=timeout,+ opener=urllib.request.urlopen,+ user_agent="avibe-show-runtime-doctor",+ )+ if result.get("reason") == "dependency_probe_unsupported":+ result["reason"] = "runtime_archive_probe_unsupported"+ elif result.get("reason") == "dependency_download_failed":+ result["reason"] = "runtime_archive_download_failed"+ return result+def clean(self, *, keep_previous: int = 1) -> dict[str, Any]:removed: list[str] = []for pattern in ("prebuilt-*", "manifest-*"):@@ -698,12 +779,16 @@ class ShowRuntimeManager:self._install_reason = "runtime_manifest_unavailable_offline"return Nonetry:- with urllib.request.urlopen(self.manifest_url, timeout=30) as response:- payload = response.read()+ payload = fetch_bytes(+ self.manifest_url,+ timeout=30,+ opener=urllib.request.urlopen,+ )source = self.manifest_url- except Exception:+ except Exception as exc:logger.exception("Failed to download Show Runtime manifest from %s", self.manifest_url)self._install_reason = "runtime_manifest_download_failed"+ self._download_error = _runtime_download_error(exc, self.manifest_url)return Noneelse:try:@@ -765,6 +850,7 @@ class ShowRuntimeManager:def _resolve_manifest_archive(self, archive: ShowRuntimeArchive) -> Path | None:cached = self.runtime_dir / "downloads" / f"{archive.sha256}.tgz"if cached.exists() and self._downloaded_archive_matches(cached, archive):+ self._download_error = Nonereturn cachedif self.offline:self._install_reason = "runtime_archive_unavailable_offline"@@ -776,17 +862,23 @@ class ShowRuntimeManager:tmp_path = cached.with_suffix(".tmp")cached.parent.mkdir(parents=True, exist_ok=True)try:- with urllib.request.urlopen(archive.url, timeout=60) as response, tmp_path.open("wb") as destination:- shutil.copyfileobj(response, destination)+ fetch_to_path(+ archive.url,+ tmp_path,+ timeout=60,+ opener=urllib.request.urlopen,+ )if not self._downloaded_archive_matches(tmp_path, archive):tmp_path.unlink(missing_ok=True)return Nonetmp_path.replace(cached)+ self._download_error = Nonereturn cached- except Exception:+ except Exception as exc:logger.exception("Failed to download Show Runtime archive from %s", archive.url)tmp_path.unlink(missing_ok=True)self._install_reason = "runtime_archive_download_failed"+ self._download_error = _runtime_download_error(exc, archive.url)return Nonedef _downloaded_archive_matches(self, path: Path, archive: ShowRuntimeArchive) -> bool:@@ -957,11 +1049,17 @@ class ShowRuntimeManager:target = self.runtime_dir / "downloads" / _runtime_archive_name()target.parent.mkdir(parents=True, exist_ok=True)try:- with urllib.request.urlopen(archive_url, timeout=60) as response, target.open("wb") as destination:- shutil.copyfileobj(response, destination)- except Exception:+ fetch_to_path(+ archive_url,+ target,+ timeout=60,+ opener=urllib.request.urlopen,+ )+ self._download_error = None+ except Exception as exc:logger.exception("Failed to download prebuilt Show Runtime from %s", archive_url)self._install_reason = "runtime_archive_download_failed"+ self._download_error = _runtime_download_error(exc, archive_url)return Nonereturn target@@ -1377,13 +1475,21 @@ def _manifest_status_payload(manifest: ShowRuntimeManifest | None) -> dict[str,}+def _redact_download_url(url: str) -> str:+ return redact_url(url)+++def _runtime_download_error(exc: BaseException, url: str) -> dict[str, Any]:+ return dependency_error_details(exc, url)++def _archive_status_payload(archive: ShowRuntimeArchive | None) -> dict[str, Any] | None:if archive is None:return Nonereturn {"platform": archive.platform,"name": archive.name,- "url": archive.url,+ "url": _redact_download_url(archive.url),"sha256": archive.sha256,"size": archive.size,}diff --git a/core/tmux_runtime.py b/core/tmux_runtime.pyindex 27506dff0..97376b194 100644--- a/core/tmux_runtime.py+++ b/core/tmux_runtime.py@@ -21,6 +21,14 @@ from sysconfig import get_platformfrom typing import Anyfrom config import paths+from core.dependency_network import (+ dependency_error_details,+ dependency_error_message,+ fetch_bytes,+ fetch_to_path,+ probe_url,+ redact_url,+)from core.process_isolation import isolated_subprocess_kwargs@@ -78,6 +86,7 @@ class TmuxRuntimeManager:self.manifest_url = manifest_url if manifest_url is not None else os.environ.get("VIBE_TMUX_MANIFEST_URL")self.offline = _env_flag_enabled("VIBE_TMUX_OFFLINE", default=False) if offline is None else offlineself._install_reason: str | None = None+ self._download_error: dict[str, Any] | None = Nonedef ensure(self, *, force: bool = False) -> dict[str, Any]:if not _TMUX_INSTALL_LOCK.acquire(blocking=False):@@ -195,8 +204,36 @@ class TmuxRuntimeManager:"manifest": _manifest_status_payload(manifest),"archive": _archive_status_payload(archive),"reason": self._install_reason,+ "download_error": self._download_error,}+ def probe_archive_reachability(self, *, timeout: float = 10.0) -> dict[str, Any]:+ manifest = self._load_manifest()+ if manifest is None:+ return {+ "ok": False,+ "checked": bool(self._download_error),+ "reason": self._install_reason or "tmux_manifest_missing",+ "download_error": self._download_error,+ }+ archive = self._manifest_archive_for_platform(manifest)+ if archive is None:+ return {"ok": False, "checked": False, "reason": self._install_reason}+ parsed = urllib.parse.urlparse(archive.url)+ if parsed.scheme not in {"https", "file"}:+ return {+ "ok": False,+ "checked": False,+ "reason": "tmux_archive_url_unsupported",+ "url": redact_url(archive.url),+ }+ return probe_url(+ archive.url,+ timeout=timeout,+ opener=urllib.request.urlopen,+ user_agent="avibe-tmux-doctor",+ )+def _load_manifest(self) -> TmuxManifest | None:payload: bytes | None = Noneloaded_from = ""@@ -211,12 +248,16 @@ class TmuxRuntimeManager:self._install_reason = "tmux_manifest_unavailable_offline"return Nonetry:- with urllib.request.urlopen(self.manifest_url, timeout=30) as response:- payload = response.read()+ payload = fetch_bytes(+ self.manifest_url,+ timeout=30,+ opener=urllib.request.urlopen,+ )loaded_from = self.manifest_url- except Exception:+ except Exception as exc:logger.exception("Failed to download tmux manifest from %s", self.manifest_url)self._install_reason = "tmux_manifest_download_failed"+ self._download_error = dependency_error_details(exc, self.manifest_url)return Noneelse:try:@@ -284,17 +325,23 @@ class TmuxRuntimeManager:tmp_path = cached.with_suffix(cached.suffix + ".tmp")cached.parent.mkdir(parents=True, exist_ok=True)try:- with urllib.request.urlopen(archive.url, timeout=60) as response, tmp_path.open("wb") as destination:- shutil.copyfileobj(response, destination)+ fetch_to_path(+ archive.url,+ tmp_path,+ timeout=60,+ opener=urllib.request.urlopen,+ )+ self._download_error = Noneif not self._downloaded_archive_matches(tmp_path, archive):tmp_path.unlink(missing_ok=True)return Nonetmp_path.replace(cached)return cached- except Exception:+ except Exception as exc:logger.exception("Failed to download tmux archive from %s", archive.url)tmp_path.unlink(missing_ok=True)self._install_reason = "tmux_archive_download_failed"+ self._download_error = dependency_error_details(exc, archive.url)return Nonedef _downloaded_archive_matches(self, path: Path, archive: TmuxArchive) -> bool:@@ -425,11 +472,17 @@ class TmuxRuntimeManager:"installed": False,"changed": False,"reason": reason,- "message": message or _reason_message(reason),+ "message": message+ or (+ dependency_error_message(self._download_error, label="tmux dependency download")+ if self._download_error+ else _reason_message(reason)+ ),"version": manifest.tmux_version if manifest else None,"platform": archive.platform if archive else _runtime_platform_tag(),"path": None,"output": None,+ "download_error": self._download_error,}@@ -623,7 +676,7 @@ def _archive_status_payload(archive: TmuxArchive | None) -> dict[str, Any] | Nonreturn {"platform": archive.platform,"name": archive.name,- "url": archive.url,+ "url": redact_url(archive.url),"sha256": archive.sha256,"size": archive.size,"bin_path": archive.bin_path,diff --git a/docs/CLI.md b/docs/CLI.mdindex 02104826b..05aa23a1a 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -113,6 +113,11 @@ vibe doctor repair home-migration --yesvibe doctor repair duplicate-service-processes --yesvibe doctor repair stale-install-runtime --yesvibe doctor repair stale-restart-state --yes+vibe doctor repair askill --yes+vibe doctor repair avault --yes+vibe doctor repair git-runtime --yes+vibe doctor repair show-runtime --yes+vibe doctor repair tmux --yes```**Checks:**@@ -121,6 +126,9 @@ vibe doctor repair stale-restart-state --yes- Agent CLI availability (Claude Code, OpenCode, Codex)- Runtime home migration state- Runtime process, install, and restart metadata state+- askill, avault, Git Runtime, Show Runtime, tmux, and Node.js readiness through one dependency diagnostic group+- `vibe doctor --deep` also probes missing dependencies without downloading their bodies+- managed downloads retry transient HTTP, DNS, timeout, and connection failures with bounded backoff### `vibe remote`diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.mdindex 4e6157d58..a5a1600d1 100644--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@ -98,6 +98,11 @@ vibe doctor repair home-migration --yesvibe doctor repair duplicate-service-processes --yesvibe doctor repair stale-install-runtime --yesvibe doctor repair stale-restart-state --yes+vibe doctor repair askill --yes+vibe doctor repair avault --yes+vibe doctor repair git-runtime --yes+vibe doctor repair show-runtime --yes+vibe doctor repair tmux --yes```**检查内容:**@@ -106,6 +111,9 @@ vibe doctor repair stale-restart-state --yes- Agent CLI 可用性(Claude Code、OpenCode、Codex)- runtime home 迁移状态- runtime 进程、安装来源和重启元数据状态+- 通过统一依赖诊断组检查 askill、avault、Git Runtime、Show Runtime、tmux 和 Node.js+- `vibe doctor --deep` 还会在不下载正文的情况下探测缺失依赖的精确地址+- 托管下载会对临时 HTTP、DNS、超时和连接故障执行有界退避重试### `vibe remote`diff --git a/docs/COMMANDS.md b/docs/COMMANDS.mdindex fe8193843..54d6c6c44 100644--- a/docs/COMMANDS.md+++ b/docs/COMMANDS.md@@ -608,6 +608,9 @@ vibe doctor- checks backend CLI availability- checks runtime home migration state- checks runtime process, install, and restart metadata state+- checks askill, avault, Git Runtime, Show Runtime, tmux, and Node.js through one dependency diagnostic group+- `vibe doctor --deep` probes missing dependency endpoints without downloading their bodies+- managed downloads retry transient HTTP, DNS, timeout, and connection failures with bounded backoffRepair mode is explicit and supports dry-run:@@ -617,6 +620,11 @@ vibe doctor repair home-migration --yesvibe doctor repair duplicate-service-processes --yesvibe doctor repair stale-install-runtime --yesvibe doctor repair stale-restart-state --yes+vibe doctor repair askill --yes+vibe doctor repair avault --yes+vibe doctor repair git-runtime --yes+vibe doctor repair show-runtime --yes+vibe doctor repair tmux --yes```### `vibe remote`diff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.mdindex 04f9e1a5f..77d37d336 100644--- a/docs/COMMANDS_ZH.md+++ b/docs/COMMANDS_ZH.md@@ -587,6 +587,9 @@ vibe doctor- 检查 backend CLI 是否可用- 检查 runtime home 迁移状态- 检查 runtime 进程、安装来源和重启元数据状态+- 通过统一依赖诊断组检查 askill、avault、Git Runtime、Show Runtime、tmux 和 Node.js+- `vibe doctor --deep` 会在不下载正文的情况下探测缺失依赖的地址+- 托管下载会对临时 HTTP、DNS、超时和连接故障执行有界退避重试修复模式需要显式执行,并支持 dry-run:@@ -596,6 +599,11 @@ vibe doctor repair home-migration --yesvibe doctor repair duplicate-service-processes --yesvibe doctor repair stale-install-runtime --yesvibe doctor repair stale-restart-state --yes+vibe doctor repair askill --yes+vibe doctor repair avault --yes+vibe doctor repair git-runtime --yes+vibe doctor repair show-runtime --yes+vibe doctor repair tmux --yes```### `vibe remote`diff --git a/docs/plans/dependency-reliability.md b/docs/plans/dependency-reliability.mdnew file mode 100644index 000000000..f7f5a8bd7--- /dev/null+++ b/docs/plans/dependency-reliability.md@@ -0,0 +1,33 @@+# Managed Dependency Reliability++## Problem++Avibe installs local dependencies through several implementations. Show+Runtime, Git Runtime, tmux, avault, and script-based installers currently use+different retry behavior and return different failure details. Doctor cannot+give one consistent answer when a dependency is missing or unreachable.++## Design++- Introduce one dependency network layer for bounded retries, URL redaction,+ reachability probes, and HTTP/DNS/TLS/timeout/local-I/O classification.+- Retry only transient failures: timeouts, DNS/network resets, HTTP 408/425/429,+ and HTTP 5xx. Do not retry missing assets, certificate failures, checksum+ failures, permissions, disk exhaustion, or unsupported platforms.+- Reuse the network layer from Show Runtime, managed Git Runtime, tmux, and+ avault. Script installers use the same bounded curl retry policy.+- Keep the bootstrap installers aligned with the same three-attempt bound for+ downloading uv before the Python dependency layer exists.+- Present askill, avault, Git Runtime, Show Runtime, tmux, and Node.js in one Doctor+ dependency group with stable codes and explicit repair targets. Node.js is+ diagnosed but remains a manual system dependency.+- Keep bare `vibe doctor repair` non-networking. Dependency downloads remain+ explicit targets so diagnosis never silently changes the machine.++## Verification++- Contract tests for retryable and terminal error classes, attempt counts,+ Retry-After behavior, and redacted structured details.+- Installer tests for each managed dependency plus fast/deep Doctor coverage.+- Existing Show Runtime, Git Runtime, tmux, local dependency, CLI, and UI API+ suites remain green.diff --git a/docs/plans/show-runtime-doctor.md b/docs/plans/show-runtime-doctor.mdnew file mode 100644index 000000000..53553936a--- /dev/null+++ b/docs/plans/show-runtime-doctor.md@@ -0,0 +1,36 @@+# Show Runtime Doctor Diagnostics++## Problem++Show Runtime archive downloads currently collapse HTTP, DNS, TLS, timeout,+permission, and disk failures into `runtime_archive_download_failed`. The+Dependencies page can retry the install, but support cannot tell whether a+retry is useful from that reason alone.++## Design++The implementation now uses the shared managed-dependency network and Doctor+contracts described in `dependency-reliability.md`; Show Runtime is one+dependency adapter rather than a separate retry/error taxonomy.++- Keep `vibe doctor` fast and read-only: inspect the selected provider,+ packaged manifest, platform archive, Node.js compatibility, and installed+ runtime state without making a network request.+- Let `vibe doctor --deep` send a body-free `HEAD` request to the exact selected+ archive URL. Report HTTP status, DNS, TLS, and timeout failures separately.+- Record a redacted structured download error on failed prepare attempts so+ `vibe runtime prepare --json` and Doctor repair results retain the root cause.+- Add the explicit low-risk repair target `vibe doctor repair show-runtime`.+ It prepares the version-pinned archive and reuses verified cache data.+- Do not include Show Runtime in bare `vibe doctor repair`; downloading a+ runtime remains an explicit operation.+- Refuse the legacy implicit URL under+ `avibe-bot/vibe-show-runtime/releases/latest`. Official releases must use the+ manifest bundled with the matching Avibe package.++## Verification++- Unit coverage for structured HTTP/DNS/TLS/timeout failures and redacted URLs.+- Doctor coverage for fast local checks, deep reachability checks, the legacy+ fallback, and explicit repair behavior.+- Focused CLI and Show Runtime tests plus Ruff on changed Python files.diff --git a/install.ps1 b/install.ps1index 5ab8d4380..009534c9d 100644--- a/install.ps1+++ b/install.ps1@@ -54,6 +54,23 @@ function Test-Command {return $?}+function Invoke-WebScriptWithRetry {+ param([string]$Url)++ for ($attempt = 1; $attempt -le 3; $attempt++) {+ try {+ return Invoke-RestMethod -Uri $Url -TimeoutSec 30+ } catch {+ if ($attempt -eq 3) {+ throw+ }+ $delay = [Math]::Pow(2, $attempt - 1)+ Write-Warning "Dependency request failed (attempt $attempt/3); retrying in $delay second(s)."+ Start-Sleep -Seconds $delay+ }+ }+}+function Test-Node {if (-not (Test-Command "node")) {return $false@@ -139,7 +156,7 @@ function Install-Uv {Write-Info "Installing uv (will also manage Python automatically)..."try {- irm https://astral.sh/uv/install.ps1 | iex+ Invoke-WebScriptWithRetry "https://astral.sh/uv/install.ps1" | iex# Refresh PATH$env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")diff --git a/install.sh b/install.shindex f824465b7..43b66caa2 100755--- a/install.sh+++ b/install.sh@@ -447,7 +447,12 @@ install_uv() {case "$os" inmacos|linux)- curl -LsSf https://astral.sh/uv/install.sh | sh+ local curl_retry_all_errors=""+ if curl --help all 2>/dev/null | grep -q -- '--retry-all-errors'; then+ curl_retry_all_errors="--retry-all-errors"+ fi+ curl -LsSf --retry 2 $curl_retry_all_errors --retry-delay 1 --connect-timeout 10 --max-time 120 \+ https://astral.sh/uv/install.sh | sh# Add to PATH for current sessionexport PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH";;diff --git a/tests/test_dependency_network.py b/tests/test_dependency_network.pynew file mode 100644index 000000000..58382631f--- /dev/null+++ b/tests/test_dependency_network.py@@ -0,0 +1,210 @@+from __future__ import annotations++import http.client+import socket+import ssl+import urllib.error++import pytest++from core import dependency_network+++class _Response:+ status = 200++ def __init__(self, body: bytes = b"ok", url: str = "https://example.test/final") -> None:+ self.body = body+ self.url = url++ def __enter__(self):+ return self++ def __exit__(self, *_exc) -> None:+ return None++ def read(self) -> bytes:+ return self.body++ def getcode(self) -> int:+ return self.status++ def geturl(self) -> str:+ return self.url+++def test_fetch_bytes_retries_transient_http_failure(monkeypatch) -> None:+ attempts = 0+ sleeps: list[float] = []++ def opener(_request, timeout):+ nonlocal attempts+ attempts += 1+ if attempts < 3:+ raise urllib.error.HTTPError(+ "https://example.test/archive.tgz",+ 503,+ "Unavailable",+ hdrs={},+ fp=None,+ )+ return _Response(b"archive")++ monkeypatch.setattr(dependency_network.time, "sleep", sleeps.append)++ result = dependency_network.fetch_bytes(+ "https://example.test/archive.tgz",+ timeout=5,+ opener=opener,+ )++ assert result == b"archive"+ assert attempts == 3+ assert sleeps == [1.0, 2.0]+++def test_fetch_bytes_does_not_retry_missing_asset(monkeypatch) -> None:+ attempts = 0++ def opener(_request, timeout):+ nonlocal attempts+ attempts += 1+ raise urllib.error.HTTPError(+ "https://example.test/missing.tgz",+ 404,+ "Not Found",+ hdrs={},+ fp=None,+ )++ monkeypatch.setattr(dependency_network.time, "sleep", lambda _delay: pytest.fail("404 must not retry"))++ with pytest.raises(dependency_network.DependencyNetworkError) as raised:+ dependency_network.fetch_bytes("https://example.test/missing.tgz", timeout=5, opener=opener)++ assert attempts == 1+ assert raised.value.details["http_status"] == 404+ assert raised.value.details["retryable"] is False+ assert raised.value.details["attempts"] == 1+++ ("exc", "kind", "retryable"),+ [+ (urllib.error.URLError(socket.gaierror(-2, "not found")), "dns", True),+ (urllib.error.URLError(TimeoutError("timed out")), "timeout", True),+ (urllib.error.URLError(ssl.SSLCertVerificationError(1, "bad cert")), "tls", False),+ (ConnectionResetError("reset"), "network", True),+ (http.client.IncompleteRead(b"partial", 10), "network", True),+ ],+)+def test_dependency_error_details_classifies_retryability(exc, kind, retryable) -> None:+ details = dependency_network.dependency_error_details(exc, "https://user:[email protected]/file?token=secret")++ assert details["kind"] == kind+ assert details["retryable"] is retryable+ assert details["url"] == "https://example.test/file"+++def test_probe_uses_bounded_retry_and_reports_attempts(monkeypatch) -> None:+ attempts = 0+ monkeypatch.setattr(dependency_network.time, "sleep", lambda _delay: None)++ def opener(_request, timeout):+ nonlocal attempts+ attempts += 1+ raise urllib.error.URLError(TimeoutError("timed out"))++ result = dependency_network.probe_url("https://example.test/archive.tgz", opener=opener)++ assert result["ok"] is False+ assert result["checked"] is True+ assert result["download_error"]["kind"] == "timeout"+ assert result["download_error"]["attempts"] == 2+++def test_probe_file_url_checks_local_file_without_http_opener(monkeypatch, tmp_path) -> None:+ archive = tmp_path / "runtime.tgz"+ archive.write_bytes(b"archive")+ monkeypatch.setattr(+ dependency_network.urllib.request,+ "urlopen",+ lambda *_args, **_kwargs: pytest.fail("file probe must not use urlopen"),+ )++ result = dependency_network.probe_url(archive.as_uri())++ assert result["ok"] is True+ assert result["checked"] is True+ assert result["kind"] == "local_file"+ assert result["path"] == str(archive)+++def test_probe_missing_file_url_reports_local_io_failure(monkeypatch, tmp_path) -> None:+ archive = tmp_path / "missing.tgz"+ monkeypatch.setattr(+ dependency_network.urllib.request,+ "urlopen",+ lambda *_args, **_kwargs: pytest.fail("file probe must not use urlopen"),+ )++ result = dependency_network.probe_url(archive.as_uri())++ assert result["ok"] is False+ assert result["checked"] is True+ assert result["reason"] == "dependency_file_missing"+ assert result["download_error"]["kind"] == "io"+ assert result["download_error"]["retryable"] is False+++def test_retry_after_is_capped_by_policy(monkeypatch) -> None:+ sleeps: list[float] = []+ attempts = 0++ def opener(_request, timeout):+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ raise urllib.error.HTTPError(+ "https://example.test/archive.tgz",+ 503,+ "Unavailable",+ hdrs={"Retry-After": "3600"},+ fp=None,+ )+ return _Response(b"archive")++ monkeypatch.setattr(dependency_network.time, "sleep", sleeps.append)++ result = dependency_network.fetch_bytes(+ "https://example.test/archive.tgz",+ timeout=5,+ opener=opener,+ )++ assert result == b"archive"+ assert sleeps == [4.0]+++def test_missing_local_file_is_not_retried() -> None:+ details = dependency_network.dependency_error_details(+ urllib.error.URLError(FileNotFoundError("missing")),+ "file:///tmp/missing.tgz",+ )++ assert details["kind"] == "io"+ assert details["retryable"] is False+++def test_dependency_error_message_reports_exhausted_attempts() -> None:+ message = dependency_network.dependency_error_message(+ {+ "kind": "timeout",+ "message": "Connection timed out",+ "url": "https://example.test/archive.tgz",+ "attempts": 3,+ },+ label="Runtime download",+ )++ assert message == "Runtime download failed after 3 attempts: Connection timed out (https://example.test/archive.tgz)"diff --git a/tests/test_git_runtime.py b/tests/test_git_runtime.pyindex 41f612152..32fe8dd65 100644--- a/tests/test_git_runtime.py+++ b/tests/test_git_runtime.py@@ -6,6 +6,7 @@ import jsonimport osimport statimport tarfile+import urllib.errorfrom pathlib import Pathimport pytest@@ -82,6 +83,31 @@ def test_manifest_parses_and_exposes_archive(tmp_path: Path, monkeypatch: pytest][managed_runtime.runtime_platform_tag()]["binary_sha256"]+def test_archive_download_retries_transient_network_failure(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ archive = _write_git_archive(tmp_path)+ manifest = _write_manifest(tmp_path, archive)+ payload = json.loads(manifest.read_text(encoding="utf-8"))+ payload["archives"][managed_runtime.runtime_platform_tag()]["url"] = "https://example.test/git.tar.gz"+ manifest.write_text(json.dumps(payload), encoding="utf-8")+ attempts = 0++ def opener(_request, timeout):+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ raise urllib.error.URLError(ConnectionResetError("reset"))+ return io.BytesIO(archive.read_bytes())++ monkeypatch.setattr(managed_runtime.urllib.request, "urlopen", opener)+ monkeypatch.setattr("core.dependency_network.time.sleep", lambda _delay: None)++ result = GitRuntimeManager(manifest_path=manifest).ensure()++ assert result["ok"] is True+ assert attempts == 2++def test_packaged_manifest_matches_published_four_platform_release(tmp_path: Path) -> None:manager = GitRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)@@ -223,6 +249,46 @@ def test_checksum_mismatch_installs_nothing(tmp_path: Path, monkeypatch: pytest.assert manager.resolve_git_path() is None+def test_successful_archive_fetch_clears_stale_download_error_before_checksum_failure(tmp_path: Path) -> None:+ archive = _write_git_archive(tmp_path)+ manifest = _write_manifest(tmp_path, archive, sha256="1" * 64)+ manager = GitRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest)+ manager._download_error = {"kind": "timeout", "message": "old timeout"}++ result = manager.ensure()++ assert result["reason"] == "git_archive_checksum_mismatch"+ assert "old timeout" not in result["message"]+ assert result["download_error"] is None+++def test_archive_probe_rejects_unsupported_scheme_before_network(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ archive = _write_git_archive(tmp_path)+ manifest = _write_manifest(tmp_path, archive)+ payload = json.loads(manifest.read_text(encoding="utf-8"))+ payload["archives"][managed_runtime.runtime_platform_tag()]["url"] = (+ "http://user:[email protected]/git.tar.gz?token=secret"+ )+ manifest.write_text(json.dumps(payload), encoding="utf-8")+ monkeypatch.setattr(+ managed_runtime,+ "probe_url",+ lambda *_args, **_kwargs: pytest.fail("unsupported URL must not be probed"),+ )++ result = GitRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest).probe_archive_reachability()++ assert result == {+ "ok": False,+ "checked": False,+ "reason": "git_archive_url_unsupported",+ "url": "http://example.test/git.tar.gz",+ }++def test_binary_checksum_mismatch_installs_nothing(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,diff --git a/tests/test_install_script.py b/tests/test_install_script.pyindex db92d9371..4c04284d8 100644--- a/tests/test_install_script.py+++ b/tests/test_install_script.py@@ -649,6 +649,51 @@ def test_install_script_reinstalls_when_existing_uv_is_x86_on_apple_silicon(tmp_assert uv_log.read_text(encoding="utf-8") == str(path_dir)+def test_install_script_omits_retry_all_errors_for_older_curl(tmp_path):+ home_dir = tmp_path / "home"+ home_dir.mkdir()+ path_dir = tmp_path / "path-bin"+ path_dir.mkdir()+ curl_log = tmp_path / "curl.log"+ uv_log = tmp_path / "uv-tool-bin-dir.txt"++ native_uv = home_dir / ".local" / "bin" / "uv"+ native_uv.parent.mkdir(parents=True)+ _write_fake_uv(native_uv, uv_log)+ _write_executable(+ path_dir / "curl",+ f"""\+ #!/usr/bin/env bash+ printf '%s\\n' "$*" >> "{curl_log}"+ if [ "${{1:-}}" = "--help" ]; then+ echo "curl 7.68 help"+ exit 0+ fi+ for arg in "$@"; do+ if [ "$arg" = "--retry-all-errors" ]; then+ exit 2+ fi+ done+ cat <<'EOF'+ #!/usr/bin/env sh+ exit 0+ EOF+ """,+ )++ env = os.environ.copy()+ env["HOME"] = str(home_dir)+ env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])++ install_result = _install(env, cwd=tmp_path)++ assert install_result.returncode == 0, install_result.stdout + install_result.stderr+ curl_calls = curl_log.read_text(encoding="utf-8").splitlines()+ assert curl_calls[0] == "--help all"+ assert "--retry 2" in curl_calls[1]+ assert "--retry-all-errors" not in curl_calls[1]++def test_install_script_accepts_universal_uv_with_arm64e_slice_on_apple_silicon(tmp_path):home_dir = tmp_path / "home"home_dir.mkdir()diff --git a/tests/test_local_deps.py b/tests/test_local_deps.pyindex 6dff7fb83..6c890353c 100644--- a/tests/test_local_deps.py+++ b/tests/test_local_deps.py@@ -11,7 +11,10 @@ from __future__ import annotationsimport hashlibimport ioimport json+import os+import subprocessimport tarfile+import urllib.errorfrom unittest.mock import Mockimport pytest@@ -111,7 +114,58 @@ def test_install_askill_uses_official_curl_installer(monkeypatch):assert out["ok"]assert captured["name"] == "askill"assert captured["cmd"][:2] == ["bash", "-c"]- assert "curl -fsSL https://askill.sh | sh" in captured["cmd"][2]+ assert "https://askill.sh | sh" in captured["cmd"][2]+ assert "--retry 2" in captured["cmd"][2]+ assert "--retry-all-errors" not in captured["cmd"][2]+++def test_curl_installer_command_uses_pipe_safe_retry_flags(tmp_path):+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir()+ curl_log = tmp_path / "curl.log"+ curl = bin_dir / "curl"+ curl.write_text(+ "#!/usr/bin/env bash\n"+ f"printf '%s\\n' \"$*\" >> {curl_log!s}\n"+ "printf '#!/bin/sh\\nexit 0\\n'\n",+ encoding="utf-8",+ )+ curl.chmod(0o755)+ env = os.environ.copy()+ env["PATH"] = os.pathsep.join([str(bin_dir), "/usr/bin", "/bin"])++ result = subprocess.run(+ api._curl_installer_command("https://example.test/install.sh", "sh"),+ env=env,+ capture_output=True,+ text=True,+ timeout=10,+ )++ assert result.returncode == 0, result.stderr+ calls = curl_log.read_text(encoding="utf-8").splitlines()+ assert len(calls) == 1+ assert "--retry 2" in calls[0]+ assert "--retry-all-errors" not in calls[0]+++def test_avault_download_retries_transient_network_failure(monkeypatch):+ attempts = 0++ def opener(_request, timeout):+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ raise urllib.error.URLError(ConnectionResetError("reset"))+ return _FakeHTTPResponse(b"manifest")++ monkeypatch.setattr(api.urllib.request, "urlopen", opener)+ monkeypatch.setattr("core.dependency_network.time.sleep", lambda _delay: None)++ result = api._download_avault_release_file("https://example.test/manifest.json")++ assert result == b"manifest"+ assert attempts == 2def test_askill_install_command_does_not_persist_agent_cli_path(monkeypatch):@@ -147,6 +201,17 @@ def test_install_askill_unsupported_without_curl(monkeypatch):assert "askill.sh" in out["message"]+def test_install_askill_unsupported_on_windows_even_with_tools(monkeypatch):+ monkeypatch.setattr("platform.system", lambda: "Windows")+ monkeypatch.setattr(api, "resolve_cli_path", lambda binary: f"C:/{binary}.exe")+ monkeypatch.setattr(api, "_run_install_command", lambda *a, **k: pytest.fail("should not install"))++ out = api.install_askill()++ assert out["ok"] is False+ assert "askill.sh" in out["message"]++def test_ensure_askill_idempotent_when_present(monkeypatch):monkeypatch.setattr(api, "resolve_cli_path", lambda b: "/usr/local/bin/askill")flag = {"installed": False}@@ -934,6 +999,33 @@ def test_start_dependency_install_job_rejects_unknown():assert api.start_dependency_install_job("bogus")["ok"] is False+def test_prepare_show_runtime_job_surfaces_retry_diagnostics(monkeypatch):+ import core.show_runtime as show_runtime++ manager = Mock()+ manager.prepare.return_value = {+ "ok": False,+ "reason": "runtime_archive_download_failed",+ "status": {+ "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)++ result = api._prepare_show_runtime_job()++ assert result["ok"] is False+ assert result["reason"] == "runtime_archive_download_failed"+ assert result["download_error"]["attempts"] == 3+ assert "after 3 attempts" in result["message"]++def test_start_dependency_install_job_runs_askill(monkeypatch):import time as _tdiff --git a/tests/test_tmux_runtime.py b/tests/test_tmux_runtime.pyindex 1cda1299c..91d4994fb 100644--- a/tests/test_tmux_runtime.py+++ b/tests/test_tmux_runtime.py@@ -5,6 +5,7 @@ import jsonimport statimport ioimport tarfile+import urllib.errorfrom pathlib import Pathimport pytest@@ -82,6 +83,30 @@ def test_download_verify_install_and_idempotent_reinstall(tmp_path: Path) -> Nonassert Path(second["path"]) == installed_path+def test_archive_download_retries_transient_network_failure(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ archive = _write_tmux_archive(tmp_path)+ manifest = _write_manifest(tmp_path, archive)+ payload = json.loads(manifest.read_text(encoding="utf-8"))+ payload["archives"][tmux_runtime._runtime_platform_tag()]["url"] = "https://example.test/tmux.tar.gz"+ manifest.write_text(json.dumps(payload), encoding="utf-8")+ attempts = 0++ def opener(_request, timeout):+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ raise urllib.error.URLError(ConnectionResetError("reset"))+ return io.BytesIO(archive.read_bytes())++ monkeypatch.setattr(tmux_runtime.urllib.request, "urlopen", opener)+ monkeypatch.setattr("core.dependency_network.time.sleep", lambda _delay: None)++ result = TmuxRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest).ensure()++ assert result["ok"] is True+ assert attempts == 2++def test_bad_checksum_is_rejected(tmp_path: Path) -> None:archive = _write_tmux_archive(tmp_path)manifest = _write_manifest(tmp_path, archive, sha256="0" * 64)@@ -94,6 +119,47 @@ def test_bad_checksum_is_rejected(tmp_path: Path) -> None:assert manager.resolve_binary() is None+def test_successful_archive_fetch_clears_stale_download_error_before_checksum_failure(tmp_path: Path) -> None:+ archive = _write_tmux_archive(tmp_path)+ manifest = _write_manifest(tmp_path, archive, sha256="0" * 64)+ manager = TmuxRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest)+ manager._download_error = {"kind": "timeout", "message": "old timeout"}++ result = manager.ensure()++ assert result["reason"] == "tmux_archive_checksum_mismatch"+ assert "checksum" in result["message"]+ assert "old timeout" not in result["message"]+ assert result["download_error"] is None+++def test_archive_probe_rejects_unsupported_scheme_before_network(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ archive = _write_tmux_archive(tmp_path)+ manifest = _write_manifest(tmp_path, archive)+ payload = json.loads(manifest.read_text(encoding="utf-8"))+ payload["archives"][tmux_runtime._runtime_platform_tag()]["url"] = (+ "http://user:[email protected]/tmux.tar.gz?token=secret"+ )+ manifest.write_text(json.dumps(payload), encoding="utf-8")+ monkeypatch.setattr(+ tmux_runtime,+ "probe_url",+ lambda *_args, **_kwargs: pytest.fail("unsupported URL must not be probed"),+ )++ result = TmuxRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest).probe_archive_reachability()++ assert result == {+ "ok": False,+ "checked": False,+ "reason": "tmux_archive_url_unsupported",+ "url": "http://example.test/tmux.tar.gz",+ }++def test_install_rejects_non_runnable_binary(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:archive = _write_tmux_archive(tmp_path)manifest_path = _write_manifest(tmp_path, archive)diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex db66067e0..7baa2d899 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -3,7 +3,10 @@ import hashlibimport ioimport jsonimport os+import socket+import sslimport tarfile+import urllib.errorfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import patch@@ -17,7 +20,13 @@ from core.show_pages import (ensure_show_page_dir,show_cli_event_token,)-from core.show_runtime import ShowRuntimeManager, _runtime_platform_tag, _safe_extract_tar, set_show_runtime_manager_for_tests+from core.show_runtime import (+ ShowRuntimeManager,+ _runtime_download_error,+ _runtime_platform_tag,+ _safe_extract_tar,+ set_show_runtime_manager_for_tests,+)from tests.test_ui_remote_access_auth import _mock_interface, _remote_peer, _save_configfrom tests.ui_server_test_helpers import csrf_headersfrom vibe import remote_access, ui_server@@ -159,7 +168,14 @@ def _sha256(path: Path) -> str:return digest.hexdigest()-def _write_runtime_manifest(tmp_path: Path, archive_path: Path, *, sha256: str | None = None, size: int | None = None) -> Path:+def _write_runtime_manifest(+ tmp_path: Path,+ archive_path: Path,+ *,+ sha256: str | None = None,+ size: int | None = None,+ url: str | None = None,+) -> Path:manifest_path = tmp_path / "show_runtime_manifest.json"manifest_path.parent.mkdir(parents=True, exist_ok=True)manifest_path.write_text(@@ -171,7 +187,7 @@ def _write_runtime_manifest(tmp_path: Path, archive_path: Path, *, sha256: str |"archives": {_runtime_platform_tag(): {"name": archive_path.name,- "url": archive_path.resolve().as_uri(),+ "url": url or archive_path.resolve().as_uri(),"sha256": sha256 or _sha256(archive_path),"size": archive_path.stat().st_size if size is None else size,}@@ -2650,6 +2666,158 @@ def test_show_runtime_manager_installs_from_manifest_cache(monkeypatch, tmp_pathassert status["installed_matches_manifest"] is True+def test_show_runtime_manager_preserves_structured_http_download_error(monkeypatch, tmp_path):+ archive_path = _write_runtime_archive(tmp_path)+ archive_url = "https://github.com/avibe-bot/avibe/releases/download/v-test/runtime.tgz?token=secret"+ manifest_path = _write_runtime_manifest(tmp_path, archive_path, url=archive_url)+ 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)++ def fail_download(*_args, **_kwargs):+ raise urllib.error.HTTPError(archive_url, 404, "Not Found", hdrs=None, fp=None)++ monkeypatch.setattr("core.show_runtime.urllib.request.urlopen", fail_download)++ result = manager.prepare()++ assert result["ok"] is False+ assert result["reason"] == "runtime_archive_download_failed"+ assert result["status"]["download_error"] == {+ "kind": "http",+ "message": "HTTP 404 Not Found",+ "url": "https://github.com/avibe-bot/avibe/releases/download/v-test/runtime.tgz",+ "host": "github.com",+ "exception_type": "HTTPError",+ "http_status": 404,+ "retryable": False,+ "attempts": 1,+ }+ assert "secret" not in json.dumps(result)+++def test_show_runtime_manager_retries_transient_archive_failure(monkeypatch, tmp_path):+ archive_path = _write_runtime_archive(tmp_path)+ archive_url = "https://example.test/runtime.tgz"+ manifest_path = _write_runtime_manifest(tmp_path, archive_path, url=archive_url)+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ manifest_path=manifest_path,+ )+ attempts = 0+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)++ def opener(_request, timeout):+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ raise urllib.error.URLError(ConnectionResetError("reset"))+ return io.BytesIO(archive_path.read_bytes())++ monkeypatch.setattr("core.show_runtime.urllib.request.urlopen", opener)+ monkeypatch.setattr("core.dependency_network.time.sleep", lambda _delay: None)++ result = manager.prepare()++ assert result["ok"] is True+ assert attempts == 2+++def test_show_runtime_status_refresh_does_not_erase_archive_download_error(monkeypatch, tmp_path):+ archive_path = _write_runtime_archive(tmp_path)+ archive_url = "https://github.com/avibe-bot/avibe/releases/download/v-test/runtime.tgz"+ manifest_path = _write_runtime_manifest(tmp_path, archive_path, url=archive_url)+ manifest_url = "https://example.test/show-runtime-manifest.json"+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ manifest_url=manifest_url,+ )+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)++ class ManifestResponse:+ def __enter__(self):+ return self++ def __exit__(self, *_args):+ return False++ def read(self):+ return manifest_path.read_bytes()++ def fake_urlopen(request, **_kwargs):+ url = request.full_url if hasattr(request, "full_url") else request+ if url == manifest_url:+ return ManifestResponse()+ raise urllib.error.HTTPError(archive_url, 404, "Not Found", hdrs=None, fp=None)++ monkeypatch.setattr("core.show_runtime.urllib.request.urlopen", fake_urlopen)++ result = manager.prepare()++ assert result["reason"] == "runtime_archive_download_failed"+ assert result["status"]["download_error"]["http_status"] == 404+++ ("exc", "kind"),+ [+ (urllib.error.URLError(socket.gaierror(-2, "Name or service not known")), "dns"),+ (urllib.error.URLError(ssl.SSLCertVerificationError(1, "certificate verify failed")), "tls"),+ (urllib.error.URLError(TimeoutError("timed out")), "timeout"),+ ],+)+def test_show_runtime_download_error_classifies_network_failures(exc, kind):+ error = _runtime_download_error(exc, "https://github.com/avibe-bot/avibe/releases/download/v-test/runtime.tgz")++ assert error["kind"] == kind+ assert error["host"] == "github.com"+++def test_show_runtime_archive_probe_uses_body_free_head_request(monkeypatch, tmp_path):+ archive_path = _write_runtime_archive(tmp_path)+ archive_url = "https://github.com/avibe-bot/avibe/releases/download/v-test/runtime.tgz"+ manifest_path = _write_runtime_manifest(tmp_path, archive_path, url=archive_url)+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ manifest_path=manifest_path,+ )+ requests = []++ class FakeResponse:+ status = 200++ def __enter__(self):+ return self++ def __exit__(self, *_args):+ return False++ def getcode(self):+ return self.status++ def geturl(self):+ return "https://release-assets.githubusercontent.com/runtime.tgz"++ def fake_urlopen(request, **_kwargs):+ requests.append(request)+ return FakeResponse()++ monkeypatch.setattr("core.show_runtime.urllib.request.urlopen", fake_urlopen)++ result = manager.probe_archive_reachability()++ assert result["ok"] is True+ assert result["http_status"] == 200+ assert result["final_host"] == "release-assets.githubusercontent.com"+ assert requests[0].get_method() == "HEAD"++def test_show_runtime_manager_manifest_install_dir_includes_manifest_and_archive_identity(monkeypatch, tmp_path):old_archive_path = _write_runtime_archive(tmp_path / "old", text="old runtime\n")old_manifest_path = _write_runtime_manifest(tmp_path / "old", old_archive_path)diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex 2b95f1e40..bcb4ee42b 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -1038,6 +1038,472 @@ def test_doctor_repair_dry_run_does_not_probe_runtime(monkeypatch):assert result["results"][0]["status"] == "planned"+def test_show_runtime_doctor_fast_mode_reports_local_state_without_network(monkeypatch):+ status = {+ "provider": "manifest-cache",+ "platform": "linux-x64",+ "explicit_command": None,+ "node_available": True,+ "node_version": "22.14.0",+ "node_supported": True,+ "manifest": {"runtime_version": "runtime-ref"},+ "archive": {+ "name": "vibe-show-runtime-node-linux-x64.tgz",+ "url": "https://github.com/avibe-bot/avibe/releases/download/v3.0.5/vibe-show-runtime-node-linux-x64.tgz",+ },+ "installed": False,+ }+ manager = SimpleNamespace(+ status=lambda: status,+ probe_archive_reachability=lambda: (_ for _ in ()).throw(AssertionError("fast Doctor must not probe network")),+ )+ monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda **_kwargs: manager)++ items = cli._show_runtime_doctor_items(deep=False)++ assert next(item for item in items if item.get("code") == "show_runtime.not_ready")["repair"]["target"] == "show-runtime"+ assert next(item for item in items if item.get("code") == "show_runtime.archive_probe_skipped")["status"] == "pass"+++def test_managed_dependencies_doctor_uses_one_status_contract(monkeypatch):+ offline_calls: list[bool] = []++ def status(*, offline=False):+ offline_calls.append(offline)+ return {+ "deps": [+ {"id": "askill", "required": True, "installed": False, "status": "missing"},+ {"id": "avault", "required": True, "installed": True, "status": "ready", "version": "0.1.6"},+ {"id": "show-runtime", "required": True, "installed": False, "status": "missing"},+ {"id": "tmux", "required": False, "installed": False, "status": "missing"},+ {"id": "git-runtime", "required": False, "installed": True, "status": "ready"},+ {"id": "node", "required": True, "installed": False, "status": "missing"},+ ]+ }++ monkeypatch.setattr(cli.api, "dependencies_status", status)+ monkeypatch.setattr(cli.api, "askill_auto_install_supported", lambda: True)++ items = cli._managed_dependencies_doctor_items(deep=False)++ assert offline_calls == [True]+ assert next(item for item in items if item.get("code") == "dependencies.askill.not_ready")["repair"]["target"] == "askill"+ assert next(item for item in items if item.get("code") == "dependencies.avault.ready")["status"] == "pass"+ assert next(item for item in items if item.get("code") == "dependencies.git-runtime.ready")["status"] == "pass"+ assert next(item for item in items if item.get("code") == "dependencies.tmux.not_ready")["status"] == "warn"+ assert next(item for item in items if item.get("code") == "dependencies.node.not_ready")["status"] == "fail"+++def test_managed_dependencies_doctor_suppresses_unsupported_askill_repair(monkeypatch):+ monkeypatch.setattr(+ cli.api,+ "dependencies_status",+ lambda **_kwargs: {+ "deps": [+ {"id": "askill", "required": True, "installed": False, "status": "missing"},+ {"id": "git-runtime", "required": False, "installed": True, "status": "ready"},+ ]+ },+ )+ monkeypatch.setattr(cli.api, "askill_auto_install_supported", lambda: False)++ items = cli._managed_dependencies_doctor_items(deep=False)++ missing = next(item for item in items if item.get("code") == "dependencies.askill.not_ready")+ assert "repair" not in missing+ assert "askill.sh" in missing["action"]+++def test_managed_dependencies_doctor_does_not_offer_unsupported_platform_repair(monkeypatch):+ monkeypatch.setattr(+ cli.api,+ "dependencies_status",+ lambda **_kwargs: {+ "deps": [+ {+ "id": "tmux",+ "required": False,+ "installed": False,+ "status": "missing",+ "reason": "tmux_platform_unsupported",+ },+ {"id": "git-runtime", "required": False, "installed": True, "status": "ready"},+ ]+ },+ )++ items = cli._managed_dependencies_doctor_items(deep=False)++ unsupported = next(+ item for item in items if item.get("code") == "dependencies.tmux.platform_unsupported"+ )+ assert unsupported["status"] == "warn"+ assert "repair" not in unsupported+ assert not any(item.get("code") == "dependencies.tmux.not_ready" for item in items)+++def test_managed_dependencies_doctor_accepts_usable_system_git(monkeypatch):+ monkeypatch.setattr(cli.api, "dependencies_status", lambda **_kwargs: {"deps": []})+ monkeypatch.setattr(+ "core.git_runtime.git_runtime_status",+ lambda: {+ "resolution": "system",+ "path": "/usr/bin/git",+ "version": None,+ "managed": {+ "installed": False,+ "status": "missing",+ "reason": "git_platform_unsupported",+ },+ },+ )++ items = cli._managed_dependencies_doctor_items(deep=False)++ system_git = next(+ item for item in items if item.get("code") == "dependencies.git-runtime.system_ready"+ )+ assert system_git["status"] == "pass"+ assert not any(item.get("code") == "dependencies.git-runtime.not_ready" for item in items)+++def test_managed_dependencies_doctor_does_not_offer_unsupported_git_runtime_repair(monkeypatch):+ monkeypatch.setattr(cli.api, "dependencies_status", lambda **_kwargs: {"deps": []})+ monkeypatch.setattr(+ "core.git_runtime.git_runtime_status",+ lambda: {+ "resolution": "none",+ "path": None,+ "version": None,+ "managed": {+ "installed": False,+ "status": "missing",+ "reason": "git_platform_unsupported",+ },+ },+ )++ items = cli._managed_dependencies_doctor_items(deep=False)++ unsupported = next(+ item+ for item in items+ if item.get("code") == "dependencies.git-runtime.platform_unsupported"+ )+ assert unsupported["status"] == "warn"+ assert "repair" not in unsupported+++def test_managed_dependencies_doctor_rejects_unsupported_archive_url_without_repair(monkeypatch):+ monkeypatch.setattr(+ cli.api,+ "dependencies_status",+ lambda **_kwargs: {+ "deps": [+ {"id": "git-runtime", "required": False, "installed": False, "status": "missing"},+ ]+ },+ )+ manager = SimpleNamespace(+ probe_archive_reachability=lambda: {+ "ok": False,+ "checked": False,+ "reason": "git_archive_url_unsupported",+ "url": "http://example.test/git.tar.gz",+ }+ )+ monkeypatch.setattr("core.git_runtime.GitRuntimeManager", lambda **_kwargs: manager)++ items = cli._managed_dependencies_doctor_items(deep=True)++ unsupported = next(+ item+ for item in items+ if item.get("code") == "dependencies.git-runtime.archive_url_unsupported"+ )+ assert unsupported["status"] == "warn"+ assert "repair" not in unsupported+ assert not any(item.get("code") == "dependencies.git-runtime.not_ready" for item in items)+++def test_managed_dependencies_doctor_deep_reports_retry_exhaustion(monkeypatch):+ monkeypatch.setattr(+ cli.api,+ "dependencies_status",+ lambda **_kwargs: {+ "deps": [+ {"id": "askill", "required": True, "installed": False, "status": "missing"},+ {"id": "git-runtime", "required": False, "installed": True, "status": "ready"},+ ]+ },+ )+ monkeypatch.setattr(+ "core.dependency_network.probe_url",+ lambda *_args, **_kwargs: {+ "ok": False,+ "checked": True,+ "download_error": {+ "kind": "timeout",+ "url": "https://askill.sh",+ "attempts": 2,+ "retryable": True,+ },+ },+ )++ items = cli._managed_dependencies_doctor_items(deep=True)++ failure = next(item for item in items if item.get("code") == "dependencies.askill.download_timeout_failed")+ assert "after 2 attempts" in failure["message"]+++def test_repair_managed_dependency_preserves_structured_download_error():+ error = {"kind": "dns", "attempts": 3, "retryable": True}++ result = cli._repair_managed_dependency(+ "avault",+ lambda force: {+ "ok": False,+ "reason": "avault_download_failed",+ "message": "download failed",+ "download_error": error,+ },+ )++ assert result["status"] == "failed"+ assert result["download_error"] == error+++def test_show_runtime_doctor_deep_mode_distinguishes_missing_release_asset(monkeypatch):+ archive_url = (+ "https://github.com/avibe-bot/avibe/releases/download/"+ "v3.0.5/vibe-show-runtime-node-linux-x64.tgz"+ )+ status = {+ "provider": "manifest-cache",+ "platform": "linux-x64",+ "explicit_command": None,+ "node_available": True,+ "node_version": "22.14.0",+ "node_supported": True,+ "manifest": {"runtime_version": "runtime-ref"},+ "archive": {"name": "vibe-show-runtime-node-linux-x64.tgz", "url": archive_url},+ "installed": False,+ }+ manager = SimpleNamespace(+ status=lambda: status,+ probe_archive_reachability=lambda: {+ "ok": False,+ "checked": True,+ "reason": "runtime_archive_download_failed",+ "download_error": {+ "kind": "http",+ "message": "HTTP 404 Not Found",+ "url": archive_url,+ "host": "github.com",+ "http_status": 404,+ },+ },+ )+ monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda **_kwargs: manager)++ items = cli._show_runtime_doctor_items(deep=True)++ failure = next(item for item in items if item.get("code") == "show_runtime.archive_http_404")+ assert failure["status"] == "fail"+ assert "proxy or security gateway" in failure["action"]+++def test_show_runtime_doctor_reports_unchecked_manifest_download_failure(monkeypatch):+ archive_url = "https://example.test/runtime.tgz"+ status = {+ "provider": "manifest-cache",+ "platform": "linux-x64",+ "explicit_command": None,+ "node_available": True,+ "node_version": "22.14.0",+ "node_supported": True,+ "manifest": {"runtime_version": "runtime-ref"},+ "archive": {"name": "runtime.tgz", "url": archive_url},+ "installed": False,+ }+ manager = SimpleNamespace(+ status=lambda: status,+ probe_archive_reachability=lambda: {+ "ok": False,+ "checked": False,+ "reason": "runtime_manifest_download_failed",+ "download_error": {+ "kind": "timeout",+ "message": "Connection timed out",+ "url": "https://example.test/manifest.json",+ "attempts": 2,+ },+ },+ )+ monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda **_kwargs: manager)++ items = cli._show_runtime_doctor_items(deep=True)++ failure = next(item for item in items if item.get("code") == "show_runtime.manifest_timeout_failed")+ assert failure["status"] == "fail"+ assert "after 2 attempts" in failure["message"]+ assert not any(item.get("code") == "show_runtime.archive_probe_unsupported" for item in items)+++def test_show_runtime_doctor_reports_unsupported_archive_url(monkeypatch):+ archive_url = "http://example.test/runtime.tgz"+ status = {+ "provider": "manifest-cache",+ "platform": "linux-x64",+ "explicit_command": None,+ "node_available": True,+ "node_version": "22.14.0",+ "node_supported": True,+ "manifest": {"runtime_version": "runtime-ref"},+ "archive": {"name": "runtime.tgz", "url": archive_url},+ "installed": False,+ }+ manager = SimpleNamespace(+ status=lambda: status,+ probe_archive_reachability=lambda: {+ "ok": False,+ "checked": False,+ "reason": "runtime_archive_url_unsupported",+ "url": archive_url,+ },+ )+ monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda **_kwargs: manager)++ items = cli._show_runtime_doctor_items(deep=True)++ failure = next(item for item in items if item.get("code") == "show_runtime.archive_url_unsupported")+ assert failure["status"] == "fail"+ assert "HTTPS or file URL" in failure["action"]+ not_ready = next(item for item in items if item.get("code") == "show_runtime.not_ready")+ assert "repair" not in not_ready+ assert "doctor repair" not in not_ready["action"]+++def test_show_runtime_doctor_only_treats_explicit_head_failure_as_probe_unsupported(monkeypatch):+ archive_url = "https://example.test/runtime.tgz"+ status = {+ "provider": "manifest-cache",+ "platform": "linux-x64",+ "explicit_command": None,+ "node_available": True,+ "node_version": "22.14.0",+ "node_supported": True,+ "manifest": {"runtime_version": "runtime-ref"},+ "archive": {"name": "runtime.tgz", "url": archive_url},+ "installed": False,+ }+ manager = SimpleNamespace(+ status=lambda: status,+ probe_archive_reachability=lambda: {+ "ok": False,+ "checked": False,+ "reason": "runtime_archive_probe_unsupported",+ "download_error": {+ "kind": "http",+ "message": "HTTP 405 Method Not Allowed",+ "url": archive_url,+ "http_status": 405,+ },+ },+ )+ monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda **_kwargs: manager)++ items = cli._show_runtime_doctor_items(deep=True)++ warning = next(item for item in items if item.get("code") == "show_runtime.archive_probe_unsupported")+ assert warning["status"] == "warn"+ assert not any(item.get("code") == "show_runtime.archive_http_error" for item in items)+++def test_show_runtime_doctor_identifies_legacy_upstream_fallback(monkeypatch):+ status = {+ "provider": "archive",+ "platform": "darwin-arm64",+ "explicit_command": None,+ "node_available": True,+ "node_version": "22.14.0",+ "node_supported": True,+ "manifest": None,+ "archive": {+ "name": "vibe-show-runtime-node-darwin-arm64.tgz",+ "url": "https://github.com/avibe-bot/vibe-show-runtime/releases/latest/download/"+ "vibe-show-runtime-node-darwin-arm64.tgz",+ },+ "installed": False,+ }+ manager = SimpleNamespace(status=lambda: status)+ monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda **_kwargs: manager)++ items = cli._show_runtime_doctor_items(deep=False)++ failure = next(item for item in items if item.get("code") == "show_runtime.legacy_archive_provider")+ assert failure["status"] == "fail"+ assert "does not publish release assets" in failure["action"]+ 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},+ "installed": False,+ },+ 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: 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):+ manager = SimpleNamespace(+ status=lambda: {+ "provider": "manifest-cache",+ "platform": "linux-x64",+ "archive": {"url": "https://github.com/avibe-bot/avibe/releases/download/v-test/runtime.tgz"},+ "installed": False,+ },+ prepare=lambda force=False: {+ "ok": True,+ "provider": "manifest-cache",+ "platform": "linux-x64",+ "status": {"install_dir": str(tmp_path / "runtime")},+ },+ )+ monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda: manager)++ result = cli._repair_show_runtime()++ assert result["status"] == "repaired"+ assert result["install_dir"] == str(tmp_path / "runtime")++def test_doctor_repair_refreshes_diagnostics_after_repair(monkeypatch):paths.ensure_data_dirs()restart_path = runtime.get_restart_status_path()@@ -1055,10 +1521,61 @@ def test_doctor_repair_refreshes_diagnostics_after_repair(monkeypatch):assert result["ok"] is Trueassert result["results"][0]["status"] == "repaired"assert refreshed == [True]- assert doctor_calls == [True]+ assert doctor_calls == [False]assert result["doctor"] == {"ok": True, "groups": []}+def test_bare_doctor_repair_keeps_post_repair_refresh_local(monkeypatch):+ handlers = {+ "_repair_home_migration": "repaired",+ "_repair_stale_install_runtime": "skipped",+ "_repair_duplicate_service_processes": "skipped",+ "_repair_stale_restart_state": "skipped",+ }+ for name, status in handlers.items():+ target = name.removeprefix("_repair_").replace("_", "-")+ monkeypatch.setattr(+ cli,+ name,+ lambda *, dry_run=False, target=target, status=status: {+ "target": target,+ "status": status,+ "message": status,+ },+ )+ doctor_calls = []+ monkeypatch.setattr(cli, "_doctor", lambda *, deep=False: doctor_calls.append(deep) or {"ok": True})++ result = cli._repair_doctor_targets([], dry_run=False)++ assert result["ok"] is True+ assert doctor_calls == [False]+++def test_dependency_or_deep_repair_requests_deep_post_repair_refresh(monkeypatch):+ monkeypatch.setattr(+ cli,+ "_repair_askill",+ lambda *, dry_run=False: {"target": "askill", "status": "repaired", "message": "done"},+ )+ monkeypatch.setattr(+ cli,+ "_repair_stale_restart_state",+ lambda *, dry_run=False: {+ "target": "stale-restart-state",+ "status": "repaired",+ "message": "done",+ },+ )+ doctor_calls = []+ monkeypatch.setattr(cli, "_doctor", lambda *, deep=False: doctor_calls.append(deep) or {"ok": True})++ cli._repair_doctor_targets(["askill"], dry_run=False)+ cli._repair_doctor_targets(["stale-restart-state"], dry_run=False, deep=True)++ assert doctor_calls == [True, True]++def test_restart_parser_accepts_delay_seconds():parser = cli.build_parser()args = parser.parse_args(["restart", "--delay-seconds", "60"])@@ -1077,6 +1594,22 @@ def test_doctor_parser_accepts_repair_target_and_dry_run():assert args.dry_run is True+def test_doctor_parser_accepts_show_runtime_repair_target():+ parser = cli.build_parser()+ args = parser.parse_args(["doctor", "repair", "show-runtime", "--yes"])++ assert args.doctor_repair_targets == ["show-runtime"]+++def test_doctor_parser_accepts_managed_dependency_repair_targets():+ parser = cli.build_parser()++ for target in ("askill", "avault", "git-runtime", "tmux"):+ args = parser.parse_args(["doctor", "repair", target, "--yes"])+ assert args.doctor_repair_targets == [target]+ assert args.yes is True++def test_doctor_parser_accepts_fast_and_deep_modes():parser = cli.build_parser()diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 39f0f843b..5aec25c9d 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -1360,6 +1360,18 @@ export type InstallResult = {path?: string | null;job_id?: string;status?: 'running' | 'succeeded' | 'failed';+ reason?: string | null;+ download_error?: DependencyDownloadError | null;+};++export type DependencyDownloadError = {+ kind: 'http' | 'dns' | 'tls' | 'timeout' | 'network' | 'permission' | 'disk' | 'io' | 'unknown';+ message: string;+ url?: string | null;+ host?: string | null;+ http_status?: number;+ retryable: boolean;+ attempts: number;};export type DependencyItem = {@@ -1369,6 +1381,8 @@ export type DependencyItem = {installed: boolean;version: string | null;status: 'ready' | 'missing' | 'upgrade_required';+ reason?: string | null;+ download_error?: DependencyDownloadError | null;};export type DependenciesResult = { ok: boolean; deps: DependencyItem[] };diff --git a/vibe/api.py b/vibe/api.pyindex de7973257..f597630bf 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -73,10 +73,13 @@ from core.vibe_agents import (validate_agent_backend,)from core.process_isolation import isolated_subprocess_kwargs, signal_process_tree, KILL_SIGNAL+from core.dependency_network import DependencyNetworkError, dependency_error_message, fetch_byteslogger = logging.getLogger(__name__)+_CURL_INSTALL_RETRY_FLAGS = "--retry 2 --retry-delay 1 --connect-timeout 10 --max-time 120"+# Cache per cwd: { cwd: { "data": ..., "updated_at": ... } }_OPENCODE_OPTIONS_CACHE: dict[str, dict] = {}_OPENCODE_OPTIONS_TTL_SECONDS = 30.0@@ -5841,7 +5844,7 @@ def install_agent(name: str) -> dict:if error:return {"ok": False, "message": error, "output": None}# Use pipefail to ensure curl failures are detected- cmd = ["bash", "-c", "set -euo pipefail; curl -fsSL https://opencode.ai/install | bash"]+ cmd = _curl_installer_command("https://opencode.ai/install", "bash")elif name == "claude":# Claude Code: platform-specific installerif system == "windows":@@ -5856,7 +5859,7 @@ def install_agent(name: str) -> dict:error = _check_binary(binary)if error:return {"ok": False, "message": error, "output": None}- cmd = ["bash", "-c", "set -euo pipefail; curl -fsSL https://claude.ai/install.sh | bash"]+ cmd = _curl_installer_command("https://claude.ai/install.sh", "bash")elif name == "codex":# Fresh installs use npm because it is the documented cross-platform# package source that does not require OS package-manager privileges.@@ -5876,6 +5879,15 @@ def install_agent(name: str) -> dict:return _run_install_command(name, cmd, _truncate_output, mode="install", env=command_env)+def _curl_installer_command(url: str, consumer: str) -> list[str]:+ """Build the shared bounded-retry command for trusted script installers."""+ return [+ "bash",+ "-c",+ f"set -euo pipefail; curl -fsSL {_CURL_INSTALL_RETRY_FLAGS} {url} | {consumer}",+ ]++def _run_install_command(name: str,cmd: list[str],@@ -6007,6 +6019,10 @@ AVAULT_VERSION = "0.1.6"_AVAULT_RELEASE_BASE_URL = f"https://github.com/avibe-bot/avault/releases/download/v{AVAULT_VERSION}/"+def avault_manifest_url() -> str:+ return urllib.parse.urljoin(_AVAULT_RELEASE_BASE_URL, "manifest.json")++def _truncate_install_output(output: str, limit: int = 8192) -> str:return output if len(output) <= limit else "...(truncated)\n" + output[-limit:]@@ -6072,6 +6088,17 @@ def _reset_avault_agent_after_binary_change(*, reason: str) -> None:logger.warning("%s: failed to quarantine resident avault agent socket after binary change", reason, exc_info=True)+def askill_auto_install_supported() -> bool:+ """Return whether this host can run askill's official installer."""+ import platform++ return (+ platform.system().lower() != "windows"+ and resolve_cli_path("curl") is not None+ and resolve_cli_path("bash") is not None+ )++def install_askill() -> dict:"""Install (or refresh) the askill CLI — a required local dependency for Skills.@@ -6080,11 +6107,8 @@ def install_askill() -> dict:V2Config cli_path bookkeeping is limited to real Agent backends, so it issafe for a standalone local dependency."""- import platform-- system = platform.system().lower()- if system != "windows" and resolve_cli_path("curl") and resolve_cli_path("bash"):- cmd = ["bash", "-c", "set -euo pipefail; curl -fsSL https://askill.sh | sh"]+ if askill_auto_install_supported():+ cmd = _curl_installer_command("https://askill.sh", "sh")return _run_install_command("askill", cmd, _truncate_install_output, mode="install")# No npm fallback: askill is distributed via the askill.sh installer, not a# public npm package, so a curl/bash-less host (e.g. Windows) must install@@ -6236,8 +6260,11 @@ def _download_avault_release_file(url: str) -> bytes:"User-Agent": "avibe/avault-installer",},)- with urllib.request.urlopen(request, timeout=30) as response: # noqa: S310 - public GitHub release asset- return response.read()+ return fetch_bytes(+ request,+ timeout=30,+ opener=urllib.request.urlopen,+ )def _extract_avault_binary(archive_bytes: bytes, output_path: Path, member_name: str = "avault") -> None:@@ -6309,7 +6336,7 @@ def install_avault(force: bool = False) -> dict:}try:- manifest_url = urllib.parse.urljoin(_AVAULT_RELEASE_BASE_URL, "manifest.json")+ manifest_url = avault_manifest_url()manifest = json.loads(_download_avault_release_file(manifest_url).decode("utf-8"))entry = manifest["versions"][AVAULT_VERSION][target]asset = entry["asset"]@@ -6354,12 +6381,17 @@ def install_avault(force: bool = False) -> dict:}except Exception as exc: # noqa: BLE001logger.warning("avault install failed: %s", exc, exc_info=True)- return {+ result = {"ok": False,"message": backend_t("dependencies.avault.installFailed", error=str(exc)),"output": None,"path": None,}+ if isinstance(exc, DependencyNetworkError):+ result["reason"] = "avault_download_failed"+ result["download_error"] = dict(exc.details)+ result["message"] = dependency_error_message(exc.details, label="avault download")+ return resultdef ensure_avault_installed(force: bool = False) -> dict:@@ -7168,7 +7200,7 @@ _DEFAULT_STARTUP_SHOW_PAGE_PREWARM_LIMIT = 3_MAX_STARTUP_SHOW_PAGE_PREWARM_LIMIT = 10-def dependencies_status() -> dict:+def dependencies_status(*, offline: bool = False) -> dict:"""Status of the required local runtime dependencies for the Dependenciessettings page: askill, the Show Page runtime, and the shared Node.jsprerequisite. (Agent backend CLIs are managed on the Backends tab.)@@ -7207,9 +7239,10 @@ def dependencies_status() -> dict:)try:- from core.show_runtime import get_show_runtime_manager+ from core.show_runtime import ShowRuntimeManager, get_show_runtime_manager- srt = get_show_runtime_manager().status()+ srt_manager = ShowRuntimeManager(offline=True) if offline else get_show_runtime_manager()+ srt = srt_manager.status()except Exception as exc: # noqa: BLE001srt = {"installed": False, "node_available": None, "node_version": None, "reason": str(exc)}manifest = srt.get("manifest") if isinstance(srt.get("manifest"), dict) else {}@@ -7222,13 +7255,15 @@ def dependencies_status() -> dict:"installed": srt_installed,"version": manifest.get("runtime_version"),"status": "ready" if srt_installed else "missing",+ "reason": srt.get("reason"),+ "download_error": srt.get("download_error"),})try:- from core.tmux_runtime import tmux_status+ from core.tmux_runtime import TmuxRuntimeManager, tmux_status- tmux = tmux_status()+ tmux = TmuxRuntimeManager(offline=True).status() if offline else tmux_status()except Exception as exc: # noqa: BLE001tmux = {"installed": False, "version": None, "status": "missing", "reason": str(exc)}deps.append(@@ -7239,6 +7274,8 @@ def dependencies_status() -> dict:"installed": bool(tmux.get("installed")),"version": tmux.get("version"),"status": "ready" if tmux.get("installed") else "missing",+ "reason": tmux.get("reason"),+ "download_error": tmux.get("download_error"),})@@ -7265,11 +7302,19 @@ def _prepare_show_runtime_job() -> dict:payload = get_show_runtime_manager().prepare(force=True)ok = bool(payload.get("ok"))- return {+ result = {"ok": ok,"message": "Show Runtime ready." if ok else (payload.get("reason") or "Show Runtime prepare failed"),"output": None,}+ 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+ result["reason"] = payload.get("reason")+ result["download_error"] = download_error+ if download_error:+ result["message"] = dependency_error_message(download_error, label="Show Runtime download")+ return resultexcept Exception as exc: # noqa: BLE001return {"ok": False, "message": str(exc), "output": None}@@ -7280,10 +7325,19 @@ def _prepare_tmux_job() -> dict:payload = ensure_tmux_installed(force=True)ok = bool(payload.get("ok"))+ download_error = payload.get("download_error") if isinstance(payload.get("download_error"), dict) else Nonereturn {**payload,"ok": ok,- "message": "tmux runtime ready." if ok else (payload.get("message") or payload.get("reason") or "tmux install failed"),+ "message": (+ "tmux runtime ready."+ if ok+ else (+ dependency_error_message(download_error, label="tmux download")+ if download_error+ else (payload.get("message") or payload.get("reason") or "tmux install failed")+ )+ ),"output": payload.get("output"),}except Exception as exc: # noqa: BLE001diff --git a/vibe/cli.py b/vibe/cli.pyindex 3da46d720..3eec0daf1 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -19,6 +19,7 @@ import tempfileimport threadingimport timeimport urllib.error+import urllib.parseimport urllib.requestfrom datetime import datetime, timedelta, timezonefrom pathlib import Path@@ -80,12 +81,24 @@ DOCTOR_REPAIR_TARGETS = ("stale-install-runtime","duplicate-service-processes","stale-restart-state",+ "askill",+ "avault",+ "git-runtime",+ "show-runtime",+ "tmux",)+DOCTOR_DEFAULT_REPAIR_TARGETS = DOCTOR_REPAIR_TARGETS[:4]+DOCTOR_DEPENDENCY_REPAIR_TARGETS = frozenset(DOCTOR_REPAIR_TARGETS[4:])DOCTOR_REPAIR_DRY_RUN_MESSAGES = {"home-migration": "Would migrate ~/.vibe_remote to ~/.avibe when safe, or recreate the legacy compatibility symlink.","stale-install-runtime": "Would stop a running legacy vibe-remote service and start the current Avibe service.","duplicate-service-processes": "Would stop extra Avibe service processes outside the service lock.","stale-restart-state": "Would remove stale restart metadata and refresh runtime status.",+ "askill": "Would install or refresh askill with the official installer.",+ "avault": "Would install or refresh the manifest-pinned avault release.",+ "git-runtime": "Would install or refresh the manifest-pinned Git Runtime.",+ "show-runtime": "Would prepare the manifest-pinned Show Runtime archive when it is missing or invalid.",+ "tmux": "Would install or refresh the manifest-pinned tmux runtime.",}DEFAULT_VAULT_APPROVAL_WAIT_SECONDS = 9 * 60@@ -7934,6 +7947,481 @@ def cmd_watch_remove(watch_id: str):return 0+def _add_dependency_download_failure(+ items: list[dict],+ error: dict | None,+ *,+ label: str,+ code_prefix: str,+ repair_target: str | None,+ retry_action: str | None = None,+ failure_status: str = "fail",+) -> None:+ error = error or {}+ kind = str(error.get("kind") or "unknown")+ url = str(error.get("url") or "the selected dependency URL")+ attempts = int(error.get("attempts") or 1)+ attempt_text = f" after {attempts} attempts" if attempts > 1 else ""+ retry_action = retry_action or f"Run `vibe doctor repair {repair_target}`."+ if kind == "http" and error.get("http_status") == 404:+ _add_doctor_item(+ items,+ failure_status,+ f"{label} release asset is missing (HTTP 404): {url}",+ "Verify the exact URL from another network. If the release asset is absent, upgrade or reinstall Avibe; "+ "if it works elsewhere, fix the proxy or security gateway.",+ code=f"{code_prefix}_http_404",+ )+ elif kind == "http":+ status = error.get("http_status") or "error"+ _add_doctor_item(+ items,+ failure_status,+ f"{label} request returned HTTP {status}{attempt_text}: {url}",+ f"Check the exact release asset and any proxy response. {retry_action}",+ code=f"{code_prefix}_http_error",+ )+ elif kind == "dns":+ _add_doctor_item(+ items,+ failure_status,+ f"{label} host DNS lookup failed{attempt_text}: {error.get('host') or url}",+ f"Fix DNS access to the dependency host. {retry_action}",+ code=f"{code_prefix}_dns_failed",+ )+ elif kind == "tls":+ _add_doctor_item(+ items,+ failure_status,+ f"{label} TLS verification failed: {url}",+ "Fix the host CA or HTTPS inspection proxy for the Avibe service, then retry the repair.",+ code=f"{code_prefix}_tls_failed",+ )+ elif kind in {"timeout", "network"}:+ _add_doctor_item(+ items,+ failure_status,+ f"{label} network request failed{attempt_text}: {url}",+ f"Allow HTTPS access to the dependency host. {retry_action}",+ code=f"{code_prefix}_{kind}_failed",+ )+ elif kind in {"permission", "disk", "io"}:+ _add_doctor_item(+ items,+ failure_status,+ f"{label} could not be stored: {error.get('message') or kind}",+ "Fix the runtime cache permissions or available disk space, then retry the repair.",+ code=f"{code_prefix}_{kind}_failed",+ )+ else:+ _add_doctor_item(+ items,+ failure_status,+ f"{label} is unreachable: {error.get('message') or url}",+ "Inspect the Avibe log for the matching download exception, then retry the repair.",+ code=f"{code_prefix}_unreachable",+ )+++def _managed_dependencies_doctor_items(*, deep: bool = False) -> list[dict]:+ from core.dependency_network import probe_url++ labels = {+ "askill": "askill",+ "avault": "avault",+ "tmux": "tmux runtime",+ "git-runtime": "Git Runtime",+ "node": "Node.js",+ }+ repair_targets = {+ "askill": "askill",+ "avault": "avault",+ "git-runtime": "git-runtime",+ "tmux": "tmux",+ }+ items: list[dict] = []+ try:+ dependencies = list(api.dependencies_status(offline=True).get("deps") or [])+ from core.git_runtime import git_runtime_status++ if not any(dependency.get("id") == "git-runtime" for dependency in dependencies):+ git_status = git_runtime_status()+ managed_git = git_status.get("managed") or {}+ git_ready = git_status.get("resolution") in {"vendored", "system"}+ dependencies.append(+ {+ "id": "git-runtime",+ "required": False,+ "installed": git_ready,+ "status": "ready" if git_ready else "missing",+ "version": git_status.get("version") or managed_git.get("version"),+ "source": git_status.get("resolution"),+ "reason": managed_git.get("reason"),+ "download_error": managed_git.get("download_error"),+ }+ )+ except Exception as exc: # noqa: BLE001+ _add_doctor_item(+ items,+ "fail",+ f"Managed dependency status could not be inspected: {exc}",+ "Inspect the Avibe log and rerun Doctor.",+ code="dependencies.status_failed",+ )+ return items++ for dependency in dependencies:+ dependency_id = str(dependency.get("id") or "")+ if dependency_id == "show-runtime" or dependency_id not in labels:+ continue+ label = labels[dependency_id]+ status = str(dependency.get("status") or "missing")+ ready = bool(dependency.get("installed")) and status == "ready"+ version = dependency.get("version")+ if ready:+ suffix = f" {version}" if version else ""+ if dependency_id == "git-runtime" and dependency.get("source") == "system":+ _add_doctor_item(+ items,+ "pass",+ "Git is ready via the system runtime",+ code="dependencies.git-runtime.system_ready",+ )+ else:+ _add_doctor_item(+ items,+ "pass",+ f"{label}{suffix} is ready",+ code=f"dependencies.{dependency_id}.ready",+ )+ continue++ required = bool(dependency.get("required"))+ severity = "fail" if required else "warn"+ if dependency_id == "node":+ _add_doctor_item(+ items,+ severity,+ f"{label} is missing or unsupported",+ "Install a supported Node.js release (^20.19.0 or >=22.12.0).",+ code="dependencies.node.not_ready",+ )+ continue++ dependency_reason = str(dependency.get("reason") or "")+ if dependency_reason.endswith("_platform_unsupported"):+ _add_doctor_item(+ items,+ severity,+ f"{label} is not published for this platform",+ "Use a system dependency where supported, or run Avibe on a platform with a published runtime.",+ code=f"dependencies.{dependency_id}.platform_unsupported",+ )+ continue++ repair_target: str | None = repair_targets[dependency_id]+ if dependency_id == "askill" and not api.askill_auto_install_supported():+ repair_target = None+ retry_action = (+ f"Run `vibe doctor repair {repair_target}`."+ if repair_target+ else "Install askill manually from https://askill.sh."+ )+ probe = None+ if deep and dependency_id == "tmux":+ from core.tmux_runtime import TmuxRuntimeManager++ probe = TmuxRuntimeManager().probe_archive_reachability()+ elif deep and dependency_id == "git-runtime":+ from core.git_runtime import GitRuntimeManager++ probe = GitRuntimeManager().probe_archive_reachability()++ probe_reason = str((probe or {}).get("reason") or "")+ if probe_reason.endswith("_archive_url_unsupported"):+ _add_doctor_item(+ items,+ severity,+ f"{label} archive URL uses an unsupported scheme: {probe.get('url') or 'unknown'}",+ "Configure the dependency manifest with an HTTPS or file URL.",+ code=f"dependencies.{dependency_id}.archive_url_unsupported",+ )+ continue++ _add_doctor_item(+ items,+ severity,+ f"{label} is not ready ({status})",+ retry_action,+ code=f"dependencies.{dependency_id}.not_ready",+ repair_target=repair_target,+ repair_risk="low",+ )+ if not deep:+ continue++ if dependency_id == "askill":+ probe = probe_url("https://askill.sh", user_agent="avibe-askill-doctor")+ elif dependency_id == "avault":+ probe = probe_url(+ api.avault_manifest_url(),+ user_agent="avibe-avault-doctor",+ )+ elif dependency_id == "tmux" and probe is None:+ from core.tmux_runtime import TmuxRuntimeManager++ probe = TmuxRuntimeManager().probe_archive_reachability()+ elif dependency_id == "git-runtime" and probe is None:+ from core.git_runtime import GitRuntimeManager++ probe = GitRuntimeManager().probe_archive_reachability()++ if probe.get("ok"):+ _add_doctor_item(+ items,+ "pass",+ f"{label} download endpoint is reachable: {probe.get('url')}",+ code=f"dependencies.{dependency_id}.reachable",+ )+ elif not probe.get("checked") and probe.get("reason") == "dependency_probe_unsupported":+ _add_doctor_item(+ items,+ "warn",+ f"{label} server does not support a body-free probe",+ retry_action,+ code=f"dependencies.{dependency_id}.probe_unsupported",+ )+ elif probe.get("download_error"):+ _add_dependency_download_failure(+ items,+ probe.get("download_error"),+ label=label,+ code_prefix=f"dependencies.{dependency_id}.download",+ repair_target=repair_target,+ retry_action=retry_action,+ failure_status=severity,+ )+ elif not probe.get("checked"):+ _add_doctor_item(+ items,+ severity,+ f"{label} archive could not be resolved ({probe.get('reason') or 'unknown'})",+ "Inspect the dependency manifest and platform mapping before retrying.",+ code=f"dependencies.{dependency_id}.probe_unavailable",+ )+ return items+++def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:+ from core.show_runtime import ShowRuntimeManager++ items: list[dict] = []+ try:+ manager = ShowRuntimeManager(offline=True if not deep else None)+ status = manager.status()+ except Exception as exc: # noqa: BLE001+ _add_doctor_item(+ items,+ "fail",+ f"Show Runtime status could not be inspected: {exc}",+ "Inspect the Avibe log and reinstall the current Avibe release if package data is missing.",+ code="show_runtime.status_failed",+ )+ return items++ provider = str(status.get("provider") or "unknown")+ explicit_command = status.get("explicit_command")+ if explicit_command:+ if status.get("installed"):+ _add_doctor_item(items, "pass", f"Show Runtime explicit command is available: {explicit_command}")+ else:+ _add_doctor_item(+ items,+ "fail",+ f"Show Runtime explicit command is missing: {explicit_command}",+ "Fix or remove VIBE_SHOW_RUNTIME_BIN, then rerun Doctor.",+ code="show_runtime.explicit_command_missing",+ )+ return items++ node_available = bool(status.get("node_available"))+ node_supported = status.get("node_supported") is not False++ manifest = status.get("manifest") if isinstance(status.get("manifest"), dict) else None+ archive = status.get("archive") if isinstance(status.get("archive"), dict) else None+ archive_url = str((archive or {}).get("url") or "")+ archive_scheme = urllib.parse.urlparse(archive_url).scheme+ archive_scheme_supported = not archive_url or archive_scheme in {"https", "file"}+ legacy_archive = "github.com/avibe-bot/vibe-show-runtime/releases/latest/download/" in archive_url+ provider_repairable = True++ if provider == "manifest-cache":+ if not manifest:+ provider_repairable = False+ _add_doctor_item(+ items,+ "fail",+ "The packaged Show Runtime manifest is missing or invalid",+ "Upgrade or reinstall Avibe from an official wheel that includes the pinned runtime manifest.",+ code="show_runtime.manifest_missing",+ )+ elif not archive:+ provider_repairable = False+ _add_doctor_item(+ items,+ "fail",+ f"The Show Runtime manifest has no archive for {status.get('platform') or 'this platform'}",+ "Install Avibe on a supported platform or upgrade to a release that publishes this platform archive.",+ code="show_runtime.platform_unsupported",+ )+ else:+ _add_doctor_item(+ items,+ "pass",+ f"Show Runtime manifest pins {archive.get('name')} from {archive_url}",+ code="show_runtime.manifest_ready",+ )+ elif provider == "archive":+ if legacy_archive:+ provider_repairable = False+ _add_doctor_item(+ items,+ "fail",+ f"Show Runtime selected the legacy unpinned archive URL: {archive_url}",+ "Reinstall the official Avibe package or remove VIBE_SHOW_RUNTIME_SOURCE/ARCHIVE overrides. "+ "The upstream source repository does not publish release assets.",+ code="show_runtime.legacy_archive_provider",+ )+ else:+ _add_doctor_item(+ items,+ "warn",+ "Show Runtime uses an explicit unpinned archive provider",+ "Prefer the manifest-cache provider for official installations.",+ code="show_runtime.unpinned_archive_provider",+ )+ elif provider in {"github", "npm"}:+ _add_doctor_item(+ items,+ "warn",+ f"Show Runtime uses the {provider} development provider",+ "Use manifest-cache for official installations; keep this override only for development.",+ code="show_runtime.development_provider",+ )+ else:+ provider_repairable = False+ _add_doctor_item(+ items,+ "fail",+ f"Show Runtime provider is unsupported: {provider}",+ "Remove the provider override and reinstall the official Avibe package.",+ code="show_runtime.provider_unsupported",+ )++ if status.get("installed"):+ _add_doctor_item(+ items,+ "pass",+ f"Show Runtime is installed for {status.get('platform') or 'this platform'}",+ code="show_runtime.installed",+ )+ return items++ show_runtime_repairable = provider_repairable and node_available and node_supported and archive_scheme_supported+ show_runtime_retry_action = (+ "Run `vibe doctor repair show-runtime`."+ if show_runtime_repairable+ else "Resolve the provider, platform, Node.js, or archive URL issue above, then rerun Doctor."+ )+ _add_doctor_item(+ items,+ "fail",+ f"Show Runtime is not ready for {status.get('platform') or 'this platform'}",+ (+ "Run `vibe doctor repair show-runtime`; use `vibe doctor --deep` first when download access is uncertain."+ if show_runtime_repairable+ else show_runtime_retry_action+ ),+ code="show_runtime.not_ready",+ repair_target="show-runtime" if show_runtime_repairable else None,+ repair_risk="low",+ )++ if not archive:+ return items+ if not deep:+ _add_doctor_item(+ items,+ "pass",+ "Show Runtime archive reachability was not checked in fast diagnostics",+ "Run `vibe doctor --deep` to distinguish HTTP, DNS, TLS, and timeout failures without downloading the archive.",+ code="show_runtime.archive_probe_skipped",+ )+ return items++ probe = manager.probe_archive_reachability()+ probe_reason = str(probe.get("reason") or "")+ if probe.get("ok"):+ target = probe.get("url") or probe.get("path") or (archive or {}).get("name")+ _add_doctor_item(+ items,+ "pass",+ f"Show Runtime archive is reachable: {target}",+ code="show_runtime.archive_reachable",+ )+ elif probe_reason == "runtime_archive_probe_unsupported":+ _add_doctor_item(+ items,+ "warn",+ "Show Runtime archive server does not support a body-free reachability probe",+ show_runtime_retry_action,+ code="show_runtime.archive_probe_unsupported",+ )+ elif probe.get("download_error"):+ is_manifest_failure = probe_reason.startswith("runtime_manifest_")+ _add_dependency_download_failure(+ items,+ probe.get("download_error"),+ label="Show Runtime manifest" if is_manifest_failure else "Show Runtime archive",+ code_prefix="show_runtime.manifest" if is_manifest_failure else "show_runtime.archive",+ repair_target="show-runtime" if show_runtime_repairable else None,+ retry_action=show_runtime_retry_action,+ )+ elif probe_reason == "runtime_archive_url_unsupported":+ _add_doctor_item(+ items,+ "fail",+ f"Show Runtime archive URL scheme is unsupported: {probe.get('url') or (archive or {}).get('url')}",+ "Use an HTTPS or file URL for the archive, then rerun deep Doctor.",+ code="show_runtime.archive_url_unsupported",+ )+ elif probe_reason.startswith("runtime_manifest_"):+ _add_doctor_item(+ items,+ "fail",+ f"Show Runtime manifest could not be loaded: {probe_reason}",+ "Inspect the configured or packaged Runtime manifest, then reinstall the current Avibe release if needed.",+ code="show_runtime.manifest_unavailable",+ )+ elif probe_reason == "runtime_platform_unsupported":+ _add_doctor_item(+ items,+ "fail",+ f"Show Runtime manifest has no archive for {status.get('platform') or 'this platform'}",+ "Install an Avibe release that publishes a Runtime archive for this platform.",+ code="show_runtime.platform_unsupported",+ )+ else:+ _add_doctor_item(+ items,+ "fail",+ f"Show Runtime archive check failed: {probe_reason or 'unknown error'}",+ f"Inspect the selected archive path or URL. {show_runtime_retry_action}",+ code="show_runtime.archive_check_failed",+ )+ return items++def _doctor(*, deep: bool = False):"""Run diagnostic checks and return results in UI-compatible format.@@ -8328,6 +8816,16 @@ def _doctor(*, deep: bool = False):groups.append({"name": "Runtime", "items": runtime_items})+ dependency_items = [+ *_managed_dependencies_doctor_items(deep=deep),+ *_show_runtime_doctor_items(deep=deep),+ ]+ for item in dependency_items:+ status = item.get("status")+ if status in summary:+ summary[status] += 1+ groups.append({"name": "Dependencies", "items": dependency_items})+local_cli_items = _local_cli_installation_items()for item in local_cli_items:status = item.get("status")@@ -8850,8 +9348,111 @@ def _repair_stale_install_runtime(*, dry_run: bool = False) -> dict:)-def _repair_doctor_targets(targets: list[str], *, dry_run: bool = False) -> dict:- requested_targets = targets or list(DOCTOR_REPAIR_TARGETS)+def _repair_managed_dependency(target: str, installer, *, dry_run: bool = False) -> dict:+ if dry_run:+ return _doctor_repair_result(target, "planned", DOCTOR_REPAIR_DRY_RUN_MESSAGES[target])+ try:+ result = installer(force=True)+ except Exception as exc: # noqa: BLE001+ return _doctor_repair_result(target, "failed", f"{target} repair failed: {exc}")+ if result.get("ok"):+ return _doctor_repair_result(+ target,+ "repaired" if result.get("changed", True) else "skipped",+ str(result.get("message") or f"{target} is ready."),+ path=result.get("path"),+ version=result.get("version"),+ )+ return _doctor_repair_result(+ target,+ "failed",+ str(result.get("message") or result.get("reason") or f"{target} repair failed"),+ reason=result.get("reason"),+ download_error=result.get("download_error"),+ output=result.get("output"),+ )+++def _repair_askill(*, dry_run: bool = False) -> dict:+ return _repair_managed_dependency("askill", api.ensure_askill_installed, dry_run=dry_run)+++def _repair_avault(*, dry_run: bool = False) -> dict:+ return _repair_managed_dependency("avault", api.ensure_avault_installed, dry_run=dry_run)+++def _repair_tmux(*, dry_run: bool = False) -> dict:+ from core.tmux_runtime import ensure_tmux_installed++ return _repair_managed_dependency("tmux", ensure_tmux_installed, dry_run=dry_run)+++def _repair_git_runtime(*, dry_run: bool = False) -> dict:+ from core.git_runtime import GitRuntimeManager++ return _repair_managed_dependency("git-runtime", GitRuntimeManager().ensure, dry_run=dry_run)+++def _repair_show_runtime(*, dry_run: bool = False) -> dict:+ from core.show_runtime import ShowRuntimeManager++ target = "show-runtime"+ if dry_run:+ return _doctor_repair_result(target, "planned", DOCTOR_REPAIR_DRY_RUN_MESSAGES[target])++ manager = ShowRuntimeManager()+ before = manager.status()+ if before.get("installed"):+ return _doctor_repair_result(target, "skipped", "Show Runtime is already ready.")++ 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+ ):+ return _doctor_repair_result(+ target,+ "failed",+ "The packaged Show Runtime manifest is unavailable and the legacy upstream archive URL has no release asset. "+ "Upgrade or reinstall the official Avibe package, or remove stale runtime source overrides.",+ provider=before.get("provider"),+ archive_url=archive_url,+ )++ result = manager.prepare(force=False)+ status = result.get("status") if isinstance(result.get("status"), dict) else {}+ if result.get("ok"):+ return _doctor_repair_result(+ target,+ "repaired",+ "Prepared the manifest-selected Show Runtime.",+ provider=result.get("provider"),+ platform=result.get("platform"),+ install_dir=status.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']}"+ else:+ detail = reason+ return _doctor_repair_result(+ target,+ "failed",+ f"Show Runtime preparation failed: {detail}",+ provider=result.get("provider"),+ platform=result.get("platform"),+ reason=reason,+ download_error=download_error,+ )+++def _repair_doctor_targets(targets: list[str], *, dry_run: bool = False, deep: bool = False) -> dict:+ requested_targets = targets or list(DOCTOR_DEFAULT_REPAIR_TARGETS)unknown = [target for target in requested_targets if target not in DOCTOR_REPAIR_TARGETS]if unknown:return {@@ -8888,6 +9489,11 @@ def _repair_doctor_targets(targets: list[str], *, dry_run: bool = False) -> dict"stale-install-runtime": _repair_stale_install_runtime,"duplicate-service-processes": _repair_duplicate_service_processes,"stale-restart-state": _repair_stale_restart_state,+ "askill": _repair_askill,+ "avault": _repair_avault,+ "git-runtime": _repair_git_runtime,+ "show-runtime": _repair_show_runtime,+ "tmux": _repair_tmux,}results = [handlers[target](dry_run=dry_run) for target in requested_targets]payload = {@@ -8897,14 +9503,15 @@ def _repair_doctor_targets(targets: list[str], *, dry_run: bool = False) -> dict"results": results,}if not dry_run and any(result["status"] != "skipped" for result in results):- payload["doctor"] = _doctor(deep=True)+ refresh_deep = deep or bool(set(targets) & DOCTOR_DEPENDENCY_REPAIR_TARGETS)+ payload["doctor"] = _doctor(deep=refresh_deep)return payloaddef _confirm_doctor_repair(targets: list[str]) -> bool:if not sys.stdin.isatty():return False- target_text = ", ".join(targets or DOCTOR_REPAIR_TARGETS)+ target_text = ", ".join(targets or DOCTOR_DEFAULT_REPAIR_TARGETS)answer = input(f"Repair Avibe doctor target(s): {target_text}? Type 'yes' to continue: ")return answer.strip().lower() == "yes"@@ -10024,7 +10631,11 @@ def cmd_doctor(args=None):if not dry_run and not getattr(args, "yes", False) and not _confirm_doctor_repair(targets):print("Doctor repair was not run. Pass --yes to confirm non-interactively.", file=sys.stderr)return 2- result = _repair_doctor_targets(targets, dry_run=dry_run)+ result = _repair_doctor_targets(+ targets,+ dry_run=dry_run,+ deep=bool(getattr(args, "doctor_deep", False)),+ )_print_doctor_repair_result(result)return 0 if result.get("ok") else 1