Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(show-runtime): bound archive cache growth with protected-set cleanup (#1509)

Call Whitec5329c631a63
diff --git a/core/managed_runtime.py b/core/managed_runtime.py
index 255e6c268..0085ce560 100644
--- a/core/managed_runtime.py
+++ b/core/managed_runtime.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import contextlib
import hashlib
import importlib.resources as package_resources
import json
@@ -19,7 +20,7 @@ from collections.abc import Callable, Mapping
from dataclasses import dataclass
from pathlib import Path, PurePosixPath, PureWindowsPath
from sysconfig import get_platform
-from typing import Any
+from typing import Any, Iterator
from core.dependency_network import (
dependency_error_details,
@@ -29,7 +30,13 @@ from core.dependency_network import (
probe_url,
redact_url,
)
-from storage.lock import MigrationFileLock, MigrationLockTimeout
+from storage.lock import (
+ MigrationFileLock,
+ MigrationLockTimeout,
+ fcntl_available,
+ try_windows_exclusive_lock,
+ unlock_windows_exclusive_lock,
+)
logger = logging.getLogger(__name__)
@@ -338,7 +345,46 @@ class ManagedRuntimeManager:
user_agent=f"avibe-{self.spec.runtime_id}-doctor",
)
- def clean(self, *, keep_previous: int = 1) -> dict[str, Any]:
+ def clean(self, *, keep_previous: int = 1, dry_run: bool = False) -> dict[str, Any]:
+ if dry_run:
+ # Read-only preview: no lock acquisition (the file lock would create
+ # ``.install.lock`` and mutate persistent state), so previews also
+ # work on read-only runtime directories. Busy checks exclude both
+ # same-process staging (in-process lock) and cross-process staging
+ # (read-only existence probe of the lock file) — a preview must not
+ # advertise removing live staging state. The probe stays held
+ # through candidate planning so an install cannot start between
+ # the check and the ``install-*`` enumeration.
+ with self._preview_guard() as busy_reason:
+ if busy_reason:
+ return {
+ "ok": False,
+ "removed": [],
+ "reason": busy_reason,
+ "message": "an install is currently running",
+ }
+ try:
+ result = self._clean_locked(keep_previous=keep_previous, dry_run=True, removed=[])
+ if self._preview_raced_busy():
+ return {
+ "ok": False,
+ "removed": [],
+ "reason": self._reason("install_already_running"),
+ "message": "an install is currently running",
+ }
+ return result
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "Managed %s runtime dry-run inspection failed",
+ self.spec.runtime_id,
+ exc_info=True,
+ )
+ return {
+ "ok": False,
+ "removed": [],
+ "reason": self._reason("clean_inspection_failed"),
+ "message": str(exc),
+ }
try:
file_lock = self._acquire_mutation_lock()
except Exception as exc: # noqa: BLE001
@@ -355,25 +401,229 @@ class ManagedRuntimeManager:
"removed": [],
"reason": self._reason("install_already_running"),
}
+ removed: list[str] = []
try:
- return self._clean_locked(keep_previous=keep_previous)
+ return self._clean_locked(keep_previous=keep_previous, dry_run=dry_run, removed=removed)
+ except Exception as cop: # noqa: BLE001
+ # Real cleanups hit the same traversal errors dry runs do; return
+ # the structured inspection failure instead of raising through
+ # _clean_git_runtime into a reasonless result. Staging removals
+ # that already happened stay in the result.
+ logger.exception("Managed %s runtime cleanup failed", self.spec.runtime_id)
+ return {
+ "ok": False,
+ "removed": list(removed),
+ "reason": self._reason("clean_inspection_failed"),
+ "message": str(cop),
+ }
finally:
self._release_mutation_lock(file_lock)
- def _clean_locked(self, *, keep_previous: int) -> dict[str, Any]:
- removed: list[str] = []
+ @contextlib.contextmanager
+ def _preview_guard(self):
+ """Hold the read-only busy probe through preview candidate planning."""
+ busy = self._preview_busy_reason()
+ try:
+ yield busy
+ finally:
+ self._release_preview_guard()
+
+ def _release_preview_guard(self) -> None:
+ fd = getattr(self, "_preview_guard_fd", None)
+ if fd is not None:
+ if getattr(self, "_preview_guard_msvcrt", False):
+ unlock_windows_exclusive_lock(fd)
+ self._preview_guard_msvcrt = False
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+ self._preview_guard_fd = None
+ if getattr(self, "_preview_held_install_lock", False):
+ self._preview_held_install_lock = False
+ try:
+ self._install_lock.release()
+ except RuntimeError:
+ pass
+
+ def _guard_path_matches_fd(self, fd: int) -> bool:
+ """True when the live path still names the locked descriptor."""
+ try:
+ open_stat = os.fstat(fd)
+ path_stat = self._install_file_lock_path.lstat()
+ except OSError:
+ return False
+ return (
+ stat.S_ISREG(open_stat.st_mode)
+ and open_stat.st_nlink == 1
+ and not stat.S_ISLNK(open_stat.st_mode)
+ and stat.S_ISREG(path_stat.st_mode)
+ and path_stat.st_nlink == 1
+ and not stat.S_ISLNK(path_stat.st_mode)
+ and (open_stat.st_dev, open_stat.st_ino) == (path_stat.st_dev, path_stat.st_ino)
+ )
+
+ def _windows_preview_busy_reason(self) -> str | None:
+ """Read-only Windows busy probe covering the pre-staging interval."""
+ probe = self._preview_lock_probe()
+ if probe is not None:
+ return probe
+ if getattr(self, "_preview_lock_was_absent", False):
+ return None
+ try:
+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NONBLOCK", 0)
+ fd = os.open(self._install_file_lock_path, flags)
+ except OSError:
+ return self._reason("install_already_running")
+ try:
+ if not try_windows_exclusive_lock(fd):
+ os.close(fd)
+ return self._reason("install_already_running")
+ if not self._guard_path_matches_fd(fd):
+ os.close(fd)
+ return self._reason("install_already_running")
+ self._preview_guard_fd = fd
+ self._preview_guard_msvcrt = True
+ return None
+ except OSError:
+ os.close(fd)
+ return self._reason("install_already_running")
+
+ def _preview_busy_reason(self) -> str | None:
+ """Read-only busy check for previews: never creates or rewrites files.
+
+ On POSIX success the shared flock stays held (stored on the instance)
+ until ``_release_preview_guard`` so an exclusive installer cannot
+ start between the probe and staging enumeration. Native Windows uses
+ a non-blocking ``msvcrt.locking`` on an existing lock file instead.
+ After either acquisition, the live path is rechecked against the
+ descriptor so a same-user swap cannot leave the preview on an
+ orphaned inode.
+ """
+ if not self._install_lock.acquire(blocking=False):
+ return self._reason("install_already_running")
+ self._preview_held_install_lock = True
+ try:
+ if not fcntl_available():
+ return self._windows_preview_busy_reason()
+ import fcntl
+
+ probe = self._preview_lock_probe()
+ if probe is not None:
+ return probe
+ if getattr(self, "_preview_lock_was_absent", False):
+ return None
+ try:
+ flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0)
+ fd = os.open(self._install_file_lock_path, flags)
+ except OSError:
+ # Existing but unopenable (ACLs/permissions): a preview cannot
+ # know whether an install is active — report it as busy rather
+ # than risking a misleading "0 entries" preview.
+ return self._reason("install_already_running")
+ try:
+ fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
+ if not self._guard_path_matches_fd(fd):
+ os.close(fd)
+ return self._reason("install_already_running")
+ self._preview_guard_fd = fd
+ return None
+ except OSError:
+ os.close(fd)
+ return self._reason("install_already_running")
+ except BaseException:
+ self._release_preview_guard()
+ raise
+
+ def _preview_lock_missing(self) -> bool:
+ try:
+ self._install_file_lock_path.lstat()
+ except FileNotFoundError:
+ return True
+ except OSError:
+ return False
+ return False
+
+ def _preview_lock_probe(self) -> str | None:
+ try:
+ info = self._install_file_lock_path.lstat()
+ except FileNotFoundError:
+ self._preview_lock_was_absent = True
+ return None
+ except OSError:
+ self._preview_lock_was_absent = False
+ return self._reason("install_already_running")
+ self._preview_lock_was_absent = False
+ if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
+ return self._reason("install_already_running")
+ return None
+
+ def _preview_raced_busy(self) -> bool:
+ """True when an install started after a lock-absent preview probe."""
+ if getattr(self, "_preview_guard_fd", None) is not None:
+ return False
+ if not getattr(self, "_preview_lock_was_absent", False):
+ return False
+ return not self._preview_lock_missing()
+
+ def _rglob_install_metadata(self, versions_dir: Path) -> Iterator[Path]:
+ """rglob metadata files with error-preserving traversal.
+
+ ``Path.rglob`` suppresses subtree traversal errors and silently
+ returns an incomplete candidate set; raise instead so the caller's
+ inspection handling reports it (a misleading empty preview must not
+ hide an unreadable versions tree).
+ """
+ stack: list[Path] = [versions_dir]
+ while stack:
+ parent = stack.pop()
+ try:
+ iterator = os.scandir(parent)
+ except FileNotFoundError:
+ continue
+ except OSError as exc:
+ raise OSError(f"versions traversal failed: {parent}") from exc
+ try:
+ for entry in iterator:
+ if entry.name == self.spec.metadata_filename:
+ yield parent / entry.name
+ elif entry.is_dir(follow_symlinks=False):
+ stack.append(parent / entry.name)
+ except OSError as exc:
+ raise OSError(f"versions traversal failed: {parent}") from exc
+ finally:
+ iterator.close()
+
+ def _clean_locked(
+ self,
+ *,
+ keep_previous: int,
+ dry_run: bool = False,
+ removed: list[str] | None = None,
+ ) -> dict[str, Any]:
+ if removed is None:
+ removed = []
for staging_dir in self.runtime_dir.glob("install-*"):
if staging_dir.is_dir():
- shutil.rmtree(staging_dir, ignore_errors=True)
+ if not dry_run:
+ shutil.rmtree(staging_dir, ignore_errors=True)
removed.append(str(staging_dir))
versions_dir = self.runtime_dir / "versions"
- if not versions_dir.is_dir():
+ try:
+ versions_is_dir = stat.S_ISDIR(versions_dir.stat().st_mode)
+ except FileNotFoundError:
+ return {"ok": True, "removed": removed}
+ except OSError as exc:
+ # An uninspectable versions tree must not silently preview as
+ # empty (misleading "0 entries") — surface an inspection failure.
+ raise OSError(f"versions directory cannot be inspected: {versions_dir}") from exc
+ if not versions_is_dir:
return {"ok": True, "removed": removed}
install_dirs = {
metadata_path.parent
- for metadata_path in versions_dir.rglob(self.spec.metadata_filename)
+ for metadata_path in self._rglob_install_metadata(versions_dir)
if metadata_path.parent.is_dir()
}
current = self._current_install_dir(versions_dir)
@@ -384,9 +634,11 @@ class ManagedRuntimeManager:
reverse=True,
)
for path in candidates[max(0, keep_previous) :]:
- shutil.rmtree(path, ignore_errors=True)
+ if not dry_run:
+ shutil.rmtree(path, ignore_errors=True)
removed.append(str(path))
- self._prune_empty_version_dirs(versions_dir)
+ if not dry_run:
+ self._prune_empty_version_dirs(versions_dir)
return {"ok": True, "removed": removed}
def _manifest_installable(self, manifest: ManagedRuntimeManifest) -> bool:
diff --git a/core/show_runtime.py b/core/show_runtime.py
index 30dbf2300..1ba647efc 100644
--- a/core/show_runtime.py
+++ b/core/show_runtime.py
@@ -2,6 +2,9 @@ from __future__ import annotations
import atexit
import asyncio
+import contextlib
+import errno
+import fnmatch
import hashlib
import importlib.resources as package_resources
import json
@@ -13,9 +16,11 @@ import re
import shlex
import shutil
import signal
+import stat
import subprocess
import tarfile
import tempfile
+import threading
import time
import urllib.parse
import urllib.request
@@ -23,10 +28,19 @@ from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from sysconfig import get_platform
-from typing import Any, Mapping
+from typing import Any, Iterable, Iterator, Mapping
import httpx
+from storage.lock import (
+ MigrationFileLock,
+ MigrationLockTimeout,
+ _try_lock as storage_lock_try_lock,
+ fcntl_available,
+ try_windows_exclusive_lock,
+ unlock_windows_exclusive_lock,
+)
+
from config import paths
from core.dependency_network import dependency_error_details, fetch_bytes, fetch_to_path, probe_url, redact_url
from core.show_pages import SHOW_RUNTIME_RECOVERY_LOADING_DELAY_SECONDS
@@ -46,7 +60,49 @@ _RUNTIME_SOURCE_GITHUB = "github"
_RUNTIME_SOURCE_NPM = "npm"
_RUNTIME_MANIFEST_RESOURCE = "show_runtime_manifest.json"
_PACKAGED_RUNTIME_MANIFEST_SOURCE = f"package:{_RUNTIME_MANIFEST_RESOURCE}"
+_CUSTOM_MANIFEST_LINEAGE = "*custom*"
_MANAGED_RUNTIME_ROLLBACK_INSTALLS = 1
+_CONTENT_ADDRESSED_ARCHIVE_RE = re.compile(r"^[0-9a-f]{64}\.tgz$")
+_ABANDONED_ARCHIVE_CLAIM_RE = re.compile(r"^[0-9a-f]{64}\.tgz\.avibe-removing$")
+# Cross-process safety window: between a download finalizing ``<sha256>.tgz``
+# and the installing process writing install metadata / ``current.json``, the
+# archive is not yet protected. Archives younger than this window are never
+# pruned by automatic or manual cleanup; real stale archives are days old.
+_ARCHIVE_MTIME_GUARD_SECONDS = 15 * 60
+# Skip reasons for archive-cache cleanup; consumers (CLI, Doctor) key off
+# ``skipped_reason`` generically instead of matching literal strings.
+_SKIPPED_ARCHIVE_REASON_INSTALL_RUNNING = "runtime_install_already_running"
+_SKIPPED_ARCHIVE_REASON_INSPECTION_FAILED = "archive_inspection_failed"
+_SKIPPED_ARCHIVE_REASON_REMOVAL_FAILED = "archive_removal_failed"
+# Every archive-cache report carries exactly one outcome from this set; the
+# enumeration test in tests/test_show_runtime_archive_cleanup.py pins CLI and
+# Doctor rendering to it, so a new outcome fails the test until wired.
+_ARCHIVE_CLEANUP_OUTCOMES = frozenset({"cleaned", "partial", "skipped"})
+
+
+class _ArchiveMetadataError(Exception):
+ """A retained install's metadata could not be read; destructive cleanup must abort."""
+
+
+class _ArchiveInspectionError(Exception):
+ """The archive cache itself could not be inspected; cleanup must abort."""
+
+
+def _is_exclusive_regular_file(info: os.stat_result) -> bool:
+ """True only for a one-link regular file that is not a reparse point."""
+ if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
+ return False
+ attrs = getattr(info, "st_file_attributes", 0)
+ reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0)
+ return not (reparse and attrs & reparse)
+
+
+def _is_reparse_point(info: os.stat_result) -> bool:
+ if stat.S_ISLNK(info.st_mode):
+ return True
+ attrs = getattr(info, "st_file_attributes", 0)
+ reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0)
+ return bool(reparse and attrs & reparse)
_FALSE_VALUES = {"0", "false", "no", "off"}
_PREWARM_IMPORT_RE = re.compile(r"""(?P<quote>["'])(?P<path>[^"']+)(?P=quote)""")
_PREWARM_MAX_ASSETS = 64
@@ -189,6 +245,15 @@ class ShowRuntimeManager:
self._base_url: str | None = None
self._lock = asyncio.Lock()
self._capability_lock = asyncio.Lock()
+ # Cross-process in-flight install guard for the archive cache: held for
+ # the whole resolve-download-validate-extract window so a concurrent
+ # ``runtime clean`` (or another process's post-install cleanup) cannot
+ # unlink an archive this process has validated but not yet opened.
+ # ``flock`` is not re-entrant across file handles, so the depth counter
+ # lets the post-install cleanup reuse the installer's lock.
+ self._install_guard = threading.RLock()
+ self._install_guard_depth = 0
+ self._install_guard_path = self.runtime_dir / ".install.lock"
self._capability_identity: tuple[str, int | None] | None = None
self._context_key_capability: ShowRuntimeContextCapability | None = None
self._capability_retry_deadline = 0.0
@@ -593,21 +658,26 @@ class ShowRuntimeManager:
return command
def _clean_after_managed_install(self, command: list[str]) -> None:
- if (
- self.runtime_source != _RUNTIME_SOURCE_MANIFEST
- or self.manifest_path is not None
- or self.manifest_url is not None
- ):
- return
try:
- protected_install_dirs = self._manifest_install_dirs_for_command(command)
- removed = self._clean_manifest_install_dirs(
- keep_previous=_MANAGED_RUNTIME_ROLLBACK_INSTALLS,
- manifest_source=_PACKAGED_RUNTIME_MANIFEST_SOURCE,
- protected_install_dirs=protected_install_dirs,
- )
- if removed:
- logger.info("Removed %d stale managed Show Runtime install(s)", len(removed))
+ if self.runtime_source == _RUNTIME_SOURCE_MANIFEST:
+ protected_install_dirs = self._manifest_install_dirs_for_command(command)
+ packaged = self.manifest_path is None and self.manifest_url is None
+ removed = self._clean_manifest_install_dirs(
+ keep_previous=_MANAGED_RUNTIME_ROLLBACK_INSTALLS,
+ manifest_source=(
+ _PACKAGED_RUNTIME_MANIFEST_SOURCE if packaged else _CUSTOM_MANIFEST_LINEAGE
+ ),
+ protected_install_dirs=protected_install_dirs,
+ )
+ if removed:
+ logger.info("Removed %d stale managed Show Runtime install(s)", len(removed))
+ archives = self._clean_downloaded_archives()
+ if archives.get("removed_count"):
+ logger.info(
+ "Removed %d stale Show Runtime archive(s), reclaimed %d byte(s)",
+ archives["removed_count"],
+ archives["removed_bytes"],
+ )
except Exception:
# Cache cleanup must never turn a usable runtime install into a failed prepare.
logger.warning("Failed to clean stale managed Show Runtime installs", exc_info=True)
@@ -733,15 +803,654 @@ class ShowRuntimeManager:
result["reason"] = "runtime_archive_download_failed"
return result
- def clean(self, *, keep_previous: int = 1) -> dict[str, Any]:
+ @contextlib.contextmanager
+ def _preview_guard(self):
+ """Hold a read-only install guard for the whole preview planning.
+
+ The probe lock stays held while staging loops enumerate candidates, so
+ an install starting after the check cannot slip a live ``manifest-*``
+ directory into the preview. Yields the busy reason (or ``None`` when
+ the preview may proceed).
+ """
+ busy = self._preview_busy_reason_locked()
+ try:
+ yield busy
+ finally:
+ self._release_preview_guard()
+
+ def _preview_busy_reason_locked(self) -> str | None:
+ """Take the read-only busy probe and keep it for the preview scope."""
+ reason = self._preview_busy_reason()
+ if reason is None:
+ self._preview_guard_fd = getattr(self, "_preview_guard_fd", None)
+ return reason
+
+ def _release_preview_guard(self) -> None:
+ fd = getattr(self, "_preview_guard_fd", None)
+ if fd is not None:
+ if getattr(self, "_preview_guard_msvcrt", False):
+ unlock_windows_exclusive_lock(fd)
+ self._preview_guard_msvcrt = False
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+ self._preview_guard_fd = None
+
+ def _windows_preview_busy_reason(self) -> str | None:
+ """Read-only Windows busy probe covering the pre-staging interval.
+
+ A leftover ``.install.lock`` is not itself busy — Windows never
+ deletes it. An installer that already holds ``msvcrt.locking`` on
+ that file (archive validation, before ``manifest-*`` exists) is.
+ Staging remains an additional crash-leftover signal.
+ """
+ probe = self._preview_lock_probe()
+ if probe is not None:
+ return probe
+ staging = self._staging_sentinel_reason()
+ if staging:
+ return staging
+ if getattr(self, "_preview_lock_was_absent", False):
+ return None
+ try:
+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NONBLOCK", 0)
+ fd = os.open(self._install_guard_path, flags)
+ except OSError:
+ return "runtime_install_guard_unavailable"
+ try:
+ if not try_windows_exclusive_lock(fd):
+ os.close(fd)
+ return "runtime_install_already_running"
+ if not self._guard_path_matches_fd(fd):
+ os.close(fd)
+ return "runtime_install_guard_unavailable"
+ self._preview_guard_fd = fd
+ self._preview_guard_msvcrt = True
+ return None
+ except OSError:
+ os.close(fd)
+ return "runtime_install_guard_unavailable"
+
+ def _preview_busy_reason(self) -> str | None:
+ """Read-only busy probe for previews: never creates or rewrites files.
+
+ Detects an active install (same process via the RLock depth, another
+ process via an advisory lock on an existing ``.install.lock``) so a
+ preview never advertises a live in-use archive or staging directory
+ as removable. On POSIX an unopenable-but-existing guard reports
+ unavailable (an inspection problem). Native Windows has no flock;
+ the probe instead takes a non-blocking ``msvcrt.locking`` on the
+ existing lock file (never creating it) and still treats a fresh
+ ``manifest-*``/``prebuilt-*`` directory as busy.
+
+ On success the probe fd is kept open with the advisory lock held
+ (stored on the instance) so the caller can hold the guard through
+ planning; ``_release_preview_guard`` unlocks and closes it.
+ """
+ if self._install_guard_depth > 0:
+ return "runtime_install_already_running"
+ if not fcntl_available():
+ return self._windows_preview_busy_reason()
+ import fcntl
+
+ probe = self._preview_lock_probe()
+ if probe is not None:
+ return probe
+ if getattr(self, "_preview_lock_was_absent", False):
+ return None
+ try:
+ flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0)
+ fd = os.open(self._install_guard_path, flags)
+ except OSError:
+ return "runtime_install_guard_unavailable"
+ try:
+ fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
+ # Held (shared) until the preview scope ends: an installer's
+ # exclusive-lock acquisition now blocks on us and vice versa.
+ if not self._guard_path_matches_fd(fd):
+ os.close(fd)
+ return "runtime_install_guard_unavailable"
+ self._preview_guard_fd = fd
+ return None
+ except OSError:
+ os.close(fd)
+ return "runtime_install_already_running"
+
+ def _staging_sentinel_reason(self) -> str | None:
+ """Treat freshly-modified staging dirs as busy (flock-less platforms)."""
+ mtime_floor = time.time() - _ARCHIVE_MTIME_GUARD_SECONDS
+ try:
+ for pattern in ("manifest-*", "prebuilt-*"):
+ for path in self.runtime_dir.glob(pattern):
+ try:
+ if path.is_dir() and path.stat().st_mtime > mtime_floor:
+ return "runtime_install_already_running"
+ except OSError:
+ continue
+ except OSError:
+ return None
+ return None
+
+ def _preview_lock_missing(self) -> bool:
+ try:
+ self._install_guard_path.lstat()
+ except FileNotFoundError:
+ return True
+ except OSError:
+ return False
+ return False
+
+ def _preview_lock_probe(self) -> str | None:
+ """Refuse special files before a blocking preview open."""
+ try:
+ info = self._install_guard_path.lstat()
+ except FileNotFoundError:
+ self._preview_lock_was_absent = True
+ return None
+ except OSError:
+ self._preview_lock_was_absent = False
+ return "runtime_install_guard_unavailable"
+ self._preview_lock_was_absent = False
+ if _is_reparse_point(info) or not _is_exclusive_regular_file(info):
+ return "runtime_install_guard_unavailable"
+ return None
+
+ def _guard_path_matches_fd(self, fd: int) -> bool:
+ """True when the live path still names the locked descriptor."""
+ try:
+ open_stat = os.fstat(fd)
+ path_stat = self._install_guard_path.lstat()
+ except OSError:
+ return False
+ return (
+ _is_exclusive_regular_file(open_stat)
+ and _is_exclusive_regular_file(path_stat)
+ and (open_stat.st_dev, open_stat.st_ino) == (path_stat.st_dev, path_stat.st_ino)
+ )
+
+ def _preview_raced_busy(self) -> bool:
+ """True when an install started after a lock-absent preview probe."""
+ if getattr(self, "_preview_guard_fd", None) is not None:
+ return False
+ if self._staging_sentinel_reason():
+ return True
+ if not getattr(self, "_preview_lock_was_absent", False):
+ return False
+ return not self._preview_lock_missing()
+
+ def clean(self, *, keep_previous: int = 1, dry_run: bool = False) -> dict[str, Any]:
removed: list[str] = []
- for pattern in ("prebuilt-*", "manifest-*"):
- for path in self.runtime_dir.glob(pattern):
- if path.is_dir():
- shutil.rmtree(path, ignore_errors=True)
- removed.append(str(path))
- removed.extend(self._clean_manifest_install_dirs(keep_previous=keep_previous))
- return {"ok": True, "removed": removed}
+ try:
+ return self._clean_locked(keep_previous=keep_previous, dry_run=dry_run, removed=removed)
+ except Exception:
+ # A planning failure (e.g. an install dir disappearing mid-scan)
+ # must return the structured inspection-failure report, never an
+ # exception through the CLI or Doctor paths. Staging removals that
+ # already happened stay in the result so the CLI does not claim
+ # zero items after files were deleted.
+ logger.warning("Show Runtime cache cleanup failed", exc_info=True)
+ return {
+ "ok": False,
+ "dry_run": dry_run,
+ "removed": list(removed),
+ "archives": self._skipped_archive_report(_SKIPPED_ARCHIVE_REASON_INSPECTION_FAILED),
+ }
+
+ def _clean_locked(
+ self,
+ *,
+ keep_previous: int,
+ dry_run: bool,
+ removed: list[str] | None = None,
+ ) -> dict[str, Any]:
+ if removed is None:
+ removed = []
+ preview_guard = self._preview_guard() if dry_run else contextlib.nullcontext(None)
+ with preview_guard as busy_reason:
+ if dry_run and busy_reason:
+ # Map both contention and guard-unavailability through the
+ # same skip-reason taxonomy the real cleanup uses, so the CLI
+ # renders reason-specific guidance either way.
+ skip_reason = (
+ _SKIPPED_ARCHIVE_REASON_INSPECTION_FAILED
+ if busy_reason == "runtime_install_guard_unavailable"
+ else _SKIPPED_ARCHIVE_REASON_INSTALL_RUNNING
+ )
+ return {
+ "ok": False,
+ "dry_run": True,
+ "removed": [],
+ "archives": self._skipped_archive_report(skip_reason),
+ }
+ for pattern in ("prebuilt-*", "manifest-*"):
+ for path in self.runtime_dir.glob(pattern):
+ if path.is_dir():
+ if not dry_run:
+ shutil.rmtree(path, ignore_errors=True)
+ removed.append(str(path))
+ self._clean_manifest_install_dirs(
+ keep_previous=keep_previous,
+ dry_run=dry_run,
+ removed=removed,
+ )
+ # A dry run leaves stale install dirs in place, so their metadata
+ # would still read as "protected" below. Skip metadata under the
+ # dirs a real run would remove, so the archive preview matches
+ # the real outcome. Hold the preview guard through this phase so
+ # an install starting after staging enumeration cannot expose an
+ # in-flight archive as reclaimable.
+ skip_metadata_under = {Path(path) for path in removed} if dry_run else None
+ archives = self._clean_downloaded_archives(
+ dry_run=dry_run,
+ skip_metadata_under=skip_metadata_under,
+ )
+ if dry_run and self._preview_raced_busy():
+ return {
+ "ok": False,
+ "dry_run": True,
+ "removed": [],
+ "archives": self._skipped_archive_report(_SKIPPED_ARCHIVE_REASON_INSTALL_RUNNING),
+ }
+ return {
+ "ok": True,
+ "dry_run": dry_run,
+ "removed": removed,
+ "archives": archives,
+ }
+
+ def archive_cache_status(self, *, keep_previous: int = 1) -> dict[str, Any]:
+ """Report reclaimable content-addressed archives without deleting anything.
+
+ Simulates the install-dir cleanup a real ``clean(keep_previous=...)``
+ would perform, so the reported candidates match what reclamation would
+ actually remove. Failures in either phase return the structured
+ inspection-failure report so Doctor can render them.
+ """
+ report = self.clean(keep_previous=keep_previous, dry_run=True)
+ archives = report.get("archives") or self._skipped_archive_report(_SKIPPED_ARCHIVE_REASON_INSPECTION_FAILED)
+ return archives
+
+ @staticmethod
+ def _iter_install_metadata(versions_dir: Path, pattern: str) -> Iterator[Path]:
+ """Glob install metadata with error-preserving traversal.
+
+ ``Path.glob`` suppresses per-directory OSError and silently omits
+ retained installs whose subtree cannot be scanned; that would unprotect
+ their rollback archives, so traversal failures raise instead.
+ """
+ try:
+ parts = pattern.split("/")
+ current: Iterable[Path] = [versions_dir]
+ for depth, part in enumerate(parts):
+ is_last = depth == len(parts) - 1
+ next_paths: list[Path] = []
+ for parent in current:
+ try:
+ iterator = os.scandir(parent)
+ except FileNotFoundError:
+ continue
+ except NotADirectoryError:
+ # An unrelated non-directory matched a wildcard level
+ # (e.g. .DS_Store under versions/); skip it rather
+ # than disabling archive reporting for the cache.
+ continue
+ except OSError as exc:
+ raise _ArchiveInspectionError(f"versions traversal failed: {parent}") from exc
+ try:
+ for entry in iterator:
+ if not fnmatch.fnmatch(entry.name, part):
+ continue
+ if not is_last and not entry.is_dir(follow_symlinks=False):
+ # Intermediate wildcard levels must be
+ # directories; files/symlinks are not installs.
+ continue
+ child = parent / entry.name
+ next_paths.append(child)
+ except OSError as exc:
+ raise _ArchiveInspectionError(f"versions traversal failed: {parent}") from exc
+ finally:
+ iterator.close()
+ current = next_paths
+ for path in current:
+ if path.name == ".vibe-show-runtime.json":
+ yield path
+ except _ArchiveInspectionError:
+ raise
+
+ def _protected_archive_sha256s(self, skip_metadata_under: set[Path] | None = None) -> set[str]:
+ """SHA-256 digests of archives the current and retained installs still need.
+
+ Sources: the ``current.json`` pointer plus every remaining managed
+ install's ``.vibe-show-runtime.json`` metadata. Called after
+ install-dir cleanup, so the remaining metadata files are exactly the
+ current install plus the retained rollback install(s). Metadata under
+ ``skip_metadata_under`` is ignored, so dry runs can simulate the state
+ after removing those install dirs.
+
+ Raises ``_ArchiveMetadataError`` when a retained install's metadata is
+ unreadable or malformed: silently treating that archive as unprotected
+ could delete the artifact a rollback reinstall needs.
+ """
+ skip_resolved = {path.resolve() for path in (skip_metadata_under or ())}
+
+ def _skipped(metadata_path: Path) -> bool:
+ if not skip_resolved:
+ return False
+ resolved = metadata_path.resolve()
+ return any(resolved == item or item in resolved.parents for item in skip_resolved)
+
+ protected: set[str] = set()
+ try:
+ pointer = json.loads((self.runtime_dir / "current.json").read_text(encoding="utf-8"))
+ digest = pointer.get("archive_sha256")
+ if isinstance(digest, str) and _CONTENT_ADDRESSED_ARCHIVE_RE.fullmatch(f"{digest}.tgz"):
+ protected.add(digest)
+ except FileNotFoundError:
+ pass
+ except Exception as cop:
+ raise _ArchiveMetadataError("current.json is unreadable") from cop
+ if self.archive_path is not None:
+ try:
+ archive_name = self.archive_path.resolve().name
+ except OSError:
+ archive_name = self.archive_path.name
+ if _CONTENT_ADDRESSED_ARCHIVE_RE.fullmatch(archive_name):
+ protected.add(archive_name[: -len(".tgz")])
+ versions_dir = self.runtime_dir / "versions"
+ if versions_dir.is_symlink():
+ raise _ArchiveMetadataError("versions directory is a symlink")
+ try:
+ # Path.is_dir()/exists() suppress OSError into False; an
+ # uninspectable versions tree must instead fail closed so every
+ # retained install keeps its rollback archive protected.
+ versions_is_dir = stat.S_ISDIR(versions_dir.stat().st_mode)
+ except FileNotFoundError:
+ versions_is_dir = False
+ except OSError as exc:
+ raise _ArchiveInspectionError("versions directory cannot be inspected") from exc
+ if versions_is_dir:
+ for pattern in ("*/*/.vibe-show-runtime.json", "*/*/*/.vibe-show-runtime.json"):
+ for metadata_path in self._iter_install_metadata(versions_dir, pattern):
+ if _skipped(metadata_path):
+ continue
+ try:
+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
+ except Exception as exc:
+ raise _ArchiveMetadataError(f"install metadata is unreadable: {metadata_path}") from exc
+ digest = metadata.get("archive_sha256")
+ if not _CONTENT_ADDRESSED_ARCHIVE_RE.fullmatch(
+ f"{digest}.tgz" if isinstance(digest, str) else ""
+ ):
+ raise _ArchiveMetadataError(
+ f"install metadata archive_sha256 is missing or not a digest: {metadata_path}"
+ )
+ protected.add(digest)
+ return protected
+
+ def _archive_cleanup_candidates(self, protected: set[str]) -> list[tuple[Path, int, str, int]]:
+ """Completed content-addressed archives outside the protected set.
+
+ Only strict ``<sha256>.tgz`` regular files are candidates. The manifest
+ download flow stages into ``<sha256>.tmp`` and atomically renames only
+ after size + checksum verification, so a matching name implies a
+ completed, verified archive; in-progress ``.tmp`` downloads, symlinks,
+ and unknown file names are never candidates. Archives modified within
+ the cross-process safety window are also skipped: another process may
+ have just finalized a download whose install metadata does not exist
+ yet.
+ """
+ downloads_dir = self.runtime_dir / "downloads"
+ # Windows tuples carry an extra inode field for identity checks;
+ # POSIX tuples pad it so both branches share one unpack shape.
+ candidates: list[tuple[Path, int, str, int]] = []
+ try:
+ downloads_stat = downloads_dir.lstat() # error-preserving, no follow
+ exists = True
+ except FileNotFoundError:
+ exists = False
+ except OSError as exc:
+ raise _ArchiveInspectionError("downloads directory cannot be inspected") from exc
+ if not exists:
+ return candidates
+ # A symlink or reparse-point downloads directory would follow the
+ # link and unlink files outside Avibe's runtime state; fail as an
+ # inspection error rather than traverse it.
+ if _is_reparse_point(downloads_stat) or not stat.S_ISDIR(downloads_stat.st_mode):
+ raise _ArchiveInspectionError("downloads directory is a symlink or not a directory")
+ mtime_floor = time.time() - _ARCHIVE_MTIME_GUARD_SECONDS
+ if os.name == "nt":
+ # Directory descriptors (dir_fd) are unsupported on native
+ # Windows, so scan/stat/unlink by path. Bind the scan to the
+ # validated directory identity (dev/ino) so a junction swap of
+ # ``downloads`` cannot redirect enumeration or later deletion.
+ downloads_identity = (downloads_stat.st_dev, downloads_stat.st_ino)
+
+ def _require_same_downloads() -> None:
+ try:
+ current = downloads_dir.lstat()
+ except OSError as exc:
+ raise _ArchiveInspectionError("downloads directory cannot be inspected") from exc
+ if _is_reparse_point(current) or not stat.S_ISDIR(current.st_mode):
+ raise _ArchiveInspectionError("downloads directory is a symlink or not a directory")
+ if (current.st_dev, current.st_ino) != downloads_identity:
+ raise _ArchiveInspectionError("downloads directory was replaced")
+
+ _require_same_downloads()
+ iterator = os.scandir(downloads_dir)
+ try:
+ for entry in iterator:
+ is_claim = bool(_ABANDONED_ARCHIVE_CLAIM_RE.fullmatch(entry.name))
+ if not is_claim and not _CONTENT_ADDRESSED_ARCHIVE_RE.fullmatch(entry.name):
+ continue
+ try:
+ entry_stat = entry.stat(follow_symlinks=False)
+ except FileNotFoundError:
+ continue
+ except OSError as cop:
+ raise _ArchiveInspectionError(f"archive is not stat-able: {entry.name}") from cop
+ if not stat.S_ISREG(entry_stat.st_mode):
+ continue
+ if not is_claim:
+ if entry_stat.st_mtime > mtime_floor:
+ continue
+ if entry.name[: -len(".tgz")] in protected:
+ continue
+ candidates.append(
+ (downloads_dir / entry.name, entry_stat.st_size, entry.name, entry_stat.st_ino)
+ )
+ finally:
+ iterator.close()
+ _require_same_downloads()
+ self._downloads_dir_identity = downloads_identity
+ return candidates
+ # POSIX: bind enumeration and unlinking to the directory we validated
+ # so a concurrent path swap (symlink replacing ``downloads`` between
+ # the stat above and iterdir/unlink below) cannot redirect operations.
+ dir_fd = os.open(downloads_dir, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_DIRECTORY", 0))
+ try:
+ opened = os.fstat(dir_fd)
+ if (opened.st_dev, opened.st_ino) != (downloads_stat.st_dev, downloads_stat.st_ino):
+ raise _ArchiveInspectionError("downloads directory was replaced before scan")
+ with os.scandir(dir_fd) as entries:
+ names = [entry.name for entry in entries]
+ for name in sorted(names):
+ is_claim = bool(_ABANDONED_ARCHIVE_CLAIM_RE.fullmatch(name))
+ if not is_claim and not _CONTENT_ADDRESSED_ARCHIVE_RE.fullmatch(name):
+ continue
+ try:
+ stat_result = os.stat(name, dir_fd=dir_fd, follow_symlinks=False)
+ except FileNotFoundError:
+ continue
+ except OSError as cop:
+ raise _ArchiveInspectionError(f"archive is not stat-able: {name}") from cop
+ if not stat.S_ISREG(stat_result.st_mode):
+ continue
+ if not is_claim:
+ if stat_result.st_mtime > mtime_floor:
+ continue
+ if name[: -len(".tgz")] in protected:
+ continue
+ candidates.append((downloads_dir / name, stat_result.st_size, name, 0))
+ # Keep the enumeration descriptor until the caller closes it so
+ # the removal phase (when any) unlinks through the same fd.
+ # Dry runs, Doctor, and empty real scans close it in
+ # ``_clean_downloaded_archives``.
+ self._downloads_dir_fd = dir_fd
+ return candidates
+ except BaseException:
+ os.close(dir_fd)
+ raise
+
+ def _close_downloads_dir_fd(self) -> None:
+ fd = getattr(self, "_downloads_dir_fd", None)
+ if fd is not None:
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+ self._downloads_dir_fd = None
+
+ def _clean_downloaded_archives(
+ self,
+ *,
+ dry_run: bool = False,
+ skip_metadata_under: set[Path] | None = None,
+ ) -> dict[str, Any]:
+ """Report on / prune the content-addressed archive cache.
+
+ Dry runs are strictly read-only: they never take the install guard,
+ never create or rewrite ``.install.lock``, and stay usable on a
+ read-only runtime directory (Doctor contract). Real cleanup serializes
+ against installs via the guard (re-entrant inside an install) and
+ reports one of two skip reasons: lock contention, or inspection
+ failure — consumers key off ``skipped_reason`` alone.
+ """
+ if dry_run:
+ try:
+ protected = self._protected_archive_sha256s(skip_metadata_under=skip_metadata_under)
+ candidates = self._archive_cleanup_candidates(protected)
+ except Exception:
+ logger.warning("Show Runtime archive cleanup inspection failed", exc_info=True)
+ return self._skipped_archive_report(_SKIPPED_ARCHIVE_REASON_INSPECTION_FAILED)
+ finally:
+ # Dry runs never delete, so the enumeration descriptor (kept
+ # for the removal phase) must be closed on every path.
+ self._close_downloads_dir_fd()
+ return {
+ "outcome": "cleaned" if not candidates else "partial",
+ "protected_count": len(protected),
+ "candidate_count": len(candidates),
+ "candidate_bytes": sum(size for _, size, _name, _ino in candidates),
+ "removed_count": 0,
+ "removed_bytes": 0,
+ "failed_count": 0,
+ }
+ with self._install_guard_locked(timeout_seconds=1.0) as (acquired, guard_reason):
+ if not acquired:
+ logger.warning("Show Runtime archive cleanup skipped: install guard %s", guard_reason)
+ if guard_reason == "runtime_install_guard_unavailable":
+ return self._skipped_archive_report(_SKIPPED_ARCHIVE_REASON_INSPECTION_FAILED)
+ return self._skipped_archive_report(_SKIPPED_ARCHIVE_REASON_INSTALL_RUNNING)
+ try:
+ protected = self._protected_archive_sha256s(skip_metadata_under=skip_metadata_under)
+ candidates = self._archive_cleanup_candidates(protected)
+ removed_count = 0
+ removed_bytes = 0
+ failed_count = 0
+ # Unlink through the same validated directory on POSIX (no
+ # path resolution that a concurrent swap could redirect); on
+ # Windows unlink by path. A fresh runtime with no candidates
+ # never opens the directory at all.
+ if candidates:
+ candidates.sort(key=lambda item: (0 if _ABANDONED_ARCHIVE_CLAIM_RE.fullmatch(item[2]) else 1, item[2]))
+ if os.name == "nt":
+ downloads_identity = getattr(self, "_downloads_dir_identity", None)
+ for path, size, name, inode in candidates:
+ is_claim = bool(_ABANDONED_ARCHIVE_CLAIM_RE.fullmatch(name))
+ claimed = path if is_claim else path.with_name(f"{name}.avibe-removing")
+ try:
+ if downloads_identity is not None:
+ dir_stat = path.parent.lstat()
+ if _is_reparse_point(dir_stat) or (
+ dir_stat.st_dev,
+ dir_stat.st_ino,
+ ) != downloads_identity:
+ raise OSError("downloads directory was replaced")
+ pre_stat = os.stat(path, follow_symlinks=False)
+ if inode and pre_stat.st_ino != inode:
+ raise OSError("entry was replaced after enumeration")
+ if not stat.S_ISREG(pre_stat.st_mode):
+ raise OSError("entry replaced by a non-regular file")
+ if is_claim:
+ os.unlink(path)
+ else:
+ os.rename(path, claimed)
+ post_stat = os.stat(claimed, follow_symlinks=False)
+ if inode and post_stat.st_ino != inode:
+ os.rename(claimed, path)
+ raise OSError("rename claimed a different entry")
+ os.unlink(claimed)
+ except OSError:
+ logger.warning("Failed to remove stale Show Runtime archive %s", path, exc_info=True)
+ failed_count += 1
+ try:
+ if not is_claim and claimed.exists():
+ os.rename(claimed, path)
+ except OSError:
+ pass
+ continue
+ removed_count += 1
+ removed_bytes += size
+ else:
+ dir_fd = getattr(self, "_downloads_dir_fd", None)
+ try:
+ for path, size, name, _inode in candidates:
+ try:
+ os.unlink(name, dir_fd=dir_fd)
+ except OSError:
+ logger.warning("Failed to remove stale Show Runtime archive %s", path, exc_info=True)
+ failed_count += 1
+ continue
+ removed_count += 1
+ removed_bytes += size
+ finally:
+ if dir_fd is not None:
+ os.close(dir_fd)
+ self._downloads_dir_fd = None
+ report = {
+ "protected_count": len(protected),
+ "candidate_count": len(candidates),
+ "candidate_bytes": sum(size for _, size, _name, _ino in candidates),
+ "removed_count": removed_count,
+ "removed_bytes": removed_bytes,
+ "failed_count": failed_count,
+ }
+ if failed_count:
+ report["outcome"] = "skipped" if removed_count == 0 else "partial"
+ report["skipped_reason"] = _SKIPPED_ARCHIVE_REASON_REMOVAL_FAILED
+ else:
+ report["outcome"] = "cleaned"
+ return report
+ except Exception:
+ logger.warning("Show Runtime archive cleanup failed", exc_info=True)
+ return self._skipped_archive_report(_SKIPPED_ARCHIVE_REASON_INSPECTION_FAILED)
+ finally:
+ # Empty real scans never enter the unlink branch that closes
+ # the enumeration descriptor; close it on every remaining path.
+ self._close_downloads_dir_fd()
+
+ @staticmethod
+ def _skipped_archive_report(reason: str) -> dict[str, Any]:
+ return {
+ "outcome": "skipped",
+ "protected_count": 0,
+ "candidate_count": 0,
+ "candidate_bytes": 0,
+ "removed_count": 0,
+ "removed_bytes": 0,
+ "skipped_reason": reason,
+ }
def _clean_manifest_install_dirs(
self,
@@ -749,10 +1458,14 @@ class ShowRuntimeManager:
keep_previous: int,
manifest_source: str | None = None,
protected_install_dirs: set[Path] | None = None,
+ dry_run: bool = False,
+ removed: list[str] | None = None,
) -> list[str]:
+ if removed is None:
+ removed = []
versions_dir = self.runtime_dir / "versions"
if not versions_dir.is_dir():
- return []
+ return removed
protected = set(protected_install_dirs or ())
current_install_dir = self._current_manifest_install_dir(versions_dir)
if current_install_dir is not None:
@@ -779,7 +1492,6 @@ class ShowRuntimeManager:
if kept_previous < keep_previous:
kept_previous += 1
protected.add(path_resolved)
- removed: list[str] = []
removable_install_dirs = [
path
for path, path_resolved in resolved_install_dirs.items()
@@ -798,9 +1510,11 @@ class ShowRuntimeManager:
for path in sorted(safe_removable_install_dirs, key=lambda item: len(resolved_install_dirs[item].parts), reverse=True):
if not path.is_dir():
continue
- shutil.rmtree(path, ignore_errors=True)
+ if not dry_run:
+ shutil.rmtree(path, ignore_errors=True)
removed.append(str(path))
- self._prune_empty_manifest_version_dirs(versions_dir)
+ if not dry_run:
+ self._prune_empty_manifest_version_dirs(versions_dir)
return removed
@staticmethod
@@ -821,10 +1535,13 @@ class ShowRuntimeManager:
metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
except Exception:
continue
- if (
- metadata.get("provider") != _RUNTIME_SOURCE_MANIFEST
- or metadata.get("manifest_source") != manifest_source
- ):
+ if metadata.get("provider") != _RUNTIME_SOURCE_MANIFEST:
+ continue
+ source = metadata.get("manifest_source")
+ if manifest_source == _CUSTOM_MANIFEST_LINEAGE:
+ if source == _PACKAGED_RUNTIME_MANIFEST_SOURCE:
+ continue
+ elif source != manifest_source:
continue
install_dirs.add(metadata_path.parent)
return install_dirs
@@ -839,14 +1556,24 @@ class ShowRuntimeManager:
pass
return None
+ def _manifest_source_for_install_dirs(self, install_dirs: set[Path]) -> str | None:
+ for install_dir in install_dirs:
+ try:
+ metadata = json.loads(self._manifest_metadata_path(install_dir).read_text(encoding="utf-8"))
+ except Exception:
+ continue
+ source = metadata.get("manifest_source")
+ if isinstance(source, str) and source:
+ return source
+ if self.manifest_path is None and self.manifest_url is None:
+ return _PACKAGED_RUNTIME_MANIFEST_SOURCE
+ return None
+
def _manifest_install_dirs_for_command(self, command: list[str]) -> set[Path]:
versions_dir = self.runtime_dir / "versions"
if not versions_dir.is_dir():
return set()
- install_dirs = self._manifest_install_dirs(
- versions_dir,
- manifest_source=_PACKAGED_RUNTIME_MANIFEST_SOURCE,
- )
+ install_dirs = self._manifest_install_dirs(versions_dir)
matching_install_dirs: set[Path] = set()
for command_part in command:
try:
@@ -914,7 +1641,172 @@ class ShowRuntimeManager:
return command
return self._verified_manifest_runtime_command(self._legacy_manifest_install_dir(manifest, archive), manifest, archive, node)
+ @contextlib.contextmanager
+ def _install_guard_locked(self, *, timeout_seconds: float = 0.0):
+ """Serialize installs and archive cleanup, across processes too.
+
+ Yields a ``(acquired, reason)`` pair. ``acquired`` is True when the
+ guard is held; otherwise ``reason`` distinguishes contention
+ (``runtime_install_already_running``) from a guard that cannot exist
+ (``runtime_install_guard_unavailable``: read-only/full directory,
+ symlinked or hard-linked lock file). The outermost caller in this
+ process takes the cross-process file lock; nested calls on the same
+ thread (post-install cleanup runs inside the install) reuse it, so the
+ non-re-entrant ``flock`` never deadlocks against itself.
+ """
+ unavailable = (False, "runtime_install_guard_unavailable")
+ busy = (False, "runtime_install_already_running")
+ with self._install_guard:
+ if self._install_guard_depth > 0:
+ self._install_guard_depth += 1
+ try:
+ yield (True, None)
+ finally:
+ self._install_guard_depth -= 1
+ return
+ # A symlinked lock path would make the lock truncate/rewrite a
+ # file outside the runtime directory; a hard link shares its
+ # inode with unrelated content. Refuse both before any open.
+ try:
+ guard_lstat = self._install_guard_path.lstat()
+ if not _is_exclusive_regular_file(guard_lstat):
+ logger.warning(
+ "Show Runtime install guard %s is a symlink or hard link; refusing to lock",
+ self._install_guard_path,
+ )
+ yield unavailable
+ return
+ except FileNotFoundError:
+ pass
+ except OSError:
+ logger.warning(
+ "Show Runtime install guard %s cannot be inspected; refusing to lock",
+ self._install_guard_path,
+ exc_info=True,
+ )
+ yield unavailable
+ return
+ # Open the guard ourselves with no-follow semantics so a raced
+ # replacement (symlink/hard link swapped in after the lstat) can
+ # never be truncated by MigrationFileLock's append-open; we then
+ # validate the descriptor and hand the same handle's fd to the
+ # lock so validation and locking cover one identical inode.
+ guard_dir = self._install_guard_path.parent
+ try:
+ guard_dir.mkdir(parents=True, exist_ok=True)
+ guard_flags = os.O_RDWR | os.O_CREAT
+ if hasattr(os, "O_NOFOLLOW"):
+ guard_flags |= os.O_NOFOLLOW
+ lock_fd = os.open(self._install_guard_path, guard_flags, 0o644)
+ except OSError as exc:
+ if exc.errno == errno.ELOOP:
+ logger.warning("Show Runtime install guard %s is a symlink; refusing to lock", self._install_guard_path)
+ yield unavailable
+ return
+ logger.warning(
+ "Show Runtime install guard %s is unavailable",
+ self._install_guard_path,
+ exc_info=True,
+ )
+ yield unavailable
+ return
+ try:
+ if not self._guard_path_matches_fd(lock_fd):
+ logger.warning(
+ "Show Runtime install guard descriptor is not an exclusive regular file; refusing",
+ )
+ os.close(lock_fd)
+ yield unavailable
+ return
+ file_lock = MigrationFileLock(self._install_guard_path, timeout_seconds=timeout_seconds)
+ file_lock._handle = os.fdopen(lock_fd, "a+", encoding="utf-8")
+ deadline = time.monotonic() + timeout_seconds
+ while True:
+ file_lock._handle.seek(0)
+ if storage_lock_try_lock(file_lock._handle):
+ file_lock._handle.seek(0)
+ file_lock._handle.truncate()
+ file_lock._handle.write(str(os.getpid()))
+ file_lock._handle.flush()
+ break
+ if time.monotonic() >= deadline:
+ file_lock._handle.close()
+ yield busy
+ return
+ time.sleep(0.1)
+ if not self._guard_path_matches_fd(file_lock._handle.fileno()):
+ logger.warning(
+ "Show Runtime install guard path was replaced after lock acquisition; refusing",
+ )
+ file_lock.release()
+ yield unavailable
+ return
+ except OSError:
+ logger.warning(
+ "Show Runtime install guard %s could not be locked",
+ self._install_guard_path,
+ exc_info=True,
+ )
+ yield unavailable
+ return
+ except OSError:
+ # A lock file that cannot be created/opened (read-only or full
+ # runtime directory) is a structured "cannot serialize" outcome,
+ # never an exception through prepare/clean.
+ logger.warning(
+ "Show Runtime install guard %s is unavailable; treating as busy",
+ self._install_guard_path,
+ exc_info=True,
+ )
+ yield unavailable
+ return
+ self._install_guard_depth = 1
+ try:
+ yield (True, None)
+ finally:
+ self._install_guard_depth = 0
+ try:
+ file_lock.release()
+ except Exception:
+ logger.warning("Failed to release Show Runtime install guard", exc_info=True)
+
def _install_manifest_runtime(self) -> list[str] | None:
+ with self._install_guard_locked() as (acquired, reason):
+ if not acquired:
+ self._install_reason = reason
+ # An untakeable lock (busy or unavailable) must not break a
+ # non-forced prepare that already has a verified install to
+ # reuse. A forced reinstall that cannot run is a failure —
+ # reporting success would hide that the repair never happened.
+ if self.force_install:
+ return None
+ return self._reuse_verified_manifest_command()
+ return self._install_manifest_runtime_locked()
+
+ def _reuse_verified_manifest_command(self) -> list[str] | None:
+ """Best-effort read-only fallback: reuse a verified installed runtime."""
+ try:
+ node = _resolve_node_command()
+ manifest = self._load_runtime_manifest()
+ if not node or not manifest:
+ return None
+ # Mirror the normal install path: an unsupported Node version must
+ # not be reported as a usable runtime.
+ if not self._manifest_node_supported(node, manifest):
+ return None
+ archive = self._manifest_archive_for_platform(manifest)
+ if not archive:
+ return None
+ install_dir = self._manifest_install_dir(manifest, archive)
+ command = self._verified_manifest_runtime_command(install_dir, manifest, archive, node)
+ if not command:
+ legacy_install_dir = self._legacy_manifest_install_dir(manifest, archive)
+ command = self._verified_manifest_runtime_command(legacy_install_dir, manifest, archive, node)
+ return self._reuse_existing_archive_runtime(command)
+ except Exception:
+ return None
+
+ def _install_manifest_runtime_locked(self) -> list[str] | None:
node = _resolve_node_command()
if not node:
self._install_reason = "runtime_node_missing"
diff --git a/docs/plans/bounded-local-storage-growth.md b/docs/plans/bounded-local-storage-growth.md
new file mode 100644
index 000000000..f60fe2da3
--- /dev/null
+++ b/docs/plans/bounded-local-storage-growth.md
@@ -0,0 +1,74 @@
+# Bounded local storage growth — Show Runtime archives & agent trace events
+
+**Status:** In progress (2026-08-17)
+**Owners:** storage workstream
+**Related:** avibe#1506 (feature issue and measured numbers)
+
+## Background
+
+One active installation measured (avibe#1506): 50 archives / ~974 MiB in
+`runtime/show-runtime/downloads` (49 stale, no open handles) and a
+`~/.avibe/state/vibe.sqlite` of ~1.27 GiB dominated by 362k `agent_events`
+rows, of which 361,958 were `visibility='trace'` / `event_type='tool_call'`.
+
+Both are internal runtime artifacts with no lifecycle owner. User-visible
+data (`messages`, deliveries, sessions/runs, Vault audit) is out of scope and
+must never be touched by this work.
+
+## Lane A — Show Runtime archive cache (small, independent)
+
+Code facts that shaped the design:
+
+- The manifest download flow stages into `<sha256>.tmp`, verifies size +
+ full sha256, then atomically renames to `downloads/<sha256>.tgz`
+ (`_resolve_manifest_archive`). A file with the strict content-addressed
+ name is therefore always a completed, verified archive; `.tmp` files and
+ unknown names are never candidates.
+- `current.json` and each install's `.vibe-show-runtime.json` record
+ `archive_sha256`, so the protected set (current + retained rollback
+ installs, following the existing `keep_previous` contract) is exact.
+- `_packaged_runtime_archive` writes a non-sha name — excluded by the strict
+ `<64-hex>.tgz` filter, so the packaged flow's cache is never pruned.
+
+Changes:
+
+- `ShowRuntimeManager.clean(dry_run=...)` now also prunes stale
+ content-addressed archives (strict name + regular file via `lstat`,
+ symlink/unknown/`.tmp` untouched) and reports
+ count/bytes (candidates + removed).
+- `_clean_after_managed_install` runs the same archive cleanup after a
+ successful managed manifest install, inside the existing
+ never-break-prepare guard.
+- `vibe runtime clean --dry-run` previews all removals; `vibe doctor` gained
+ a read-only archive-cache item (`show_runtime.archive_cache_reclaimable`).
+
+## Lane B — agent_events trace retention (storage-owned)
+
+Design decisions:
+
+- One retention owner: a new `storage/agent_events_retention.py`. Call sites
+ (controller daily task, CLI) never write ad hoc deletes.
+- Eligibility is a single property predicate: `event_type='tool_call' AND
+ visibility='trace' AND created_at < cutoff` (default 30 days, configurable,
+ explicit opt-out). Everything else — messages, non-trace events, newer
+ traces — is preserved by construction.
+- Alembic partial index on `created_at WHERE event_type='tool_call' AND
+ visibility='trace'` keeps the age scan bounded.
+- Deletes run in small batches in per-batch transactions (WAL allows
+ concurrent writers between batches); a persistent `state_meta` marker
+ throttles runs to at most once per day and serializes concurrent runners.
+- Physical compaction only after a preflight (free disk > db + WAL + margin,
+ checkpoint first); otherwise deferred with a reported reason. Never an
+ automatic VACUUM that can exhaust a nearly-full volume.
+- Trigger: controller background task (daily check via marker) + manual CLI
+ with dry-run/status; never in user request hot paths.
+
+## Todos
+
+- [x] Lane A implementation + tests (`tests/test_show_runtime_archive_cleanup.py`)
+- [ ] Lane A PR review loop
+- [x] Lane A user docs: `vibe runtime clean` / `--dry-run` en + zh (avibe-bot/avibe-docs#24)
+- [ ] Lane B migration (partial index) — next alembic head after `20260817_0055`
+- [ ] Lane B retention service + controller task + CLI + tests
+- [ ] Lane B PR review loop
+- [ ] avibe-docs: en/zh docs for trace retention (ships with lane B)
diff --git a/storage/lock.py b/storage/lock.py
index d75b71559..1baddd90a 100644
--- a/storage/lock.py
+++ b/storage/lock.py
@@ -250,3 +250,35 @@ def _unlock(handle) -> None:
import fcntl
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
+
+
+def fcntl_available() -> bool:
+ try:
+ import fcntl # noqa: F401
+ except ImportError:
+ return False
+ return True
+
+
+def try_windows_exclusive_lock(fd: int) -> bool:
+ """Non-blocking exclusive probe on an already-open Windows lock fd."""
+ try:
+ import msvcrt
+ except ImportError:
+ return False
+ try:
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
+ except OSError:
+ return False
+ return True
+
+
+def unlock_windows_exclusive_lock(fd: int) -> None:
+ try:
+ import msvcrt
+ except ImportError:
+ return
+ try:
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
+ except OSError:
+ pass
diff --git a/tests/test_managed_runtime.py b/tests/test_managed_runtime.py
index b04da5780..3e2013a88 100644
--- a/tests/test_managed_runtime.py
+++ b/tests/test_managed_runtime.py
@@ -4,6 +4,7 @@ import ast
import hashlib
import io
import json
+import os
import tarfile
from pathlib import Path
@@ -23,6 +24,161 @@ class FixtureRuntimeManager(ManagedRuntimeManager):
return binary.read_text(encoding="utf-8").strip()
+def test_clean_dry_run_is_read_only_and_creates_no_lock(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ runtime_dir = tmp_path / "git-runtime"
+ versions = runtime_dir / "versions" / "v1" / "linux-x64" / "aaa"
+ versions.mkdir(parents=True)
+ manager = GitRuntimeManager(
+ runtime_dir=runtime_dir,
+ manifest_path=tmp_path / "missing-manifest.json",
+ offline=True,
+ )
+ (versions / manager.spec.metadata_filename).write_text("{}", encoding="utf-8")
+
+ result = manager.clean(dry_run=True)
+
+ assert result["ok"] is True
+ assert not (runtime_dir / ".install.lock").exists()
+
+
+def test_clean_dry_run_reports_inspection_failure(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ manager = GitRuntimeManager(
+ runtime_dir=tmp_path / "git-runtime",
+ manifest_path=tmp_path / "missing-manifest.json",
+ offline=True,
+ )
+
+ def _boom(*, keep_previous, dry_run=False, removed=None):
+ raise OSError("disk unreadable")
+
+ monkeypatch.setattr(manager, "_clean_locked", _boom)
+ result = manager.clean(dry_run=True)
+
+ assert result["ok"] is False
+ assert result["reason"] == "git_clean_inspection_failed"
+ assert "disk unreadable" in result["message"]
+
+
+def test_clean_reports_inspection_failure_on_real_run(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ manager = GitRuntimeManager(
+ runtime_dir=tmp_path / "git-runtime",
+ manifest_path=tmp_path / "missing-manifest.json",
+ offline=True,
+ )
+
+ def _boom(*, keep_previous, dry_run=False, removed=None):
+ raise OSError("disk unreadable")
+
+ monkeypatch.setattr(manager, "_clean_locked", _boom)
+ result = manager.clean()
+
+ assert result["ok"] is False
+ assert result["reason"] == "git_clean_inspection_failed"
+ assert "disk unreadable" in result["message"]
+
+
+def test_clean_dry_run_holds_preview_guard_through_planning(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ runtime_dir = tmp_path / "git-runtime"
+ runtime_dir.mkdir()
+ (runtime_dir / ".install.lock").write_text("", encoding="utf-8")
+ manager = GitRuntimeManager(
+ runtime_dir=runtime_dir,
+ manifest_path=tmp_path / "missing-manifest.json",
+ offline=True,
+ )
+ seen: dict[str, object] = {}
+ real_clean_locked = manager._clean_locked
+
+ def _observe(*, keep_previous, dry_run=False, removed=None):
+ seen["held_lock"] = getattr(manager, "_preview_held_install_lock", False)
+ seen["fd"] = getattr(manager, "_preview_guard_fd", None)
+ seen["lock_busy"] = not manager._install_lock.acquire(blocking=False)
+ if seen["lock_busy"] is False:
+ manager._install_lock.release()
+ return real_clean_locked(keep_previous=keep_previous, dry_run=dry_run, removed=removed)
+
+ monkeypatch.setattr(manager, "_clean_locked", _observe)
+ result = manager.clean(dry_run=True)
+
+ assert result["ok"] is True
+ assert seen["held_lock"] is True
+ assert seen["lock_busy"] is True
+ assert getattr(manager, "_preview_held_install_lock", False) is False
+ assert getattr(manager, "_preview_guard_fd", None) is None
+ assert manager._install_lock.acquire(blocking=False)
+ manager._install_lock.release()
+
+
+def test_windows_preview_detects_held_git_lock(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ runtime_dir = tmp_path / "git-runtime"
+ runtime_dir.mkdir()
+ (runtime_dir / ".install.lock").write_text("", encoding="utf-8")
+ manager = GitRuntimeManager(
+ runtime_dir=runtime_dir,
+ manifest_path=tmp_path / "missing-manifest.json",
+ offline=True,
+ )
+ monkeypatch.setattr("core.managed_runtime.fcntl_available", lambda: False)
+ monkeypatch.setattr("core.managed_runtime.try_windows_exclusive_lock", lambda fd: False)
+ result = manager.clean(dry_run=True)
+ assert result["ok"] is False
+ assert result["reason"] == "git_install_already_running"
+
+
+def test_git_preview_refuses_lock_identity_mismatch(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)
+ runtime_dir = tmp_path / "git-runtime"
+ runtime_dir.mkdir()
+ lock_path = runtime_dir / ".install.lock"
+ lock_path.write_text("", encoding="utf-8")
+ manager = GitRuntimeManager(
+ runtime_dir=runtime_dir,
+ manifest_path=tmp_path / "missing-manifest.json",
+ offline=True,
+ )
+ real_lstat = Path.lstat
+ mismatch = {"on": False}
+
+ def _lstat(self):
+ info = real_lstat(self)
+ if mismatch["on"] and self == lock_path:
+ fields = list(info)
+ fields[1] = info.st_ino + 51
+ return os.stat_result(fields)
+ return info
+
+ def _fstat(fd):
+ mismatch["on"] = True
+ return real_fstat(fd)
+
+ real_fstat = os.fstat
+ monkeypatch.setattr(Path, "lstat", _lstat)
+ monkeypatch.setattr(os, "fstat", _fstat)
+ result = manager.clean(dry_run=True)
+ assert result["ok"] is False
+ assert result["reason"] == "git_install_already_running"
+
+
def test_shared_ensure_failure_vocabulary_matches_reachable_reason_literals() -> None:
module = ast.parse(Path("core/managed_runtime.py").read_text(encoding="utf-8"))
manager = next(
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 1dd4ffb10..18d4549fc 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -193,15 +193,16 @@ def test_runtime_clean_cleans_git_runtime(monkeypatch, capsys):
args = parser.parse_args(["runtime", "clean", "--json", "--keep-previous", "2"])
class FakeRuntimeManager:
- def clean(self, *, keep_previous=1):
+ def clean(self, *, keep_previous=1, dry_run=False):
assert keep_previous == 2
- return {"ok": True, "removed": ["show-old"]}
+ assert dry_run is False
+ return {"ok": True, "removed": ["show-old"], "archives": {"removed_count": 0}}
monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
monkeypatch.setattr(
cli,
"_clean_git_runtime",
- lambda *, keep_previous: {"ok": True, "removed": [f"git-old-{keep_previous}"]},
+ lambda *, keep_previous, dry_run=False: {"ok": True, "removed": [f"git-old-{keep_previous}"], "dry_run": dry_run},
)
assert cli.cmd_runtime(args) == 0
diff --git a/tests/test_show_runtime_archive_cleanup.py b/tests/test_show_runtime_archive_cleanup.py
new file mode 100644
index 000000000..930e70857
--- /dev/null
+++ b/tests/test_show_runtime_archive_cleanup.py
@@ -0,0 +1,1221 @@
+"""Show Runtime content-addressed archive cache cleanup (avibe#1506 lane A).
+
+Covers bounding ``runtime/show-runtime/downloads/`` growth: protected
+current/rollback archives survive, stale content-addressed archives are
+reclaimed, unknown/symlink/temp files are never touched, dry-run reports
+without deleting, and the post-install hook prunes stale archives.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+from pathlib import Path
+
+import pytest
+
+from core.show_runtime import ShowRuntimeManager
+
+
+def _make_manager(tmp_path: Path) -> ShowRuntimeManager:
+ return ShowRuntimeManager(runtime_dir=tmp_path / "show-runtime", offline=True)
+
+
+def _write_archive(manager: ShowRuntimeManager, sha256: str, payload: bytes, *, age_seconds: float = 3600) -> Path:
+ downloads = manager.runtime_dir / "downloads"
+ downloads.mkdir(parents=True, exist_ok=True)
+ path = downloads / f"{sha256}.tgz"
+ path.write_bytes(payload)
+ stamp = time.time() - age_seconds
+ os.utime(path, (stamp, stamp))
+ return path
+
+
+def _sha(index: int) -> str:
+ return f"{index:064x}"
+
+
+def _write_current_pointer(manager: ShowRuntimeManager, sha256: str, install_dir: Path | None = None) -> None:
+ manager.runtime_dir.mkdir(parents=True, exist_ok=True)
+ pointer = {
+ "provider": "manifest-cache",
+ "runtime_version": "v1",
+ "platform": "test",
+ "install_dir": str(install_dir or manager.runtime_dir / "versions" / "v1" / "test" / "abc123"),
+ "manifest_sha256": "m" * 64,
+ "archive_sha256": sha256,
+ }
+ (manager.runtime_dir / "current.json").write_text(json.dumps(pointer), encoding="utf-8")
+
+
+def _write_install_metadata(manager: ShowRuntimeManager, *, version: str, sha256: str, mtime: float) -> Path:
+ install_dir = manager.runtime_dir / "versions" / version / "test" / version[::-1][:8]
+ install_dir.mkdir(parents=True, exist_ok=True)
+ metadata = {
+ "provider": "manifest-cache",
+ "manifest_sha256": "m" * 64,
+ "runtime_version": version,
+ "platform": "test",
+ "archive_name": "vibe-show-runtime-node-test.tgz",
+ "archive_sha256": sha256,
+ "manifest_source": "package:vibe/show-runtime-manifest.json",
+ }
+ metadata_path = install_dir / ".vibe-show-runtime.json"
+ metadata_path.write_text(json.dumps(metadata), encoding="utf-8")
+ stamp = time.time() + mtime
+ os.utime(metadata_path, (stamp, stamp))
+ os.utime(install_dir, (stamp, stamp))
+ return install_dir
+
+
+def test_clean_removes_stale_archives_and_keeps_current_plus_rollback(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ current_sha, rollback_sha, stale_one_sha, stale_two_sha = _sha(1), _sha(2), _sha(3), _sha(4)
+ rollback_install = _write_install_metadata(manager, version="v1", sha256=rollback_sha, mtime=-7200)
+ current_install = _write_install_metadata(manager, version="v2", sha256=current_sha, mtime=0)
+ _write_current_pointer(manager, current_sha, install_dir=current_install)
+
+ current_archive = _write_archive(manager, current_sha, b"current")
+ rollback_archive = _write_archive(manager, rollback_sha, b"rollback")
+ stale_one = _write_archive(manager, stale_one_sha, b"one")
+ stale_two = _write_archive(manager, stale_two_sha, b"two")
+
+ result = manager.clean()
+
+ archives = result["archives"]
+ assert archives["removed_count"] == 2
+ assert archives["removed_bytes"] == len(b"one") + len(b"two")
+ assert archives["protected_count"] == 2
+ assert current_archive.exists() and rollback_archive.exists()
+ assert not stale_one.exists() and not stale_two.exists()
+ assert current_install.exists() and rollback_install.exists()
+
+
+def test_clean_dry_run_reports_candidates_without_deleting(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(1), b"current")
+ stale = _write_archive(manager, _sha(2), b"stale")
+
+ result = manager.clean(dry_run=True)
+
+ archives = result["archives"]
+ assert result["dry_run"] is True
+ assert archives["candidate_count"] == 1
+ assert archives["candidate_bytes"] == len(b"stale")
+ assert archives["removed_count"] == 0
+ assert stale.exists()
+
+
+def test_archive_cleanup_never_touches_unknown_symlink_or_tmp_files(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+
+ stale = _write_archive(manager, _sha(2), b"stale")
+ packaged = manager.runtime_dir / "downloads" / "vibe-show-runtime-node-test.tgz"
+ packaged.write_bytes(b"packaged")
+ temp_download = manager.runtime_dir / "downloads" / f"{_sha(3)}.tmp"
+ temp_download.write_bytes(b"partial")
+ notes = manager.runtime_dir / "downloads" / "notes.txt"
+ notes.write_text("keep me", encoding="utf-8")
+ outside = tmp_path / "outside.txt"
+ outside.write_text("target", encoding="utf-8")
+ symlink = manager.runtime_dir / "downloads" / f"{_sha(4)}.tgz"
+ symlink.symlink_to(outside)
+ directory = manager.runtime_dir / "downloads" / f"{_sha(5)}.tgz"
+ directory.mkdir()
+ unknown_claim = manager.runtime_dir / "downloads" / "backup.tgz.avibe-removing"
+ unknown_claim.write_bytes(b"not ours")
+ newline_archive = manager.runtime_dir / "downloads" / f"{_sha(6)}.tgz\n"
+ newline_archive.write_bytes(b"newline")
+ newline_claim = manager.runtime_dir / "downloads" / f"{_sha(7)}.tgz.avibe-removing\n"
+ newline_claim.write_bytes(b"newline-claim")
+
+ result = manager.clean()
+
+ assert result["archives"]["removed_count"] == 1
+ assert not stale.exists()
+ assert packaged.exists() and temp_download.exists() and notes.exists()
+ assert symlink.is_symlink() and outside.exists()
+ assert directory.is_dir()
+ assert unknown_claim.exists()
+ assert newline_archive.exists()
+ assert newline_claim.exists()
+
+
+def test_clean_is_idempotent_for_archives(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(1), b"current")
+ _write_archive(manager, _sha(2), b"stale")
+
+ first = manager.clean()
+ second = manager.clean()
+
+ assert first["archives"]["removed_count"] == 1
+ assert second["archives"]["removed_count"] == 0
+ assert second["archives"]["candidate_count"] == 0
+
+
+def test_clean_after_managed_install_prunes_stale_archives(tmp_path: Path) -> None:
+ manager = ShowRuntimeManager(runtime_dir=tmp_path / "show-runtime", offline=True, runtime_source="manifest-cache")
+ current_install = _write_install_metadata(manager, version="v2", sha256=_sha(1), mtime=0)
+ _write_current_pointer(manager, _sha(1), install_dir=current_install)
+ current_archive = _write_archive(manager, _sha(1), b"current")
+ stale = _write_archive(manager, _sha(2), b"stale")
+
+ manager._clean_after_managed_install(["node", str(current_install / "cli.js")])
+
+ assert current_archive.exists() # current archive intact
+ assert not stale.exists()
+
+
+def test_clean_after_custom_manifest_install_prunes_stale_installs(tmp_path: Path) -> None:
+ manifest_path = tmp_path / "custom-manifest.json"
+ manifest_path.write_text("{}", encoding="utf-8")
+ manager = ShowRuntimeManager(
+ runtime_dir=tmp_path / "show-runtime",
+ offline=True,
+ runtime_source="manifest-cache",
+ manifest_path=manifest_path,
+ )
+ def _retag(install_dir: Path) -> None:
+ metadata_path = next(install_dir.rglob(".vibe-show-runtime.json"))
+ payload = json.loads(metadata_path.read_text(encoding="utf-8"))
+ payload["manifest_source"] = str(manifest_path)
+ metadata_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ current_install = _write_install_metadata(manager, version="v2", sha256=_sha(1), mtime=0)
+ rollback_install = _write_install_metadata(manager, version="v1", sha256=_sha(8), mtime=-3600)
+ stale_install = _write_install_metadata(manager, version="v0", sha256=_sha(9), mtime=-999999)
+ _retag(current_install)
+ _retag(rollback_install)
+ _retag(stale_install)
+ _write_current_pointer(manager, _sha(1), install_dir=current_install)
+ current_archive = _write_archive(manager, _sha(1), b"current")
+ rollback_archive = _write_archive(manager, _sha(8), b"rollback")
+ stale_archive = _write_archive(manager, _sha(9), b"stale-custom")
+
+ manager._clean_after_managed_install(["node", str(current_install / "cli.js")])
+
+ assert current_archive.exists() and current_install.exists()
+ assert rollback_archive.exists() and rollback_install.exists()
+ assert not stale_install.exists() and not stale_archive.exists()
+
+
+def test_clean_after_custom_manifest_prunes_obsolete_sources(tmp_path: Path) -> None:
+ old_manifest = tmp_path / "old-manifest.json"
+ new_manifest = tmp_path / "new-manifest.json"
+ old_manifest.write_text("{}", encoding="utf-8")
+ new_manifest.write_text("{}", encoding="utf-8")
+ manager = ShowRuntimeManager(
+ runtime_dir=tmp_path / "show-runtime",
+ offline=True,
+ runtime_source="manifest-cache",
+ manifest_path=new_manifest,
+ )
+
+ def _retag(install_dir: Path, source: str) -> None:
+ metadata_path = next(install_dir.rglob(".vibe-show-runtime.json"))
+ payload = json.loads(metadata_path.read_text(encoding="utf-8"))
+ payload["manifest_source"] = source
+ metadata_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ current_install = _write_install_metadata(manager, version="v2", sha256=_sha(1), mtime=0)
+ rollback_install = _write_install_metadata(manager, version="v1", sha256=_sha(8), mtime=-3600)
+ stale_install = _write_install_metadata(manager, version="v0", sha256=_sha(9), mtime=-999999)
+ _retag(current_install, str(new_manifest))
+ _retag(rollback_install, str(old_manifest))
+ _retag(stale_install, str(old_manifest))
+ _write_current_pointer(manager, _sha(1), install_dir=current_install)
+ current_archive = _write_archive(manager, _sha(1), b"current")
+ rollback_archive = _write_archive(manager, _sha(8), b"rollback")
+ stale_archive = _write_archive(manager, _sha(9), b"stale-old-source")
+
+ manager._clean_after_managed_install(["node", str(current_install / "cli.js")])
+
+ assert current_archive.exists() and current_install.exists()
+ assert rollback_archive.exists() and rollback_install.exists()
+ assert not stale_install.exists() and not stale_archive.exists()
+
+
+def test_archive_cache_status_is_read_only(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(1), b"current")
+ stale = _write_archive(manager, _sha(2), b"stale")
+
+ report = manager.archive_cache_status()
+
+ assert report["candidate_count"] == 1
+ assert report["candidate_bytes"] == len(b"stale")
+ assert stale.exists()
+
+
+def test_recent_unprotected_archive_survives_mtime_guard(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ fresh_unprotected = _write_archive(manager, _sha(2), b"just downloaded", age_seconds=0)
+
+ result = manager.clean()
+
+ # Another process may have finalized this archive moments ago and not yet
+ # written install metadata; the safety window must keep it.
+ assert result["archives"]["removed_count"] == 0
+ assert fresh_unprotected.exists()
+
+
+def test_dry_run_preview_includes_archives_of_stale_install_dirs(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ # Current install (v2), retained rollback install (v1), stale install (v0)
+ # whose only protection is its own metadata.
+ current_install = _write_install_metadata(manager, version="v2", sha256=_sha(1), mtime=0)
+ _write_current_pointer(manager, _sha(1), install_dir=current_install)
+ _write_install_metadata(manager, version="v1", sha256=_sha(8), mtime=-3600)
+ stale_install = _write_install_metadata(manager, version="v0", sha256=_sha(9), mtime=-999999)
+ _write_archive(manager, _sha(1), b"current")
+ _write_archive(manager, _sha(8), b"rollback")
+ stale_archive = _write_archive(manager, _sha(9), b"stale-install-archive")
+
+ dry = manager.clean(dry_run=True)
+ assert dry["archives"]["candidate_count"] == 1
+ assert dry["archives"]["candidate_bytes"] == len(b"stale-install-archive")
+ assert stale_install.exists() and stale_archive.exists() # dry run removed nothing
+
+ real = manager.clean()
+ # A real run removes the stale install dir and its archive together, while
+ # the current and rollback archives stay protected in both modes.
+ assert real["archives"]["removed_count"] == 1
+ assert not stale_install.exists() and not stale_archive.exists()
+ assert (manager.runtime_dir / "downloads" / f"{_sha(1)}.tgz").exists()
+ assert (manager.runtime_dir / "downloads" / f"{_sha(8)}.tgz").exists()
+
+
+def test_cli_clean_dry_run_is_read_only_for_git_runtime(monkeypatch, capsys) -> None:
+ from vibe import cli as vibe_cli
+
+ parser = vibe_cli.build_parser()
+ args = parser.parse_args(["runtime", "clean", "--dry-run", "--json"])
+
+ class FakeRuntimeManager:
+ def clean(self, *, keep_previous=1, dry_run=False):
+ return {"ok": True, "dry_run": dry_run, "removed": [], "archives": {"candidate_count": 0}}
+
+ git_calls: list[dict] = []
+
+ def fake_git_clean(*, keep_previous, dry_run=False):
+ git_calls.append({"keep_previous": keep_previous, "dry_run": dry_run})
+ return {"ok": True, "removed": ["git-stale"]}
+
+ monkeypatch.setattr(vibe_cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ monkeypatch.setattr(vibe_cli, "_clean_git_runtime", fake_git_clean)
+
+ assert vibe_cli.cmd_runtime(args) == 0
+ assert git_calls == [{"keep_previous": 1, "dry_run": True}]
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["dry_run"] is True
+ assert payload["git"]["removed"] == ["git-stale"]
+
+
+def test_cleanup_reuses_install_guard_without_deadlock(tmp_path: Path) -> None:
+ """The post-install cleanup runs inside the installer's guard.
+
+ ``flock`` is not re-entrant across file handles, so this exercises the
+ depth-counted reuse: cleaning while the guard is held must complete and
+ actually remove stale archives instead of timing out.
+ """
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(1), b"current")
+ stale = _write_archive(manager, _sha(2), b"stale")
+
+ with manager._install_guard_locked():
+ result = manager._clean_downloaded_archives()
+
+ assert result["removed_count"] == 1
+ assert not stale.exists()
+
+
+def test_cleanup_skips_while_foreign_process_holds_install_guard(tmp_path: Path) -> None:
+ from storage.lock import MigrationFileLock
+
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ stale = _write_archive(manager, _sha(2), b"stale")
+
+ foreign = MigrationFileLock(manager.runtime_dir / ".install.lock", timeout_seconds=0)
+ foreign.acquire()
+ try:
+ result = manager._clean_downloaded_archives()
+ finally:
+ foreign.release()
+
+ assert result["removed_count"] == 0
+ assert result["skipped_reason"] == "runtime_install_already_running"
+ assert stale.exists()
+
+
+def test_archive_cache_status_is_read_only_and_creates_no_lock(tmp_path: Path) -> None:
+ """Doctor/status previews must not create or rewrite runtime state."""
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(2), b"stale")
+
+ report = manager.archive_cache_status()
+
+ assert report["candidate_count"] == 1
+ assert not (manager.runtime_dir / ".install.lock").exists()
+
+
+def test_cleanup_reports_inspection_failure_distinct_from_lock_contention(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+
+ def _boom(skip_metadata_under=None):
+ raise OSError("disk unreadable")
+
+ original = manager._protected_archive_sha256s
+ manager._protected_archive_sha256s = _boom
+ try:
+ result = manager._clean_downloaded_archives()
+ finally:
+ manager._protected_archive_sha256s = original
+
+ assert result["skipped_reason"] == "archive_inspection_failed"
+
+
+def test_archive_cleanup_outcomes_are_fully_rendered_everywhere() -> None:
+ """Enumeration pin: every report outcome/reason must render distinctly.
+
+ A new outcome or skip reason that the CLI/Doctor forgot to wire fails this
+ test instead of silently rendering placeholder counts.
+ """
+ from core import show_runtime as module
+ from vibe import cli as vibe_cli
+
+ reasons = {
+ module._SKIPPED_ARCHIVE_REASON_INSTALL_RUNNING,
+ module._SKIPPED_ARCHIVE_REASON_INSPECTION_FAILED,
+ module._SKIPPED_ARCHIVE_REASON_REMOVAL_FAILED,
+ }
+ # Every skip reason produces a non-empty localized skip line.
+ language = "en"
+ rendered = set()
+ for reason in reasons:
+ message = vibe_cli.i18n_t("runtime.clean.skipped", language, reason=reason)
+ assert message and message != "runtime.clean.skipped"
+ assert reason in message
+ rendered.add(message)
+ assert len(rendered) == len(reasons)
+ # Inspection failures carry different remediation from lock contention.
+ wait_action = vibe_cli.i18n_t("runtime.doctor.archiveCacheSkippedAction", language)
+ inspect_action = vibe_cli.i18n_t("runtime.doctor.archiveCacheSkippedInspectionAction", language)
+ assert wait_action and inspect_action and wait_action != inspect_action
+ # Partial removals report the failed count.
+ partial = vibe_cli.i18n_t("runtime.clean.partiallyRemoved", language, failed=3)
+ assert "3" in partial and partial != "runtime.clean.partiallyRemoved"
+ # The outcome vocabulary stays closed.
+ assert module._ARCHIVE_CLEANUP_OUTCOMES == frozenset({"cleaned", "partial", "skipped"})
+
+
+def test_unreadable_retained_install_metadata_aborts_cleanup(tmp_path: Path) -> None:
+ """A rollback install with malformed metadata must protect its archive."""
+ manager = _make_manager(tmp_path)
+ current_install = _write_install_metadata(manager, version="v2", sha256=_sha(1), mtime=0)
+ _write_current_pointer(manager, _sha(1), install_dir=current_install)
+ _write_install_metadata(manager, version="v1", sha256=_sha(8), mtime=-3600)
+ (manager.runtime_dir / "versions" / "v1" / "test").mkdir(parents=True, exist_ok=True)
+ # Corrupt the retained rollback install's metadata after writing it.
+ rollback_dir = manager.runtime_dir / "versions" / "v1"
+ for metadata in rollback_dir.rglob(".vibe-show-runtime.json"):
+ metadata.write_text("{ not json", encoding="utf-8")
+ _write_archive(manager, _sha(1), b"current")
+ rollback_archive = _write_archive(manager, _sha(8), b"rollback")
+
+ result = manager.clean()
+
+ assert result["archives"]["skipped_reason"] == "archive_inspection_failed"
+ assert rollback_archive.exists()
+
+
+def test_archive_removal_failures_are_reported(tmp_path: Path, monkeypatch) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(2), b"stale")
+
+ real_unlink = os.unlink
+
+ def _unlink_boom(path, *args, **kwargs):
+ raise OSError("read-only filesystem")
+
+ real_remove = Path.unlink
+ monkeypatch.setattr(Path, "unlink", _unlink_boom)
+ monkeypatch.setattr("os.unlink", _unlink_boom)
+ try:
+ result = manager.clean()
+ finally:
+ monkeypatch.setattr(Path, "unlink", real_remove)
+ monkeypatch.setattr("os.unlink", real_unlink)
+
+ assert result["archives"]["skipped_reason"] == "archive_removal_failed"
+ assert result["archives"]["outcome"] == "skipped"
+ assert result["archives"]["candidate_count"] == 1
+
+
+def test_archive_cache_status_handles_stale_install_plan_paths(tmp_path: Path) -> None:
+ """Doctor status must convert the stale-plan strings back to Paths."""
+ manager = _make_manager(tmp_path)
+ current_install = _write_install_metadata(manager, version="v2", sha256=_sha(1), mtime=0)
+ _write_current_pointer(manager, _sha(1), install_dir=current_install)
+ _write_install_metadata(manager, version="v1", sha256=_sha(8), mtime=-3600)
+ _write_install_metadata(manager, version="v0", sha256=_sha(9), mtime=-999999)
+ _write_archive(manager, _sha(1), b"current")
+ stale_archive = _write_archive(manager, _sha(9), b"stale")
+
+ report = manager.archive_cache_status()
+
+ assert report.get("skipped_reason") != "archive_inspection_failed"
+ assert report["candidate_count"] == 1
+ assert stale_archive.exists()
+
+
+def test_install_guard_unavailable_falls_back_to_verified_install(tmp_path: Path, monkeypatch) -> None:
+ """A read-only runtime dir must not turn a verified install into a failure."""
+ from core import show_runtime as module
+
+ monkeypatch.setattr(module, "_runtime_platform_tag", lambda: "test")
+ monkeypatch.setattr(module, "_resolve_node_command", lambda: ["node"])
+ manifest_payload = {
+ "schema_version": 1,
+ "runtime_version": "v2",
+ "archives": {
+ "test": {
+ "name": "vibe-show-runtime-node-test.tgz",
+ "url": f"file://{tmp_path}/v2.tgz",
+ "sha256": _sha(1),
+ }
+ },
+ }
+ manifest_path = tmp_path / "manifest.json"
+ manifest_path.write_text(json.dumps(manifest_payload), encoding="utf-8")
+ manager = ShowRuntimeManager(
+ runtime_dir=tmp_path / "show-runtime",
+ offline=True,
+ runtime_source="manifest-cache",
+ manifest_path=manifest_path,
+ )
+ manifest = manager._load_runtime_manifest()
+ assert manifest is not None
+ archive = manifest.archives["test"]
+ install_dir = manager._manifest_install_dir(manifest, archive)
+ install_dir.mkdir(parents=True, exist_ok=True)
+ (install_dir / ".vibe-show-runtime.json").write_text(
+ json.dumps(
+ {
+ "provider": "manifest-cache",
+ "manifest_sha256": manifest.digest,
+ "runtime_version": manifest.runtime_version,
+ "platform": "test",
+ "archive_name": archive.name,
+ "archive_sha256": archive.sha256,
+ }
+ ),
+ encoding="utf-8",
+ )
+ cli_path = install_dir / "node_modules" / "@avibe" / "show-runtime" / "dist" / "cli.js"
+ cli_path.parent.mkdir(parents=True, exist_ok=True)
+ cli_path.write_text("runtime", encoding="utf-8")
+
+ def _unwritable_open(path, flags, *args, **kwargs):
+ if Path(path) == manager.runtime_dir / ".install.lock":
+ raise OSError("read-only filesystem")
+ return real_open(path, flags, *args, **kwargs)
+
+ real_open = os.open
+ monkeypatch.setattr(os, "open", _unwritable_open)
+
+ command = manager._install_manifest_runtime()
+
+ assert command is not None and command[-1].endswith("cli.js")
+
+
+def test_partial_removal_reports_removed_and_failed_counts(monkeypatch, capsys) -> None:
+ from vibe import cli as vibe_cli
+
+ parser = vibe_cli.build_parser()
+ args = parser.parse_args(["runtime", "clean"])
+
+ class FakeRuntimeManager:
+ def clean(self, *, keep_previous=1, dry_run=False):
+ return {
+ "ok": True,
+ "removed": [],
+ "archives": {
+ "outcome": "partial",
+ "candidate_count": 3,
+ "removed_count": 2,
+ "removed_bytes": 2048,
+ "failed_count": 1,
+ "skipped_reason": "archive_removal_failed",
+ },
+ }
+
+ monkeypatch.setattr(vibe_cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ monkeypatch.setattr(
+ vibe_cli,
+ "_clean_git_runtime",
+ lambda *, keep_previous, dry_run=False: {"ok": True, "removed": []},
+ )
+
+ assert vibe_cli.cmd_runtime(args) == 0
+ captured = capsys.readouterr()
+ assert "2" in captured.out # successful removal total still reported
+ assert "1" in captured.err # failed count reported as a warning
+
+
+def test_dry_run_with_candidates_previews_without_partial_warning(monkeypatch, capsys) -> None:
+ from vibe import cli as vibe_cli
+
+ parser = vibe_cli.build_parser()
+ args = parser.parse_args(["runtime", "clean", "--dry-run"])
+
+ class FakeRuntimeManager:
+ def clean(self, *, keep_previous=1, dry_run=False):
+ assert dry_run is True
+ return {
+ "ok": True,
+ "removed": [],
+ "archives": {
+ "outcome": "partial",
+ "candidate_count": 3,
+ "candidate_bytes": 3072,
+ "removed_count": 0,
+ "removed_bytes": 0,
+ "failed_count": 0,
+ },
+ }
+
+ monkeypatch.setattr(vibe_cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ monkeypatch.setattr(
+ vibe_cli,
+ "_clean_git_runtime",
+ lambda *, keep_previous, dry_run=False: {"ok": True, "removed": []},
+ )
+
+ assert vibe_cli.cmd_runtime(args) == 0
+ captured = capsys.readouterr()
+ assert "3" in captured.out and "3.0 KiB" in captured.out # candidate preview rendered
+ assert captured.err == "" # no bogus partial-removal warning in a preview
+
+
+def test_archive_cache_status_reports_stale_plan_failure(tmp_path: Path, monkeypatch) -> None:
+ """A stale-plan phase failure returns the structured inspection report."""
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+
+ def _boom(*args, **kwargs):
+ raise OSError("directory disappeared")
+
+ monkeypatch.setattr(manager, "_clean_manifest_install_dirs", _boom)
+ report = manager.archive_cache_status()
+
+ assert report.get("skipped_reason") == "archive_inspection_failed"
+
+
+def test_candidate_stat_failure_is_an_inspection_failure(tmp_path: Path, monkeypatch) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(2), b"stale")
+
+ import errno
+
+ def _stat_boom(self):
+ raise OSError(errno.EIO, "I/O error")
+
+ monkeypatch.setattr(Path, "lstat", _stat_boom)
+ result = manager.clean()
+
+ assert result["archives"].get("skipped_reason") == "archive_inspection_failed"
+
+
+def test_forced_prepare_fails_structured_when_guard_unavailable(tmp_path: Path, monkeypatch) -> None:
+ from core import show_runtime as module
+
+ monkeypatch.setattr(module, "_runtime_platform_tag", lambda: "test")
+ monkeypatch.setattr(module, "_resolve_node_command", lambda: ["node"])
+ manifest_payload = {
+ "schema_version": 1,
+ "runtime_version": "v2",
+ "archives": {"test": {"name": "n.tgz", "url": "file:///n.tgz", "sha256": _sha(1)}},
+ }
+ manifest_path = tmp_path / "manifest.json"
+ manifest_path.write_text(json.dumps(manifest_payload), encoding="utf-8")
+ manager = ShowRuntimeManager(
+ runtime_dir=tmp_path / "show-runtime",
+ offline=True,
+ runtime_source="manifest-cache",
+ manifest_path=manifest_path,
+ force_install=True,
+ )
+
+ import builtins
+
+ real_open = builtins.open if False else os.open
+
+ def _unwritable_open(p, flags, *args, **kwargs):
+ if isinstance(p, Path) and p.name == ".install.lock":
+ raise OSError("read-only filesystem")
+ return real_open(p, flags, *args, **kwargs)
+
+ monkeypatch.setattr("os.open", _unwritable_open)
+
+ command = manager._install_manifest_runtime()
+
+ assert command is None
+ assert manager._install_reason == "runtime_install_guard_unavailable"
+
+
+def test_lock_fallback_enforces_manifest_node_requirement(tmp_path: Path, monkeypatch) -> None:
+ from core import show_runtime as module
+
+ monkeypatch.setattr(module, "_runtime_platform_tag", lambda: "test")
+ monkeypatch.setattr(module, "_resolve_node_command", lambda: ["node"])
+ manifest_payload = {
+ "schema_version": 1,
+ "runtime_version": "v2",
+ "minimum_node": "99.0.0",
+ "archives": {"test": {"name": "n.tgz", "url": "file:///n.tgz", "sha256": _sha(1)}},
+ }
+ manifest_path = tmp_path / "manifest.json"
+ manifest_path.write_text(json.dumps(manifest_payload), encoding="utf-8")
+ manager = ShowRuntimeManager(
+ runtime_dir=tmp_path / "show-runtime",
+ offline=True,
+ runtime_source="manifest-cache",
+ manifest_path=manifest_path,
+ )
+ manifest = manager._load_runtime_manifest()
+ assert manifest is not None
+ archive = manifest.archives["test"]
+ install_dir = manager._manifest_install_dir(manifest, archive)
+ install_dir.mkdir(parents=True, exist_ok=True)
+ (install_dir / ".vibe-show-runtime.json").write_text(
+ json.dumps(
+ {
+ "provider": "manifest-cache",
+ "manifest_sha256": manifest.digest,
+ "runtime_version": manifest.runtime_version,
+ "platform": "test",
+ "archive_name": archive.name,
+ "archive_sha256": archive.sha256,
+ }
+ ),
+ encoding="utf-8",
+ )
+ cli_path = install_dir / "node_modules" / "@avibe" / "show-runtime" / "dist" / "cli.js"
+ cli_path.parent.mkdir(parents=True, exist_ok=True)
+ cli_path.write_text("runtime", encoding="utf-8")
+
+ from storage.lock import MigrationFileLock
+
+ def _unwritable_lock(self, *args, **kwargs):
+ raise OSError("read-only filesystem")
+
+ monkeypatch.setattr(MigrationFileLock, "acquire", _unwritable_lock)
+
+ command = manager._reuse_verified_manifest_command()
+
+ # The installed files verify, but Node is below the manifest minimum, so
+ # the fallback must not hand back an unusable command.
+ assert command is None
+
+
+def test_dry_run_planning_failure_returns_structured_report(tmp_path: Path, monkeypatch) -> None:
+ """A mid-scan install-dir failure must not abort the CLI dry run."""
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+
+ def _boom(*args, **kwargs):
+ raise OSError("install dir vanished during scan")
+
+ monkeypatch.setattr(manager, "_clean_manifest_install_dirs", _boom)
+ result = manager.clean(dry_run=True)
+
+ assert result["archives"].get("skipped_reason") == "archive_inspection_failed"
+
+
+def test_skipped_archives_do_not_hide_other_cleanup_results(monkeypatch, capsys) -> None:
+ from vibe import cli as vibe_cli
+
+ parser = vibe_cli.build_parser()
+ args = parser.parse_args(["runtime", "clean"])
+
+ class FakeRuntimeManager:
+ def clean(self, *, keep_previous=1, dry_run=False):
+ return {
+ "ok": True,
+ "removed": ["show-install-1"],
+ "archives": {
+ "outcome": "skipped",
+ "skipped_reason": "runtime_install_already_running",
+ "removed_count": 0,
+ },
+ }
+
+ monkeypatch.setattr(vibe_cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ monkeypatch.setattr(
+ vibe_cli,
+ "_clean_git_runtime",
+ lambda *, keep_previous, dry_run=False: {"ok": True, "removed": ["git-old"]},
+ )
+
+ assert vibe_cli.cmd_runtime(args) == 0
+ captured = capsys.readouterr()
+ assert "runtime_install_already_running" in captured.err # archive skip reason surfaced
+ assert "1" in captured.out # Show Runtime install result still reported
+ assert "git" in captured.out.lower() or "Git" in captured.out # Git result still reported
+
+
+def test_symlinked_downloads_directory_is_rejected(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ outside = tmp_path / "outside-downloads"
+ outside.mkdir()
+ (outside / f"{_sha(2)}.tgz").write_bytes(b"stale")
+ downloads_link = manager.runtime_dir / "downloads"
+ downloads_link.parent.mkdir(parents=True, exist_ok=True)
+ downloads_link.symlink_to(outside)
+
+ result = manager.clean()
+
+ assert result["archives"].get("skipped_reason") == "archive_inspection_failed"
+ assert (outside / f"{_sha(2)}.tgz").exists() # nothing traversed via the link
+
+
+def test_symlinked_install_lock_is_refused(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ manager.runtime_dir.mkdir(parents=True, exist_ok=True)
+ victim = tmp_path / "victim.txt"
+ victim.write_text("precious", encoding="utf-8")
+ (manager.runtime_dir / ".install.lock").symlink_to(victim)
+
+ with manager._install_guard_locked() as (acquired, reason):
+ assert acquired is False
+ assert reason == "runtime_install_guard_unavailable"
+ assert victim.read_text(encoding="utf-8") == "precious" # link never followed
+
+
+def test_downloads_dir_stat_failure_is_an_inspection_failure(tmp_path: Path, monkeypatch) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(2), b"stale")
+
+ import errno
+
+ real_stat = Path.stat
+
+ def _stat_guard(self, **kwargs):
+ if self.name == "downloads" and self.parent == manager.runtime_dir:
+ raise OSError(errno.EACCES, "permission denied")
+ return real_stat(self, **kwargs)
+
+ monkeypatch.setattr(Path, "stat", _stat_guard)
+ result = manager.clean()
+
+ assert result["archives"].get("skipped_reason") == "archive_inspection_failed"
+
+
+def test_versions_dir_stat_failure_fails_closed(tmp_path: Path, monkeypatch) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ _write_install_metadata(manager, version="v1", sha256=_sha(8), mtime=-3600)
+ rollback_archive = _write_archive(manager, _sha(8), b"rollback")
+
+ import errno
+
+ real_stat = Path.stat
+
+ def _stat_guard(self, **kwargs):
+ if self.name == "versions" and self.parent == manager.runtime_dir:
+ raise OSError(errno.EACCES, "permission denied")
+ return real_stat(self, **kwargs)
+
+ monkeypatch.setattr(Path, "stat", _stat_guard)
+ result = manager.clean()
+
+ assert result["archives"].get("skipped_reason") == "archive_inspection_failed"
+ assert rollback_archive.exists() # the rollback archive stays protected
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+
+ def _boom(skip_metadata_under=None):
+ raise OSError("disk unreadable")
+
+ original = manager._protected_archive_sha256s
+ manager._protected_archive_sha256s = _boom
+ try:
+ dry = manager.clean(dry_run=True)
+ status = manager.archive_cache_status()
+ finally:
+ manager._protected_archive_sha256s = original
+
+ # Both read-only surfaces return a skipped report the Doctor/CLI can
+ # render; neither lets the exception escape as a silent no-item result.
+ assert dry["archives"]["skipped_reason"] == "archive_inspection_failed"
+ assert status["skipped_reason"] == "archive_inspection_failed"
+
+
+def test_cli_clean_reports_skipped_archives_without_zero_counts(monkeypatch, capsys) -> None:
+ from vibe import cli as vibe_cli
+
+ parser = vibe_cli.build_parser()
+ args = parser.parse_args(["runtime", "clean"])
+
+ class FakeRuntimeManager:
+ def clean(self, *, keep_previous=1, dry_run=False):
+ return {
+ "ok": True,
+ "removed": [],
+ "archives": {"removed_count": 0, "skipped_reason": "runtime_install_already_running"},
+ }
+
+ monkeypatch.setattr(vibe_cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ monkeypatch.setattr(
+ vibe_cli,
+ "_clean_git_runtime",
+ lambda *, keep_previous, dry_run=False: {"ok": True, "removed": []},
+ )
+
+ assert vibe_cli.cmd_runtime(args) == 0
+ captured = capsys.readouterr()
+ assert "runtime_install_already_running" in captured.err
+ # The archive skip is reported as a warning; Show/Git results still render
+ # (they may legitimately be zero here — the fake removed nothing).
+ assert "Removed 0 Show Runtime cache item(s)." in captured.out
+ assert "downloaded Show Runtime archive" not in captured.out # no placeholder archive line
+
+
+def test_posix_downloads_descriptor_is_closed_after_every_scan(tmp_path: Path) -> None:
+ if os.name == "nt":
+ pytest.skip("directory descriptors are POSIX-only")
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(1), b"current")
+ stale = _write_archive(manager, _sha(2), b"stale")
+
+ manager.clean(dry_run=True)
+ assert getattr(manager, "_downloads_dir_fd", None) is None
+
+ manager.archive_cache_status()
+ assert getattr(manager, "_downloads_dir_fd", None) is None
+
+ manager.clean()
+ assert getattr(manager, "_downloads_dir_fd", None) is None
+ assert not stale.exists()
+
+ manager.clean()
+ assert getattr(manager, "_downloads_dir_fd", None) is None
+
+
+ "digest",
+ [None, "", 123, "not-a-digest", "A" * 64, "g" * 64, "a" * 63],
+)
+def test_retained_metadata_without_valid_digest_fails_closed(tmp_path: Path, digest) -> None:
+ manager = _make_manager(tmp_path)
+ current_install = _write_install_metadata(manager, version="v2", sha256=_sha(1), mtime=0)
+ _write_current_pointer(manager, _sha(1), install_dir=current_install)
+ rollback_dir = _write_install_metadata(manager, version="v1", sha256=_sha(8), mtime=-3600)
+ metadata_path = next(rollback_dir.rglob(".vibe-show-runtime.json"))
+ payload = json.loads(metadata_path.read_text(encoding="utf-8"))
+ if digest is None:
+ payload.pop("archive_sha256", None)
+ else:
+ payload["archive_sha256"] = digest
+ metadata_path.write_text(json.dumps(payload), encoding="utf-8")
+ _write_archive(manager, _sha(1), b"current")
+ rollback_archive = _write_archive(manager, _sha(8), b"rollback")
+
+ result = manager.clean()
+
+ assert result["archives"]["skipped_reason"] == "archive_inspection_failed"
+ assert rollback_archive.exists()
+
+
+def test_preview_guard_covers_archive_planning(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ manager.runtime_dir.mkdir(parents=True, exist_ok=True)
+ (manager.runtime_dir / ".install.lock").write_text("", encoding="utf-8")
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(1), b"current")
+ stale = _write_archive(manager, _sha(2), b"stale")
+ seen: dict[str, object] = {}
+ real_clean = manager._clean_downloaded_archives
+
+ def _observe(*, dry_run=False, skip_metadata_under=None):
+ seen["fd"] = getattr(manager, "_preview_guard_fd", None)
+ return real_clean(dry_run=dry_run, skip_metadata_under=skip_metadata_under)
+
+ manager._clean_downloaded_archives = _observe
+ result = manager.clean(dry_run=True)
+
+ assert result["dry_run"] is True
+ assert stale.exists()
+ assert result["archives"]["candidate_count"] == 1
+ if os.name != "nt":
+ assert seen["fd"] is not None
+ assert getattr(manager, "_preview_guard_fd", None) is None
+
+
+def _stat_with_ino(info: os.stat_result, ino: int) -> os.stat_result:
+ fields = list(info)
+ fields[1] = ino
+ return os.stat_result(fields)
+
+
+def test_windows_downloads_identity_mismatch_fails_closed(tmp_path: Path, monkeypatch) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(2), b"stale")
+ monkeypatch.setattr("os.name", "nt")
+ real_lstat = Path.lstat
+ calls = {"n": 0}
+
+ def _lstat(self):
+ result = real_lstat(self)
+ if self.name == "downloads" and self.parent == manager.runtime_dir:
+ calls["n"] += 1
+ if calls["n"] >= 3:
+ return _stat_with_ino(result, result.st_ino + 1)
+ return result
+
+ monkeypatch.setattr(Path, "lstat", _lstat)
+ result = manager.clean()
+ assert result["archives"].get("skipped_reason") == "archive_inspection_failed"
+ assert (manager.runtime_dir / "downloads" / f"{_sha(2)}.tgz").exists()
+
+
+def test_install_guard_refuses_path_fd_identity_mismatch(tmp_path: Path, monkeypatch) -> None:
+ manager = _make_manager(tmp_path)
+ manager.runtime_dir.mkdir(parents=True, exist_ok=True)
+ real_lstat = Path.lstat
+ real_fstat = os.fstat
+ mismatch = {"on": False}
+
+ def _lstat(self):
+ info = real_lstat(self)
+ if mismatch["on"] and self == manager.runtime_dir / ".install.lock":
+ return _stat_with_ino(info, info.st_ino + 99)
+ return info
+
+ def _fstat(fd):
+ mismatch["on"] = True
+ return real_fstat(fd)
+
+ monkeypatch.setattr(Path, "lstat", _lstat)
+ monkeypatch.setattr(os, "fstat", _fstat)
+ with manager._install_guard_locked() as (acquired, reason):
+ assert acquired is False
+ assert reason == "runtime_install_guard_unavailable"
+
+
+def test_install_guard_refuses_swap_after_lock_acquisition(tmp_path: Path, monkeypatch) -> None:
+ manager = _make_manager(tmp_path)
+ manager.runtime_dir.mkdir(parents=True, exist_ok=True)
+ real_lstat = Path.lstat
+ mismatch = {"on": False}
+
+ def _lstat(self):
+ info = real_lstat(self)
+ if mismatch["on"] and self == manager.runtime_dir / ".install.lock":
+ return _stat_with_ino(info, info.st_ino + 77)
+ return info
+
+ def _try_lock(handle):
+ mismatch["on"] = True
+ return True
+
+ monkeypatch.setattr(Path, "lstat", _lstat)
+ monkeypatch.setattr("core.show_runtime.storage_lock_try_lock", _try_lock)
+ with manager._install_guard_locked() as (acquired, reason):
+ assert acquired is False
+ assert reason == "runtime_install_guard_unavailable"
+
+
+def test_preview_discards_plan_when_lock_appears_mid_scan(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(2), b"stale")
+ real_clean = manager._clean_downloaded_archives
+
+ def _observe(*, dry_run=False, skip_metadata_under=None):
+ (manager.runtime_dir / "manifest-live").mkdir(parents=True, exist_ok=True)
+ (manager.runtime_dir / ".install.lock").write_text("busy", encoding="utf-8")
+ return real_clean(dry_run=dry_run, skip_metadata_under=skip_metadata_under)
+
+ manager._clean_downloaded_archives = _observe
+ result = manager.clean(dry_run=True)
+ assert result["ok"] is False
+ assert result["archives"]["skipped_reason"] == "runtime_install_already_running"
+
+
+def test_abandoned_windows_claim_is_reclaimed(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ leftover = manager.runtime_dir / "downloads"
+ leftover.mkdir(parents=True, exist_ok=True)
+ claim = leftover / f"{_sha(2)}.tgz.avibe-removing"
+ claim.write_bytes(b"abandoned")
+ stamp = time.time() - 3600
+ os.utime(claim, (stamp, stamp))
+ result = manager.clean()
+ assert not claim.exists()
+ assert result["archives"]["removed_count"] >= 1
+
+
+def test_cleanup_removes_abandoned_claim_before_same_digest_archive(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ digest = _sha(2)
+ leftover = manager.runtime_dir / "downloads"
+ leftover.mkdir(parents=True, exist_ok=True)
+ claim = leftover / f"{digest}.tgz.avibe-removing"
+ claim.write_bytes(b"abandoned")
+ archive = _write_archive(manager, digest, b"redownloaded")
+ stamp = time.time() - 3600
+ os.utime(claim, (stamp, stamp))
+ result = manager.clean()
+ assert not claim.exists()
+ assert not archive.exists()
+ assert result["archives"]["removed_count"] == 2
+ assert result["archives"].get("skipped_reason") is None
+
+
+def test_dry_run_includes_abandoned_claims(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ _write_current_pointer(manager, _sha(1))
+ leftover = manager.runtime_dir / "downloads"
+ leftover.mkdir(parents=True, exist_ok=True)
+ claim = leftover / f"{_sha(2)}.tgz.avibe-removing"
+ claim.write_bytes(b"abandoned")
+ stamp = time.time() - 3600
+ os.utime(claim, (stamp, stamp))
+ dry = manager.clean(dry_run=True)
+ assert dry["archives"]["candidate_count"] == 1
+ assert dry["archives"]["candidate_bytes"] == len(b"abandoned")
+ assert claim.exists()
+
+
+def test_archive_cache_status_uses_preview_guard(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ manager.runtime_dir.mkdir(parents=True, exist_ok=True)
+ (manager.runtime_dir / ".install.lock").write_text("", encoding="utf-8")
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(2), b"stale")
+ seen: dict[str, object] = {}
+ real_clean = manager._clean_downloaded_archives
+
+ def _observe(*, dry_run=False, skip_metadata_under=None):
+ seen["fd"] = getattr(manager, "_preview_guard_fd", None)
+ return real_clean(dry_run=dry_run, skip_metadata_under=skip_metadata_under)
+
+ manager._clean_downloaded_archives = _observe
+ report = manager.archive_cache_status()
+ assert report["candidate_count"] == 1
+ if os.name != "nt":
+ assert seen["fd"] is not None
+ assert getattr(manager, "_preview_guard_fd", None) is None
+
+
+def test_windows_preview_ignores_persistent_lock_file(tmp_path: Path, monkeypatch) -> None:
+ manager = _make_manager(tmp_path)
+ manager.runtime_dir.mkdir(parents=True, exist_ok=True)
+ (manager.runtime_dir / ".install.lock").write_text("", encoding="utf-8")
+ _write_current_pointer(manager, _sha(1))
+ stale = _write_archive(manager, _sha(2), b"stale")
+ monkeypatch.setattr("core.show_runtime.fcntl_available", lambda: False)
+ monkeypatch.setattr("core.show_runtime.try_windows_exclusive_lock", lambda fd: True)
+ result = manager.clean(dry_run=True)
+ assert result["ok"] is True
+ assert result["archives"]["candidate_count"] == 1
+ assert stale.exists()
+
+
+def test_windows_preview_detects_held_lock_before_staging(tmp_path: Path, monkeypatch) -> None:
+ manager = _make_manager(tmp_path)
+ manager.runtime_dir.mkdir(parents=True, exist_ok=True)
+ (manager.runtime_dir / ".install.lock").write_text("", encoding="utf-8")
+ _write_current_pointer(manager, _sha(1))
+ stale = _write_archive(manager, _sha(2), b"stale")
+ monkeypatch.setattr("core.show_runtime.fcntl_available", lambda: False)
+ monkeypatch.setattr("core.show_runtime.try_windows_exclusive_lock", lambda fd: False)
+ result = manager.clean(dry_run=True)
+ assert result["ok"] is False
+ assert result["archives"]["skipped_reason"] == "runtime_install_already_running"
+ assert stale.exists()
+
+
+def test_preview_probe_refuses_fifo_lock(tmp_path: Path) -> None:
+ manager = _make_manager(tmp_path)
+ manager.runtime_dir.mkdir(parents=True, exist_ok=True)
+ os.mkfifo(manager.runtime_dir / ".install.lock")
+ _write_current_pointer(manager, _sha(1))
+ _write_archive(manager, _sha(2), b"stale")
+ result = manager.clean(dry_run=True)
+ assert result["ok"] is False
+ assert result["archives"]["skipped_reason"] == "archive_inspection_failed"
+
+
+def test_clean_keeps_completed_staging_removals_on_later_failure(tmp_path: Path, monkeypatch) -> None:
+ manager = _make_manager(tmp_path)
+ staging = manager.runtime_dir / "manifest-gone"
+ staging.mkdir(parents=True)
+ _write_current_pointer(manager, _sha(1))
+
+ def _boom(*, keep_previous, dry_run=False, removed=None, **kwargs):
+ raise OSError("versions unreadable")
+
+ monkeypatch.setattr(manager, "_clean_manifest_install_dirs", _boom)
+ result = manager.clean()
+ assert result["ok"] is False
+ assert str(staging) in result["removed"]
+ assert not staging.exists()
+
+
+def test_clean_keeps_completed_install_removals_when_prune_fails(tmp_path: Path, monkeypatch) -> None:
+ manager = _make_manager(tmp_path)
+ current_install = _write_install_metadata(manager, version="v2", sha256=_sha(1), mtime=0)
+ _write_current_pointer(manager, _sha(1), install_dir=current_install)
+ _write_install_metadata(manager, version="v1", sha256=_sha(8), mtime=-3600)
+ stale_install = _write_install_metadata(manager, version="v0", sha256=_sha(9), mtime=-999999)
+ _write_archive(manager, _sha(1), b"current")
+
+ def _boom(self, versions_dir):
+ raise OSError("parent became nonempty")
+
+ monkeypatch.setattr(ShowRuntimeManager, "_prune_empty_manifest_version_dirs", _boom)
+ result = manager.clean()
+ assert result["ok"] is False
+ assert str(stale_install) in result["removed"]
+ assert not stale_install.exists()
+
+
+def test_configured_prebuilt_archive_is_protected(tmp_path: Path) -> None:
+ digest = _sha(3)
+ archive = tmp_path / "show-runtime" / "downloads" / f"{digest}.tgz"
+ archive.parent.mkdir(parents=True)
+ archive.write_bytes(b"prebuilt")
+ stamp = time.time() - 3600
+ os.utime(archive, (stamp, stamp))
+ manager = ShowRuntimeManager(
+ runtime_dir=tmp_path / "show-runtime",
+ offline=True,
+ runtime_source="archive",
+ archive_path=archive,
+ )
+ _write_archive(manager, _sha(2), b"stale")
+ result = manager.clean()
+ assert archive.exists()
+ assert not (manager.runtime_dir / "downloads" / f"{_sha(2)}.tgz").exists()
+ assert result["archives"]["removed_count"] == 1
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index f8bcd9ef2..ad7dda289 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -1631,6 +1631,40 @@ def test_show_runtime_doctor_fast_mode_reports_local_state_without_network(monke
assert next(item for item in items if item.get("code") == "show_runtime.archive_probe_skipped")["status"] == "pass"
+def test_show_runtime_doctor_reports_skipped_archive_inspection_as_warn(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": True,
+ }
+ manager = SimpleNamespace(
+ status=lambda: status,
+ probe_archive_reachability=lambda: (_ for _ in ()).throw(AssertionError("fast Doctor must not probe network")),
+ archive_cache_status=lambda: {
+ "candidate_count": 0,
+ "candidate_bytes": 0,
+ "skipped_reason": "runtime_install_already_running",
+ },
+ )
+ monkeypatch.setattr("core.show_runtime.ShowRuntimeManager", lambda **_kwargs: manager)
+
+ items = cli._show_runtime_doctor_items(deep=False)
+
+ skipped = next(item for item in items if item.get("code") == "show_runtime.archive_cache_skipped")
+ assert skipped["status"] == "warn"
+ clean = [item for item in items if item.get("code") == "show_runtime.archive_cache_clean"]
+ assert not clean # an uninspected cache must not be reported as clean
+
+
def test_managed_dependencies_doctor_uses_one_status_contract(monkeypatch):
offline_calls: list[bool] = []
diff --git a/vibe/cli.py b/vibe/cli.py
index 72e506710..4ffe1f532 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -10837,6 +10837,49 @@ def _show_runtime_doctor_items(*, deep: bool = False) -> list[dict]:
)
return items
+ try:
+ archive_cache = manager.archive_cache_status()
+ except Exception: # noqa: BLE001
+ archive_cache = None
+ doctor_language = _configured_cli_language()
+ archive_skipped_reason = str((archive_cache or {}).get("skipped_reason") or "")
+ if archive_cache and archive_skipped_reason == "archive_inspection_failed":
+ _add_doctor_item(
+ items,
+ "warn",
+ i18n_t("runtime.doctor.archiveCacheSkipped", doctor_language, reason=archive_skipped_reason),
+ i18n_t("runtime.doctor.archiveCacheSkippedInspectionAction", doctor_language),
+ code="show_runtime.archive_cache_skipped",
+ )
+ elif archive_cache and archive_skipped_reason:
+ _add_doctor_item(
+ items,
+ "warn",
+ i18n_t("runtime.doctor.archiveCacheSkipped", doctor_language, reason=archive_skipped_reason),
+ i18n_t("runtime.doctor.archiveCacheSkippedAction", doctor_language),
+ code="show_runtime.archive_cache_skipped",
+ )
+ elif archive_cache and int(archive_cache.get("candidate_count") or 0) > 0:
+ _add_doctor_item(
+ items,
+ "warn",
+ i18n_t(
+ "runtime.doctor.archiveCacheReclaimable",
+ doctor_language,
+ count=int(archive_cache.get("candidate_count") or 0),
+ size=_format_byte_size(int(archive_cache.get("candidate_bytes") or 0)),
+ ),
+ i18n_t("runtime.doctor.archiveCacheReclaimableAction", doctor_language),
+ code="show_runtime.archive_cache_reclaimable",
+ )
+ elif archive_cache is not None:
+ _add_doctor_item(
+ items,
+ "pass",
+ i18n_t("runtime.doctor.archiveCacheClean", _configured_cli_language()),
+ code="show_runtime.archive_cache_clean",
+ )
+
provider = str(status.get("provider") or "unknown")
explicit_command = status.get("explicit_command")
if explicit_command:
@@ -14149,15 +14192,76 @@ def cmd_runtime(args) -> int:
strict_ok = bool(payload.get("ok")) and _git_prepare_satisfies_strict(git)
return 1 if getattr(args, "strict", False) and not strict_ok else 0
if command == "clean":
- payload = manager.clean(keep_previous=getattr(args, "keep_previous", 1))
- git = _clean_git_runtime(keep_previous=getattr(args, "keep_previous", 1))
+ dry_run = bool(getattr(args, "dry_run", False))
+ payload = manager.clean(
+ keep_previous=getattr(args, "keep_previous", 1),
+ dry_run=dry_run,
+ )
+ git = _clean_git_runtime(keep_previous=getattr(args, "keep_previous", 1), dry_run=dry_run)
payload["git"] = git
if getattr(args, "json", False):
print(json.dumps(payload, indent=2))
else:
+ language = _configured_cli_language()
+ archives = payload.get("archives") or {}
+ skipped_reason = str(archives.get("skipped_reason") or "")
+ outcome = str(archives.get("outcome") or "")
+ # Show/Git results are reported independently of the archive
+ # outcome: a skipped archive pass must not hide what the rest of
+ # the cleanup actually reclaimed (or would reclaim).
+ prefix_key = "runtime.clean.wouldRemove" if dry_run else "runtime.clean.removed"
removed = payload.get("removed") or []
- print(f"Removed {len(removed)} Show Runtime cache item(s).")
- print(f"Removed {len(git.get('removed') or [])} Git Runtime cache item(s).")
+ print(i18n_t(f"{prefix_key}Items", language, count=len(removed)))
+ is_partial_run = outcome == "partial" and not dry_run
+ if is_partial_run:
+ print(
+ i18n_t(
+ "runtime.clean.removedArchives",
+ language,
+ count=int(archives.get("removed_count") or 0),
+ size=_format_byte_size(int(archives.get("removed_bytes") or 0)),
+ )
+ )
+ print(
+ i18n_t("runtime.clean.partiallyRemoved", language, failed=int(archives.get("failed_count") or 0)),
+ file=sys.stderr,
+ )
+ elif skipped_reason:
+ # A skipped/failed archive pass is not a completed zero-removal
+ # cleanup; say so instead of printing placeholder counts, with
+ # remediation that matches the actual reason.
+ if skipped_reason == "archive_removal_failed":
+ print(
+ i18n_t(
+ "runtime.clean.removalFailed",
+ language,
+ failed=int(archives.get("failed_count") or 0),
+ ),
+ file=sys.stderr,
+ )
+ else:
+ skip_key = (
+ "runtime.clean.skippedInspection"
+ if skipped_reason == "archive_inspection_failed"
+ else "runtime.clean.skipped"
+ )
+ print(i18n_t(skip_key, language, reason=skipped_reason), file=sys.stderr)
+ else:
+ archive_count = int(archives.get("candidate_count") or 0) if dry_run else int(archives.get("removed_count") or 0)
+ archive_bytes = int(archives.get("candidate_bytes") or 0) if dry_run else int(archives.get("removed_bytes") or 0)
+ print(
+ i18n_t(
+ f"{prefix_key}Archives",
+ language,
+ count=archive_count,
+ size=_format_byte_size(archive_bytes),
+ )
+ )
+ if git.get("ok") is False and git.get("reason"):
+ git_skip_key = "runtime.clean.gitSkippedPreview" if dry_run else "runtime.clean.gitSkipped"
+ print(i18n_t(git_skip_key, language, reason=git["reason"]), file=sys.stderr)
+ else:
+ print(i18n_t(f"{prefix_key}Git", language, count=len(git.get("removed") or [])))
return 0
raise TaskCliError("runtime command is required", code="invalid_arguments", help_command="vibe runtime --help")
@@ -14246,11 +14350,21 @@ def _ensure_git_during_prepare(offline: bool | None = None, force: bool = False)
return {"ok": False, "message": str(exc)}
-def _clean_git_runtime(*, keep_previous: int) -> dict:
+def _format_byte_size(size: int) -> str:
+ if size < 1024:
+ return f"{size} B"
+ for unit in ("KiB", "MiB", "GiB", "TiB"):
+ size /= 1024
+ if size < 1024:
+ return f"{size:.1f} {unit}"
+ return f"{size:.1f} PiB"
+
+
+def _clean_git_runtime(*, keep_previous: int, dry_run: bool = False) -> dict:
try:
from core.git_runtime import get_git_runtime_manager
- return get_git_runtime_manager().clean(keep_previous=keep_previous)
+ return get_git_runtime_manager().clean(keep_previous=keep_previous, dry_run=dry_run)
except Exception as exc: # noqa: BLE001
return {"ok": False, "removed": [], "message": str(exc)}
@@ -14503,6 +14617,11 @@ def build_parser():
runtime_clean_parser = runtime_subparsers.add_parser("clean", help="Clean stale managed runtime cache entries")
runtime_clean_parser.add_argument("--keep-previous", type=int, default=1, help="Number of previous runtime versions to keep.")
+ runtime_clean_parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help=i18n_t("runtime.clean.dryRunHelp", _configured_cli_language()),
+ )
runtime_clean_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")
remote_parser = subparsers.add_parser(
"remote",
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 2caeb810f..b225da39f 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -905,5 +905,30 @@
"interrupted": {
"serviceRestart": "\u26a0\ufe0f This turn was interrupted \u2014 the Avibe service restarted while it was still running, and its agent runtime could not be resumed. Nothing further will arrive for it. Send the request again if the work still needs doing."
}
+ },
+ "runtime": {
+ "clean": {
+ "dryRunHelp": "Report stale archives and cache entries without removing anything.",
+ "wouldRemoveItems": "Would remove {count} Show Runtime cache item(s).",
+ "wouldRemoveArchives": "Would remove {count} downloaded Show Runtime archive(s) ({size}).",
+ "wouldRemoveGit": "Would remove {count} Git Runtime cache item(s).",
+ "removedItems": "Removed {count} Show Runtime cache item(s).",
+ "removedArchives": "Removed {count} downloaded Show Runtime archive(s) ({size}).",
+ "removedGit": "Removed {count} Git Runtime cache item(s).",
+ "partiallyRemoved": " {failed} archive(s) could not be removed; check permissions and the Avibe log.",
+ "skipped": "Archive cleanup skipped ({reason}); stale archives may remain. Try again after the running install or cleanup finishes.",
+ "removalFailed": "{failed} archive(s) could not be removed; stale archives remain. Check runtime directory permissions and the Avibe log.",
+ "skippedInspection": "Archive cleanup could not inspect the cache ({reason}); stale archives may remain. Check runtime directory permissions and the Avibe log.",
+ "gitSkipped": "Git Runtime cleanup skipped ({reason}); stale entries remain.",
+ "gitSkippedPreview": "Git Runtime cache preview skipped ({reason}); stale entries may remain."
+ },
+ "doctor": {
+ "archiveCacheReclaimable": "Show Runtime archive cache holds {count} reclaimable archive(s) ({size}); the current and rollback archives are kept.",
+ "archiveCacheReclaimableAction": "Run `vibe runtime clean --dry-run` to preview, then `vibe runtime clean` to reclaim.",
+ "archiveCacheClean": "Show Runtime archive cache has no reclaimable archives",
+ "archiveCacheSkipped": "Show Runtime archive cache was not inspected ({reason}); it may still hold reclaimable archives.",
+ "archiveCacheSkippedAction": "Wait for the running install or clean to finish, then rerun Doctor.",
+ "archiveCacheSkippedInspectionAction": "Check runtime directory permissions and the Avibe log; retry Doctor once fixed."
+ }
}
-}
+}
\ No newline at end of file
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 0ee1a857f..368e0eec2 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -905,5 +905,30 @@
"interrupted": {
"serviceRestart": "\u26a0\ufe0f \u672c\u8f6e\u6267\u884c\u88ab\u4e2d\u65ad\u2014\u2014Avibe \u670d\u52a1\u5728\u5b83\u8fd0\u884c\u671f\u95f4\u91cd\u542f\uff0c\u5176 Agent \u8fd0\u884c\u65f6\u65e0\u6cd5\u6062\u590d\u3002\u8fd9\u4e00\u8f6e\u4e0d\u4f1a\u518d\u6709\u4efb\u4f55\u540e\u7eed\u7ed3\u679c\u3002\u5982\u679c\u8fd9\u9879\u5de5\u4f5c\u4ecd\u7136\u9700\u8981\u5b8c\u6210\uff0c\u8bf7\u91cd\u65b0\u53d1\u9001\u8bf7\u6c42\u3002"
}
+ },
+ "runtime": {
+ "clean": {
+ "dryRunHelp": "\u4ec5\u62a5\u544a\u53ef\u6e05\u7406\u7684\u5f52\u6863\u4e0e\u7f13\u5b58\u6761\u76ee\uff0c\u4e0d\u5220\u9664\u4efb\u4f55\u5185\u5bb9\u3002",
+ "wouldRemoveItems": "\u5c06\u6e05\u7406 {count} \u9879 Show Runtime \u7f13\u5b58\u3002",
+ "wouldRemoveArchives": "\u5c06\u6e05\u7406 {count} \u4e2a\u5df2\u4e0b\u8f7d\u7684 Show Runtime \u5f52\u6863\uff08{size}\uff09\u3002",
+ "wouldRemoveGit": "\u5c06\u6e05\u7406 {count} \u9879 Git Runtime \u7f13\u5b58\u3002",
+ "removedItems": "\u5df2\u6e05\u7406 {count} \u9879 Show Runtime \u7f13\u5b58\u3002",
+ "removedArchives": "\u5df2\u6e05\u7406 {count} \u4e2a\u5df2\u4e0b\u8f7d\u7684 Show Runtime \u5f52\u6863\uff08{size}\uff09\u3002",
+ "removedGit": "\u5df2\u6e05\u7406 {count} \u9879 Git Runtime \u7f13\u5b58\u3002",
+ "partiallyRemoved": " \u6709 {failed} \u4e2a\u5f52\u6863\u65e0\u6cd5\u5220\u9664\uff1b\u8bf7\u68c0\u67e5\u6743\u9650\u4e0e Avibe \u65e5\u5fd7\u3002",
+ "skipped": "\u5f52\u6863\u6e05\u7406\u5df2\u8df3\u8fc7\uff08{reason}\uff09\uff1b\u53ef\u80fd\u4ecd\u6709\u8fc7\u671f\u5f52\u6863\u3002\u8bf7\u5728\u6b63\u5728\u8fd0\u884c\u7684\u5b89\u88c5\u6216\u6e05\u7406\u7ed3\u675f\u540e\u91cd\u8bd5\u3002",
+ "removalFailed": "\u6709 {failed} \u4e2a\u5f52\u6863\u65e0\u6cd5\u5220\u9664\uff1b\u8fc7\u671f\u5f52\u6863\u4ecd\u4fdd\u7559\u3002\u8bf7\u68c0\u67e5\u8fd0\u884c\u76ee\u5f55\u6743\u9650\u4e0e Avibe \u65e5\u5fd7\u3002",
+ "skippedInspection": "\u5f52\u6863\u6e05\u7406\u65e0\u6cd5\u68c0\u67e5\u7f13\u5b58\uff08{reason}\uff09\uff1b\u53ef\u80fd\u4ecd\u6709\u8fc7\u671f\u5f52\u6863\u3002\u8bf7\u68c0\u67e5\u8fd0\u884c\u76ee\u5f55\u6743\u9650\u4e0e Avibe \u65e5\u5fd7\u3002",
+ "gitSkipped": "Git Runtime \u6e05\u7406\u5df2\u8df3\u8fc7\uff08{reason}\uff09\uff1b\u8fc7\u671f\u6761\u76ee\u4ecd\u4fdd\u7559\u3002",
+ "gitSkippedPreview": "Git Runtime \u7f13\u5b58\u9884\u89c8\u5df2\u8df3\u8fc7\uff08{reason}\uff09\uff1b\u53ef\u80fd\u4ecd\u6709\u8fc7\u671f\u6761\u76ee\u3002"
+ },
+ "doctor": {
+ "archiveCacheReclaimable": "Show Runtime \u5f52\u6863\u7f13\u5b58\u4e2d\u6709 {count} \u4e2a\u53ef\u56de\u6536\u5f52\u6863\uff08{size}\uff09\uff1b\u5f53\u524d\u4e0e\u56de\u6eda\u5f52\u6863\u4f1a\u88ab\u4fdd\u7559\u3002",
+ "archiveCacheReclaimableAction": "\u5148\u8fd0\u884c `vibe runtime clean --dry-run` \u9884\u89c8\uff0c\u518d\u8fd0\u884c `vibe runtime clean` \u56de\u6536\u7a7a\u95f4\u3002",
+ "archiveCacheClean": "Show Runtime \u5f52\u6863\u7f13\u5b58\u6ca1\u6709\u53ef\u56de\u6536\u5f52\u6863",
+ "archiveCacheSkipped": "未能检查 Show Runtime 归档缓存({reason});其中可能仍有可回收归档。",
+ "archiveCacheSkippedAction": "等待正在进行的安装或清理结束后,重新运行 Doctor。",
+ "archiveCacheSkippedInspectionAction": "\u8bf7\u68c0\u67e5\u8fd0\u884c\u76ee\u5f55\u6743\u9650\u548c Avibe \u65e5\u5fd7\uff0c\u4fee\u590d\u540e\u91cd\u8bd5 Doctor\u3002"
+ }
}
-}
+}
\ No newline at end of file