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.

refactor(show): use shared manifest runtime manager (#1734)

Call Whitedd4b47098832
diff --git a/core/managed_runtime.py b/core/managed_runtime.py
index 37ca1d9ce..cda24e7b6 100644
--- a/core/managed_runtime.py
+++ b/core/managed_runtime.py
@@ -104,7 +104,7 @@ class ManagedRuntimeArchive:
name: str
url: str
sha256: str
- binary_sha256: str
+ binary_sha256: str | None
size: int | None
bin_path: str
@@ -131,10 +131,16 @@ class ManagedRuntimeSpec:
archives_field: str = "archives"
archive_size_field: str = "size"
platform_aliases: tuple[tuple[str, str], ...] = ()
+ binary_artifact: bool = True
+ record_provider: str = "manifest"
+ metadata_filename_override: str | None = None
+ allow_legacy_missing_runtime_id: bool = False
+ staging_prefixes: tuple[str, ...] = ("install-",)
+ replace_target_on_force: bool = False
@property
def metadata_filename(self) -> str:
- return f".avibe-{self.runtime_id}-runtime.json"
+ return self.metadata_filename_override or f".avibe-{self.runtime_id}-runtime.json"
@dataclass(frozen=True)
@@ -229,11 +235,19 @@ class ManagedRuntimeManager:
# manifest's admitted disk record. Cleanup cannot make the
# same assumption because it has no replacement transaction.
current_install_dir = None
- existing_install_dir = current_install_dir or install_dir
- existing = self._verified_manifest_binary(existing_install_dir, manifest, archive)
- if existing is None and existing_install_dir != install_dir:
- existing_install_dir = install_dir
- existing = self._verified_manifest_binary(install_dir, manifest, archive)
+ candidate_install_dirs: list[Path] = []
+ if current_install_dir is not None:
+ candidate_install_dirs.append(current_install_dir)
+ candidate_install_dirs.extend(self._manifest_install_candidates(manifest, archive))
+ unique_install_dirs = list(dict.fromkeys(candidate_install_dirs))
+ existing_install_dir = unique_install_dirs[0]
+ existing: Path | None = None
+ for candidate_install_dir in unique_install_dirs:
+ candidate = self._verified_manifest_binary(candidate_install_dir, manifest, archive)
+ if candidate is not None:
+ existing_install_dir = candidate_install_dir
+ existing = candidate
+ break
if existing is not None and not force:
return self._reuse_existing_install(existing, existing_install_dir, manifest, archive)
@@ -266,7 +280,8 @@ class ManagedRuntimeManager:
manifest=manifest,
archive=archive,
)
- make_executable(staged_binary)
+ if self.spec.binary_artifact:
+ make_executable(staged_binary)
preparation = self._prepare_binary_for_manifest(staged_binary, manifest)
if not preparation.get("ok"):
return self._failure(
@@ -274,8 +289,8 @@ class ManagedRuntimeManager:
manifest=manifest,
archive=archive,
)
- binary_sha256 = file_sha256(staged_binary)
- if binary_sha256 != archive.binary_sha256:
+ binary_sha256 = file_sha256(staged_binary) if self.spec.binary_artifact else None
+ if self.spec.binary_artifact and binary_sha256 != archive.binary_sha256:
return self._failure(
self._reason("binary_checksum_mismatch"),
manifest=manifest,
@@ -290,11 +305,19 @@ class ManagedRuntimeManager:
install_dir.parent.mkdir(parents=True, exist_ok=True)
if install_dir.exists():
- replacement = Path(
- tempfile.mkdtemp(prefix=f"{install_dir.name}-", dir=install_dir.parent)
- )
- replacement.rmdir()
- install_dir = replacement
+ if force and self.spec.replace_target_on_force:
+ if not self._remove_install_target_for_replacement(install_dir):
+ return self._failure(
+ self._reason("install_failed"),
+ manifest=manifest,
+ archive=archive,
+ )
+ else:
+ replacement = Path(
+ tempfile.mkdtemp(prefix=f"{install_dir.name}-", dir=install_dir.parent)
+ )
+ replacement.rmdir()
+ install_dir = replacement
shutil.move(str(staging_dir), str(install_dir))
candidate_install_dir = install_dir
installed_binary = (install_dir / archive.bin_path).resolve(strict=True)
@@ -373,8 +396,8 @@ class ManagedRuntimeManager:
host_platform = aliases.get(runtime_platform_tag(), runtime_platform_tag())
installed_platform = aliases.get(platform_tag, platform_tag) if isinstance(platform_tag, str) else None
if (
- pointer.get("provider") != "manifest"
- or pointer.get("runtime_id") != self.spec.runtime_id
+ not self._record_provider_matches(pointer.get("provider"))
+ or not self._record_runtime_id_matches(pointer.get("runtime_id"))
or not _safe_metadata_value(runtime_version)
or not _safe_metadata_value(platform_tag)
or installed_platform != host_platform
@@ -407,18 +430,28 @@ class ManagedRuntimeManager:
metadata_platform = metadata.get("platform")
metadata_bin_path = metadata.get("bin_path", self.spec.default_bin_path)
binary_sha256 = metadata.get("binary_sha256")
+ binary_integrity_valid = (
+ isinstance(binary_sha256, str) and bool(_SHA256_RE.fullmatch(binary_sha256))
+ if self.spec.binary_artifact
+ else (
+ binary_sha256 is None
+ or isinstance(binary_sha256, str)
+ and bool(_SHA256_RE.fullmatch(binary_sha256))
+ )
+ )
if not (
- metadata.get("provider") == "manifest"
- and metadata.get("runtime_id") == self.spec.runtime_id
+ self._record_provider_matches(metadata.get("provider"))
+ and self._record_runtime_id_matches(metadata.get("runtime_id"))
and metadata.get("runtime_version") == runtime_version
and isinstance(metadata_platform, str)
and aliases.get(metadata_platform, metadata_platform) == installed_platform
and all(metadata.get(field) == pointer.get(field) for field in digest_fields)
and metadata_bin_path == bin_path
- and isinstance(binary_sha256, str)
- and _SHA256_RE.fullmatch(binary_sha256)
+ and binary_integrity_valid
and binary.is_file()
- and os.access(binary, os.X_OK)
+ and (not self.spec.binary_artifact or os.access(binary, os.X_OK))
+ and self._record_matches_configured_source(metadata)
+ and self._record_install_dir_matches(install_dir, metadata)
):
return None
@@ -439,7 +472,7 @@ class ManagedRuntimeManager:
if self._verified_manifest_binary(install_dir, manifest, archive) != binary:
self._install_reason = inspection_reason
return None
- elif file_sha256(binary) != binary_sha256:
+ elif self.spec.binary_artifact and file_sha256(binary) != binary_sha256:
self._install_reason = inspection_reason
return None
self._install_reason = None
@@ -481,7 +514,7 @@ class ManagedRuntimeManager:
matches_manifest = self._verified_manifest_binary(Path(pointer["install_dir"]), manifest, archive) == binary
return {
"id": self.spec.runtime_id,
- "provider": "manifest",
+ "provider": self.spec.record_provider,
"platform": runtime_platform_tag(),
"installed": binary is not None,
"version": pointer.get("runtime_version") if binary is not None else None,
@@ -497,7 +530,7 @@ class ManagedRuntimeManager:
}
def probe_archive_reachability(self, *, timeout: float = 10.0) -> dict[str, Any]:
- manifest = self._load_manifest(allow_network=not self.offline)
+ manifest = self.load_manifest_for_diagnostics()
if manifest is None:
return {
"ok": False,
@@ -842,6 +875,10 @@ class ManagedRuntimeManager:
by_lineage.setdefault(record.lineage, []).append(record)
current_lineage = records_by_path[current].lineage
for lineage, lineage_installs in by_lineage.items():
+ lineage_installs = self._retention_ranked_installs(
+ lineage_installs,
+ protected,
+ )
ranked = sorted(lineage_installs, key=lambda item: item.mtime, reverse=True)
if lineage == current_lineage:
rollback = [record for record in ranked if record.path.resolve() != current]
@@ -854,7 +891,11 @@ class ManagedRuntimeManager:
protected.update(record.path.resolve() for record in ranked[1 : keep_count + 1])
install_candidates = sorted(
- (path for path in install_dirs if path.resolve() not in protected),
+ (
+ path
+ for path in install_dirs
+ if not self._install_dir_is_protected(path.resolve(), protected)
+ ),
key=lambda path: path.stat().st_mtime,
reverse=True,
)
@@ -969,8 +1010,8 @@ class ManagedRuntimeManager:
archive_sha256 = metadata.get("archive_sha256") if isinstance(metadata, dict) else None
manifest_source = metadata.get("manifest_source") if isinstance(metadata, dict) else None
if (
- metadata.get("provider") != "manifest"
- or metadata.get("runtime_id") != self.spec.runtime_id
+ not self._record_provider_matches(metadata.get("provider"))
+ or not self._record_runtime_id_matches(metadata.get("runtime_id"))
or not isinstance(manifest_sha256, str)
or not _SHA256_RE.fullmatch(manifest_sha256)
or not isinstance(archive_name, str)
@@ -990,7 +1031,11 @@ class ManagedRuntimeManager:
_ManagedRuntimeInstall(
path=install_dir,
lineage=lineage,
- archive_name=archive_name,
+ archive_name=self._install_record_archive_name(
+ metadata,
+ archive_name,
+ archive_sha256,
+ ),
archive_sha256=archive_sha256,
mtime=install_info.st_mtime,
)
@@ -1059,7 +1104,7 @@ class ManagedRuntimeManager:
try:
with os.scandir(self.runtime_dir) as entries:
for entry in entries:
- if entry.name.startswith("install-") and entry.is_dir(follow_symlinks=False):
+ if entry.name.startswith(self.spec.staging_prefixes) and entry.is_dir(follow_symlinks=False):
staging.append(self.runtime_dir / entry.name)
except OSError as exc:
raise OSError(f"runtime directory cannot be inspected: {self.runtime_dir}") from exc
@@ -1083,6 +1128,25 @@ class ManagedRuntimeManager:
return False
return True
+ def _remove_install_target_for_replacement(self, path: Path) -> bool:
+ try:
+ leaf_info = path.lstat()
+ versions_dir = (self.runtime_dir / "versions").resolve(strict=True)
+ parent = path.parent.resolve(strict=True)
+ except (OSError, RuntimeError):
+ return False
+ if (
+ stat.S_ISLNK(leaf_info.st_mode)
+ or _is_reparse_point(leaf_info)
+ or not stat.S_ISDIR(leaf_info.st_mode)
+ or (
+ parent != versions_dir
+ and versions_dir not in parent.parents
+ )
+ ):
+ return False
+ return self._remove_tree(path)
+
def _current_archive_sha256(self) -> str:
pointer_path = self.runtime_dir / "current.json"
try:
@@ -1151,6 +1215,10 @@ class ManagedRuntimeManager:
digest.update(chunk)
return digest.hexdigest()
+ def _archive_candidate_sha256(self, name: str, fd: int) -> str:
+ del name
+ return self._sha256_from_fd(fd)
+
def _clean_downloaded_archives(
self,
*,
@@ -1213,7 +1281,7 @@ class ManagedRuntimeManager:
opened = os.fstat(fd)
if (opened.st_dev, opened.st_ino) != (entry_info.st_dev, entry_info.st_ino):
raise OSError("archive was replaced during inspection")
- archive_sha256 = self._sha256_from_fd(fd)
+ archive_sha256 = self._archive_candidate_sha256(name, fd)
finally:
os.close(fd)
except OSError as exc:
@@ -1297,7 +1365,7 @@ class ManagedRuntimeManager:
entry_info.st_ino,
):
raise OSError("archive was replaced during inspection")
- archive_sha256 = self._sha256_from_fd(file_fd)
+ archive_sha256 = self._archive_candidate_sha256(name, file_fd)
finally:
os.close(file_fd)
if (
@@ -1343,6 +1411,70 @@ class ManagedRuntimeManager:
def _manifest_installable(self, manifest: ManagedRuntimeManifest) -> bool:
return True
+ def _manifest_install_candidates(
+ self,
+ manifest: ManagedRuntimeManifest,
+ archive: ManagedRuntimeArchive,
+ ) -> Iterator[Path]:
+ yield self._manifest_install_dir(manifest, archive)
+
+ def _manifest_identity_fields(self, manifest: ManagedRuntimeManifest) -> dict[str, str]:
+ del manifest
+ return {}
+
+ def _metadata_matches_install_target(
+ self,
+ metadata: Mapping[str, Any],
+ target: Mapping[str, str],
+ ) -> bool:
+ return all(metadata.get(key) == value for key, value in target.items())
+
+ def _record_provider_matches(self, value: object) -> bool:
+ return value == self.spec.record_provider
+
+ def _record_runtime_id_matches(self, value: object) -> bool:
+ return value == self.spec.runtime_id or (
+ value is None and self.spec.allow_legacy_missing_runtime_id
+ )
+
+ def _archive_cache_name(self, archive: ManagedRuntimeArchive) -> str:
+ return archive.name
+
+ def _install_record_archive_name(
+ self,
+ metadata: Mapping[str, Any],
+ archive_name: str,
+ archive_sha256: str,
+ ) -> str:
+ del metadata, archive_sha256
+ return archive_name
+
+ def _record_matches_configured_source(self, metadata: Mapping[str, Any]) -> bool:
+ del metadata
+ return True
+
+ def _manifest_path_read_error_reason(self) -> str:
+ return self._reason("manifest_missing")
+
+ def _record_install_dir_matches(
+ self,
+ install_dir: Path,
+ metadata: Mapping[str, Any],
+ ) -> bool:
+ del install_dir, metadata
+ return True
+
+ def _install_dir_is_protected(self, install_dir: Path, protected: set[Path]) -> bool:
+ return install_dir in protected
+
+ def _retention_ranked_installs(
+ self,
+ installs: list[_ManagedRuntimeInstall],
+ protected: set[Path],
+ ) -> list[_ManagedRuntimeInstall]:
+ del protected
+ return installs
+
def _prepare_binary(self, binary: Path) -> dict[str, Any]:
return {"ok": True, "skipped": True}
@@ -1362,7 +1494,20 @@ class ManagedRuntimeManager:
def _binary_matches_manifest(self, binary: Path, manifest: ManagedRuntimeManifest) -> bool:
return self._binary_version(binary) == manifest.runtime_version
- def _load_manifest(self, *, allow_network: bool) -> ManagedRuntimeManifest | None:
+ def load_manifest_for_diagnostics(self) -> ManagedRuntimeManifest | None:
+ """Load the selected manifest without writing runtime state."""
+
+ return self._load_manifest(
+ allow_network=not self.offline,
+ persist_remote_cache=False,
+ )
+
+ def _load_manifest(
+ self,
+ *,
+ allow_network: bool,
+ persist_remote_cache: bool = True,
+ ) -> ManagedRuntimeManifest | None:
payload: bytes
loaded_from: str
cache_remote = False
@@ -1373,7 +1518,7 @@ class ManagedRuntimeManager:
try:
payload = self.manifest_path.read_bytes()
except OSError:
- self._install_reason = self._reason("manifest_missing")
+ self._install_reason = self._manifest_path_read_error_reason()
return None
loaded_from = str(self.manifest_path)
elif self.manifest_url:
@@ -1405,7 +1550,7 @@ class ManagedRuntimeManager:
self._download_error = dependency_error_details(exc, self.manifest_url)
return None
loaded_from = self.manifest_url
- cache_remote = True
+ cache_remote = persist_remote_cache
else:
try:
resource = package_resources.files(self.spec.package).joinpath(self.spec.manifest_resource)
@@ -1455,7 +1600,12 @@ class ManagedRuntimeManager:
url = str(item["url"])
name = str(item.get("name") or Path(urllib.parse.urlparse(url).path).name)
sha256 = str(item["sha256"]).lower()
- binary_sha256 = str(item["binary_sha256"]).lower()
+ raw_binary_sha256 = item.get("binary_sha256")
+ binary_sha256 = (
+ str(raw_binary_sha256).lower()
+ if raw_binary_sha256 is not None
+ else None
+ )
bin_path = str(item.get("bin_path") or self.spec.default_bin_path)
raw_size = item.get(self.spec.archive_size_field)
size = int(raw_size) if raw_size is not None else None
@@ -1463,7 +1613,11 @@ class ManagedRuntimeManager:
raise ValueError("unsafe archive name")
if not _SHA256_RE.fullmatch(sha256):
raise ValueError("invalid archive sha256")
- if not _SHA256_RE.fullmatch(binary_sha256):
+ if self.spec.binary_artifact and (
+ binary_sha256 is None or not _SHA256_RE.fullmatch(binary_sha256)
+ ):
+ raise ValueError("invalid binary sha256")
+ if binary_sha256 is not None and not _SHA256_RE.fullmatch(binary_sha256):
raise ValueError("invalid binary sha256")
if size is not None and size < 0:
raise ValueError("invalid archive size")
@@ -1515,7 +1669,7 @@ class ManagedRuntimeManager:
return archive
def _resolve_manifest_archive(self, archive: ManagedRuntimeArchive) -> Path | None:
- cached = self.runtime_dir / "downloads" / archive.name
+ cached = self.runtime_dir / "downloads" / self._archive_cache_name(archive)
if cached.is_file() and self._downloaded_archive_matches(cached, archive):
return cached
if self.offline:
@@ -1572,17 +1726,20 @@ class ManagedRuntimeManager:
/ fingerprint
)
- @staticmethod
def _install_target_identity(
+ self,
manifest: ManagedRuntimeManifest,
archive: ManagedRuntimeArchive,
) -> dict[str, str]:
- return {
+ target = {
"runtime_version": manifest.runtime_version,
"platform": archive.platform,
"archive_sha256": archive.sha256,
- "binary_sha256": archive.binary_sha256,
}
+ if archive.binary_sha256 is not None:
+ target["binary_sha256"] = archive.binary_sha256
+ target.update(self._manifest_identity_fields(manifest))
+ return target
@staticmethod
def _normalized_install_target(target: Mapping[str, str]) -> dict[str, str]:
@@ -1609,7 +1766,8 @@ class ManagedRuntimeManager:
if (
install_dir_resolved not in binary.parents
or not binary.is_file()
- or not os.access(binary, os.X_OK)
+ or self.spec.binary_artifact
+ and not os.access(binary, os.X_OK)
):
return None
target = self._install_target_identity(manifest, archive)
@@ -1617,14 +1775,17 @@ class ManagedRuntimeManager:
metadata_platform = metadata.get("platform")
aliases = dict(self.spec.platform_aliases)
if not (
- metadata.get("provider") == "manifest"
- and metadata.get("runtime_id") == self.spec.runtime_id
- and all(metadata.get(key) == value for key, value in target.items())
+ self._record_provider_matches(metadata.get("provider"))
+ and self._record_runtime_id_matches(metadata.get("runtime_id"))
+ and self._metadata_matches_install_target(metadata, target)
and isinstance(metadata_platform, str)
and aliases.get(metadata_platform, metadata_platform)
== aliases.get(target_platform, target_platform)
and bin_path == archive.bin_path
- and file_sha256(binary) == archive.binary_sha256
+ and (
+ not self.spec.binary_artifact
+ or file_sha256(binary) == archive.binary_sha256
+ )
):
return None
return binary
@@ -1635,23 +1796,26 @@ class ManagedRuntimeManager:
manifest: ManagedRuntimeManifest,
archive: ManagedRuntimeArchive,
*,
- binary_sha256: str,
+ binary_sha256: str | None,
) -> None:
+ payload: dict[str, Any] = {
+ "provider": self.spec.record_provider,
+ "runtime_id": self.spec.runtime_id,
+ "manifest_sha256": manifest.digest,
+ "runtime_version": manifest.runtime_version,
+ "platform": archive.platform,
+ "archive_name": archive.name,
+ "archive_sha256": archive.sha256,
+ "bin_path": archive.bin_path,
+ "manifest_source": manifest.loaded_from,
+ "source": manifest.source,
+ **self._manifest_identity_fields(manifest),
+ }
+ if binary_sha256 is not None:
+ payload["binary_sha256"] = binary_sha256
write_json_atomic(
install_dir / self.spec.metadata_filename,
- {
- "provider": "manifest",
- "runtime_id": self.spec.runtime_id,
- "manifest_sha256": manifest.digest,
- "runtime_version": manifest.runtime_version,
- "platform": archive.platform,
- "archive_name": archive.name,
- "archive_sha256": archive.sha256,
- "binary_sha256": binary_sha256,
- "bin_path": archive.bin_path,
- "manifest_source": manifest.loaded_from,
- "source": manifest.source,
- },
+ payload,
)
def _write_current_pointer(
@@ -1671,7 +1835,7 @@ class ManagedRuntimeManager:
write_json_atomic(
self.runtime_dir / "current.json",
{
- "provider": "manifest",
+ "provider": self.spec.record_provider,
"runtime_id": self.spec.runtime_id,
"runtime_version": manifest.runtime_version,
"platform": archive.platform,
@@ -1679,6 +1843,7 @@ class ManagedRuntimeManager:
"manifest_sha256": manifest_sha256,
"archive_sha256": archive.sha256,
"bin_path": archive.bin_path,
+ **self._manifest_identity_fields(manifest),
},
)
@@ -1729,19 +1894,20 @@ class ManagedRuntimeManager:
"release_state": manifest.payload.get("release_state"),
}
- @staticmethod
- def _archive_status_payload(archive: ManagedRuntimeArchive | None) -> dict[str, Any] | None:
+ def _archive_status_payload(self, archive: ManagedRuntimeArchive | None) -> dict[str, Any] | None:
if archive is None:
return None
- return {
+ payload = {
"platform": archive.platform,
"name": archive.name,
"url": redact_url(archive.url),
"sha256": archive.sha256,
- "binary_sha256": archive.binary_sha256,
"size": archive.size,
"bin_path": archive.bin_path,
}
+ if archive.binary_sha256 is not None:
+ payload["binary_sha256"] = archive.binary_sha256
+ return payload
def _reuse_existing_install(
self,
@@ -1902,7 +2068,8 @@ def install_lock_for(runtime_id: str) -> threading.Lock:
def safe_extract_tar(archive: tarfile.TarFile, destination: Path) -> None:
supports_data_filter = hasattr(tarfile, "data_filter")
destination_resolved = destination.resolve()
- for member in archive.getmembers():
+ members = archive.getmembers()
+ for member in members:
if not (member.isfile() or member.isdir() or member.issym() or member.islnk()):
raise ValueError(f"Unsupported managed runtime archive member: {member.name}")
if archive_path_is_unsafe(member.name):
@@ -1910,10 +2077,6 @@ def safe_extract_tar(archive: tarfile.TarFile, destination: Path) -> None:
target = (destination / member.name).resolve()
if target != destination_resolved and destination_resolved not in target.parents:
raise ValueError(f"Unsafe managed runtime archive path: {member.name}")
- if (member.issym() or member.islnk()) and not supports_data_filter:
- raise ValueError(
- f"Managed runtime archive link requires tarfile.data_filter: {member.name}"
- )
if member.issym():
link_target = (destination / member.name).parent / member.linkname
link_target_resolved = link_target.resolve()
@@ -1933,7 +2096,154 @@ def safe_extract_tar(archive: tarfile.TarFile, destination: Path) -> None:
if supports_data_filter:
archive.extractall(destination, filter="data")
else:
- archive.extractall(destination)
+ _extract_tar_without_filter(archive, destination, members)
+
+
+def _extract_tar_without_filter(
+ archive: tarfile.TarFile,
+ destination: Path,
+ members: list[tarfile.TarInfo],
+) -> None:
+ member_paths: dict[tuple[str, ...], tarfile.TarInfo] = {}
+ link_targets: dict[tuple[str, ...], tuple[str, ...]] = {}
+ for member in members:
+ path = _normalized_tar_path(member.name)
+ if not path and not member.isdir():
+ raise ValueError(f"Unsafe managed runtime archive path: {member.name}")
+ if path in member_paths:
+ raise ValueError(f"Managed runtime archive path collision: {member.name}")
+ member_paths[path] = member
+
+ for path, member in member_paths.items():
+ for index in range(1, len(path)):
+ ancestor = member_paths.get(path[:index])
+ if ancestor is not None and not ancestor.isdir():
+ raise ValueError(f"Managed runtime archive path/type collision: {member.name}")
+
+ for path, member in member_paths.items():
+ if member.issym():
+ target = _normalized_tar_link_target(path[:-1], member.linkname, member.name)
+ resolved_target = _resolved_tar_symlink_target(target, member_paths)
+ if resolved_target and resolved_target not in member_paths and not any(
+ candidate[: len(resolved_target)] == resolved_target
+ for candidate in member_paths
+ ):
+ raise ValueError(f"Missing managed runtime archive link target: {member.name}")
+ link_targets[path] = target
+ elif member.islnk():
+ target = _normalized_tar_link_target((), member.linkname, member.name)
+ target_member = member_paths.get(target)
+ if target_member is None or not target_member.isfile():
+ raise ValueError(f"Unsafe managed runtime archive hardlink target: {member.name}")
+ link_targets[path] = target
+
+ try:
+ destination_info = destination.lstat()
+ except FileNotFoundError:
+ destination.mkdir(parents=True)
+ else:
+ if _is_reparse_point(destination_info) or not stat.S_ISDIR(destination_info.st_mode):
+ raise ValueError("Managed runtime archive destination is not a directory")
+ if any(destination.iterdir()):
+ raise ValueError("Managed runtime archive destination is not empty")
+
+ directories = sorted(
+ ((path, member) for path, member in member_paths.items() if member.isdir()),
+ key=lambda item: len(item[0]),
+ )
+ for path, _member in directories:
+ destination.joinpath(*path).mkdir(parents=True, exist_ok=True)
+
+ for path, member in member_paths.items():
+ if not member.isfile():
+ continue
+ target = destination.joinpath(*path)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ source = archive.extractfile(member)
+ if source is None:
+ raise ValueError(f"Unreadable managed runtime archive member: {member.name}")
+ with source, target.open("xb") as handle:
+ shutil.copyfileobj(source, handle)
+ target.chmod(member.mode & 0o777)
+
+ for path, member in member_paths.items():
+ if not member.islnk():
+ continue
+ target = destination.joinpath(*path)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ os.link(destination.joinpath(*link_targets[path]), target)
+
+ for path, member in member_paths.items():
+ if not member.issym():
+ continue
+ target = destination.joinpath(*path)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ os.symlink(member.linkname, target)
+
+ for path, member in reversed(directories):
+ destination.joinpath(*path).chmod(member.mode & 0o777)
+
+
+def _normalized_tar_path(value: str) -> tuple[str, ...]:
+ if archive_path_is_unsafe(value) or "\\" in value:
+ raise ValueError(f"Unsafe managed runtime archive path: {value}")
+ parts = tuple(part for part in PurePosixPath(value).parts if part not in {"", "."})
+ return parts
+
+
+def _normalized_tar_link_target(
+ base: tuple[str, ...],
+ value: str,
+ member_name: str,
+) -> tuple[str, ...]:
+ posix_path = PurePosixPath(value)
+ windows_path = PureWindowsPath(value)
+ if (
+ not value
+ or "\\" in value
+ or posix_path.is_absolute()
+ or windows_path.is_absolute()
+ or windows_path.drive
+ or windows_path.root
+ ):
+ raise ValueError(f"Unsafe managed runtime archive link target: {member_name}")
+ parts = list(base)
+ for part in posix_path.parts:
+ if part in {"", "."}:
+ continue
+ if part == "..":
+ if not parts:
+ raise ValueError(f"Unsafe managed runtime archive link target: {member_name}")
+ parts.pop()
+ else:
+ parts.append(part)
+ return tuple(parts)
+
+
+def _resolved_tar_symlink_target(
+ target: tuple[str, ...],
+ member_paths: Mapping[tuple[str, ...], tarfile.TarInfo],
+) -> tuple[str, ...]:
+ pending = list(target)
+ resolved: list[str] = []
+ visited: set[tuple[str, ...]] = set()
+ while pending:
+ resolved.append(pending.pop(0))
+ candidate = tuple(resolved)
+ member = member_paths.get(candidate)
+ if member is None or not member.issym():
+ continue
+ if candidate in visited:
+ raise ValueError(f"Managed runtime archive symlink cycle: {member.name}")
+ visited.add(candidate)
+ linked = _normalized_tar_link_target(
+ candidate[:-1],
+ member.linkname,
+ member.name,
+ )
+ resolved = []
+ pending = [*linked, *pending]
+ return tuple(resolved)
def archive_path_is_unsafe(value: str) -> bool:
diff --git a/core/show_runtime.py b/core/show_runtime.py
index a986e9738..38ff4b0f5 100644
--- a/core/show_runtime.py
+++ b/core/show_runtime.py
@@ -43,6 +43,12 @@ from storage.lock import (
from config import paths
from core.dependency_network import dependency_error_details, fetch_bytes, fetch_to_path, probe_url, redact_url
+from core.managed_runtime import (
+ ManagedRuntimeArchive,
+ ManagedRuntimeManager,
+ ManagedRuntimeManifest,
+ ManagedRuntimeSpec,
+)
from core.process_isolation import KILL_SIGNAL, isolated_subprocess_kwargs, signal_process_tree
from core.show_runtime_failures import (
ShowRuntimeFailureClass,
@@ -433,6 +439,319 @@ class ShowRuntimeAvailability:
}
+_SHOW_MANAGED_RUNTIME_SPEC = ManagedRuntimeSpec(
+ runtime_id="runtime",
+ manifest_resource=_RUNTIME_MANIFEST_RESOURCE,
+ version_field="runtime_version",
+ default_bin_path="node_modules/@avibe/show-runtime/dist/cli.js",
+ binary_artifact=False,
+ record_provider=_RUNTIME_SOURCE_MANIFEST,
+ metadata_filename_override=".vibe-show-runtime.json",
+ allow_legacy_missing_runtime_id=True,
+ staging_prefixes=("install-", "manifest-"),
+ replace_target_on_force=True,
+)
+
+
+class _ShowManifestRuntimeManager(ManagedRuntimeManager):
+ """Show policy and released-record declarations over the shared installer."""
+
+ def __init__(self, owner: "ShowRuntimeManager", *, offline: bool) -> None:
+ self.owner = owner
+ super().__init__(
+ spec=_SHOW_MANAGED_RUNTIME_SPEC,
+ runtime_dir=owner.runtime_dir,
+ manifest_path=owner.manifest_path,
+ manifest_url=owner.manifest_url,
+ offline=offline,
+ )
+
+ def load_manifest(self, *, allow_network: bool) -> ManagedRuntimeManifest | None:
+ return self._load_manifest(allow_network=allow_network)
+
+ def archive_for_platform(
+ self,
+ manifest: ManagedRuntimeManifest,
+ ) -> ManagedRuntimeArchive | None:
+ return self._manifest_archive_for_platform(manifest)
+
+ def verified_entrypoint(
+ self,
+ install_dir: Path,
+ manifest: ManagedRuntimeManifest,
+ archive: ManagedRuntimeArchive,
+ ) -> Path | None:
+ admitted = self._verified_manifest_binary(install_dir, manifest, archive)
+ return self._project_entrypoint(install_dir) if admitted is not None else None
+
+ def installed_result_entrypoint(self, result: Mapping[str, Any]) -> Path | None:
+ if not result.get("ok") or not isinstance(result.get("path"), str):
+ return None
+ install_dir = result.get("install_dir")
+ if not isinstance(install_dir, str):
+ return None
+ entrypoint = self._project_entrypoint(Path(install_dir))
+ return entrypoint if entrypoint.is_file() else None
+
+ def resolve_selected_entrypoint(self) -> Path | None:
+ manifest = self._load_manifest(allow_network=False)
+ if manifest is None or not self._manifest_installable(manifest):
+ return None
+ archive = self._manifest_archive_for_platform(manifest)
+ if archive is None:
+ return None
+ for install_dir in self._manifest_install_candidates(manifest, archive):
+ entrypoint = self._verified_manifest_binary(install_dir, manifest, archive)
+ if entrypoint is not None:
+ return self._project_entrypoint(install_dir)
+ return None
+
+ def _project_entrypoint(self, install_dir: Path) -> Path:
+ return install_dir / self.spec.default_bin_path
+
+ def install_candidates(
+ self,
+ manifest: ManagedRuntimeManifest,
+ archive: ManagedRuntimeArchive,
+ ) -> Iterator[Path]:
+ return self._manifest_install_candidates(manifest, archive)
+
+ def _manifest_installable(self, manifest: ManagedRuntimeManifest) -> bool:
+ node = _resolve_node_command()
+ if node is None:
+ self._install_reason = "runtime_node_missing"
+ return False
+ minimum_node = self._minimum_node(manifest)
+ if minimum_node and not _node_satisfies_requirement(_node_version(node), minimum_node):
+ self._install_reason = "runtime_node_unsupported"
+ return False
+ return True
+
+ def _parse_manifest(
+ self,
+ payload: bytes,
+ *,
+ loaded_from: str,
+ ) -> ManagedRuntimeManifest | None:
+ manifest = super()._parse_manifest(payload, loaded_from=loaded_from)
+ if manifest is None:
+ return None
+ if "minimum_node" in manifest.payload and not isinstance(
+ manifest.payload["minimum_node"],
+ str,
+ ):
+ self._install_reason = "runtime_manifest_invalid"
+ return None
+ return manifest
+
+ def _manifest_archive_for_platform(
+ self,
+ manifest: ManagedRuntimeManifest,
+ ) -> ManagedRuntimeArchive | None:
+ archive = super()._manifest_archive_for_platform(manifest)
+ if archive is not None and archive.bin_path != self.spec.default_bin_path:
+ self._install_reason = "runtime_manifest_invalid"
+ return None
+ return archive
+
+ def _binary_matches_manifest(
+ self,
+ binary: Path,
+ manifest: ManagedRuntimeManifest,
+ ) -> bool:
+ del binary, manifest
+ return True
+
+ def _manifest_identity_fields(self, manifest: ManagedRuntimeManifest) -> dict[str, str]:
+ minimum_node = self._minimum_node(manifest)
+ return {"minimum_node": minimum_node} if minimum_node else {}
+
+ def _metadata_matches_install_target(
+ self,
+ metadata: Mapping[str, Any],
+ target: Mapping[str, str],
+ ) -> bool:
+ if metadata.get("runtime_id") is None:
+ target = {key: value for key, value in target.items() if key != "minimum_node"}
+ return super()._metadata_matches_install_target(metadata, target)
+
+ def _manifest_install_candidates(
+ self,
+ manifest: ManagedRuntimeManifest,
+ archive: ManagedRuntimeArchive,
+ ) -> Iterator[Path]:
+ install_dir = self._manifest_install_dir(manifest, archive)
+ legacy_parent = install_dir.parent
+ yield install_dir
+ yield legacy_parent
+
+ try:
+ candidates = sorted(legacy_parent.iterdir(), key=lambda path: path.name)
+ except OSError:
+ return
+ for candidate in candidates:
+ if candidate == install_dir:
+ continue
+ try:
+ metadata = json.loads(
+ (candidate / self.spec.metadata_filename).read_text(encoding="utf-8")
+ )
+ except Exception:
+ continue
+ manifest_sha256 = metadata.get("manifest_sha256")
+ if not isinstance(manifest_sha256, str) or not _CONTENT_ADDRESSED_ARCHIVE_RE.fullmatch(
+ f"{manifest_sha256}.tgz"
+ ):
+ continue
+ previous_fingerprint = hashlib.sha256(
+ f"{manifest_sha256}:{archive.sha256}".encode("utf-8")
+ ).hexdigest()[:16]
+ if candidate.name == previous_fingerprint:
+ yield candidate
+
+ def _archive_cache_name(self, archive: ManagedRuntimeArchive) -> str:
+ return f"{archive.sha256}.tgz"
+
+ def _install_record_archive_name(
+ self,
+ metadata: Mapping[str, Any],
+ archive_name: str,
+ archive_sha256: str,
+ ) -> str:
+ del metadata, archive_name
+ return f"{archive_sha256}.tgz"
+
+ def _read_archive_provenance(self) -> set[tuple[str, str]]:
+ provenance = super()._read_archive_provenance()
+ downloads_dir = self.runtime_dir / "downloads"
+ try:
+ downloads_info = downloads_dir.lstat()
+ except FileNotFoundError:
+ return provenance
+ except OSError as exc:
+ raise OSError("downloads directory cannot be inspected") from exc
+ if _is_reparse_point(downloads_info) or not stat.S_ISDIR(downloads_info.st_mode):
+ raise OSError("downloads directory is not a confined directory")
+ try:
+ with os.scandir(downloads_dir) as entries:
+ for entry in entries:
+ match = _CONTENT_ADDRESSED_ARCHIVE_RE.fullmatch(entry.name)
+ claim = _ABANDONED_ARCHIVE_CLAIM_RE.fullmatch(entry.name)
+ if match is None and claim is None:
+ continue
+ info = entry.stat(follow_symlinks=False)
+ if not _is_exclusive_regular_file(info):
+ continue
+ provenance.add((entry.name, entry.name[:64]))
+ except OSError as exc:
+ raise OSError("downloads directory cannot be inspected") from exc
+ return provenance
+
+ def _archive_candidate_sha256(self, name: str, fd: int) -> str:
+ if _CONTENT_ADDRESSED_ARCHIVE_RE.fullmatch(name) or _ABANDONED_ARCHIVE_CLAIM_RE.fullmatch(name):
+ return name[:64]
+ return super()._archive_candidate_sha256(name, fd)
+
+ def _clean_downloaded_archives(
+ self,
+ *,
+ archive_provenance: set[tuple[str, str]],
+ protected_sha256s: set[str],
+ dry_run: bool,
+ ) -> tuple[dict[str, Any], set[str]]:
+ report, terminal_names = super()._clean_downloaded_archives(
+ archive_provenance=archive_provenance,
+ protected_sha256s=protected_sha256s,
+ dry_run=dry_run,
+ )
+ report["protected_count"] = len(protected_sha256s)
+ return report, terminal_names
+
+ def _record_matches_configured_source(self, metadata: Mapping[str, Any]) -> bool:
+ source = metadata.get("manifest_source")
+ configured_source = self.owner._configured_manifest_source()
+ return source == configured_source or (
+ isinstance(source, str)
+ and self.owner.manifest_url is not None
+ and source == f"cache:{self.owner.manifest_url}"
+ )
+
+ def _record_install_dir_matches(
+ self,
+ install_dir: Path,
+ metadata: Mapping[str, Any],
+ ) -> bool:
+ runtime_version = metadata.get("runtime_version")
+ platform_tag = metadata.get("platform")
+ archive_sha256 = metadata.get("archive_sha256")
+ manifest_sha256 = metadata.get("manifest_sha256")
+ if not all(
+ isinstance(value, str) and value
+ for value in (runtime_version, platform_tag, archive_sha256, manifest_sha256)
+ ):
+ return False
+ if not all(
+ _CONTENT_ADDRESSED_ARCHIVE_RE.fullmatch(f"{value}.tgz")
+ for value in (archive_sha256, manifest_sha256)
+ ):
+ return False
+ try:
+ parts = install_dir.relative_to((self.runtime_dir / "versions").resolve()).parts
+ except (OSError, ValueError):
+ return False
+ expected_prefix = (_safe_path_part(runtime_version), _safe_path_part(platform_tag))
+ if parts[:2] != expected_prefix:
+ return False
+ if len(parts) == 2:
+ return True
+ if len(parts) != 3:
+ return False
+ current_fingerprint = hashlib.sha256(
+ f"{runtime_version}:{platform_tag}:{archive_sha256}".encode("utf-8")
+ ).hexdigest()[:16]
+ previous_fingerprint = hashlib.sha256(
+ f"{manifest_sha256}:{archive_sha256}".encode("utf-8")
+ ).hexdigest()[:16]
+ return parts[2] in {current_fingerprint, previous_fingerprint}
+
+ def _install_dir_is_protected(self, install_dir: Path, protected: set[Path]) -> bool:
+ return any(
+ install_dir == item or install_dir in item.parents or item in install_dir.parents
+ for item in protected
+ )
+
+ def _retention_ranked_installs(self, installs, protected):
+ resolved_by_path = {install.path: install.path.resolve() for install in installs}
+ return [
+ install
+ for install in installs
+ if not any(
+ resolved_by_path[install.path] in other.parents
+ for other in resolved_by_path.values()
+ if other != resolved_by_path[install.path]
+ )
+ and not self._install_dir_is_protected(
+ resolved_by_path[install.path],
+ protected,
+ )
+ ]
+
+ def _manifest_path_read_error_reason(self) -> str:
+ return "runtime_manifest_invalid"
+
+ def _reason(self, suffix: str) -> str:
+ aliases = {
+ "install_lock_failed": "runtime_install_guard_unavailable",
+ "install_missing_binary": "runtime_install_missing_bin",
+ }
+ return aliases.get(suffix, f"runtime_{suffix}")
+
+ @staticmethod
+ def _minimum_node(manifest: ManagedRuntimeManifest) -> str | None:
+ value = manifest.payload.get("minimum_node")
+ return value if isinstance(value, str) and value else None
+
+
class ShowRuntimeManager:
def __init__(
self,
@@ -1253,7 +1572,12 @@ class ShowRuntimeManager:
if preflight is not None:
admission, operation = preflight
else:
- acquired, guard_reason = stack.enter_context(self._install_guard_locked())
+ guard = (
+ contextlib.nullcontext((True, None))
+ if self.runtime_source == _RUNTIME_SOURCE_MANIFEST
+ else self._install_guard_locked()
+ )
+ acquired, guard_reason = stack.enter_context(guard)
if not acquired:
command = None if force else self._safe_installed_managed_runtime_command(offline=offline)
if command:
@@ -1306,7 +1630,15 @@ class ShowRuntimeManager:
else self._publish_install_availability(install_reason=reason)
)
operation = _ShowRuntimeOperationOutcome(
- _ShowRuntimeOperationState.FAILED,
+ (
+ _ShowRuntimeOperationState.NOT_APPLICABLE
+ if reason
+ in {
+ "runtime_install_already_running",
+ "runtime_install_guard_unavailable",
+ }
+ else _ShowRuntimeOperationState.FAILED
+ ),
reason,
)
except OSError:
@@ -1419,7 +1751,8 @@ class ShowRuntimeManager:
if self._managed_command:
return self._publish_install_availability(command=self._managed_command, policy_reason=reason)
if self.runtime_source == _RUNTIME_SOURCE_MANIFEST:
- disk_install = self._persisted_manifest_disk_install()
+ manager = self._shared_manifest_manager(offline=True)
+ disk_install = self._shared_manifest_disk_install(manager)
return self._publish_install_availability(
command=disk_install.command if disk_install else None,
install_state=(ShowRuntimeInstallState.INSTALLED if disk_install else ShowRuntimeInstallState.ABSENT),
@@ -1512,15 +1845,7 @@ class ShowRuntimeManager:
def _remove_managed_runtime_tree_for_replacement(self, path: Path, *, label: str) -> bool:
"""Invalidate cached install facts before removing managed runtime bytes."""
- self._managed_command = None
- self._availability = replace(
- self._availability,
- install=ShowRuntimeInstallState.ABSENT,
- command=None,
- install_reason=None,
- install_failure_class=None,
- install_recovery_action=None,
- )
+ self._invalidate_managed_runtime_projection()
try:
if os.path.lexists(path):
shutil.rmtree(path)
@@ -1533,6 +1858,17 @@ class ShowRuntimeManager:
return False
return True
+ def _invalidate_managed_runtime_projection(self) -> None:
+ self._managed_command = None
+ self._availability = replace(
+ self._availability,
+ install=ShowRuntimeInstallState.ABSENT,
+ command=None,
+ install_reason=None,
+ install_failure_class=None,
+ install_recovery_action=None,
+ )
+
def _install_managed_runtime_locked(
self,
*,
@@ -1579,16 +1915,15 @@ class ShowRuntimeManager:
def _clean_after_managed_install(self, command: list[str]) -> None:
try:
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(
+ result = self._shared_manifest_manager(offline=True).clean(
keep_previous=_MANAGED_RUNTIME_ROLLBACK_INSTALLS,
- manifest_source=(_PACKAGED_RUNTIME_MANIFEST_SOURCE if packaged else _CUSTOM_MANIFEST_LINEAGE),
- protected_install_dirs=protected_install_dirs,
)
+ removed = result.get("removed", [])
if removed:
logger.info("Removed %d stale managed Show Runtime install(s)", len(removed))
- archives = self._clean_downloaded_archives()
+ archives = result.get("archives", {})
+ else:
+ archives = self._clean_downloaded_archives()
if archives.get("removed_count"):
logger.info(
"Removed %d stale Show Runtime archive(s), reclaimed %d byte(s)",
@@ -1606,23 +1941,40 @@ class ShowRuntimeManager:
else None
)
configured_command = explicit_availability.command if explicit_availability else None
- disk_install = (
- self._persisted_manifest_disk_install()
+ effective_offline = self.offline if offline is None else offline
+ manifest_manager = (
+ self._shared_manifest_manager(offline=effective_offline)
if explicit_availability is None and self.runtime_source == _RUNTIME_SOURCE_MANIFEST
else None
)
manifest = (
- self._load_runtime_manifest(offline=offline)
- if explicit_availability is None and self.runtime_source == _RUNTIME_SOURCE_MANIFEST
+ manifest_manager.load_manifest(allow_network=not effective_offline)
+ if manifest_manager is not None
+ else None
+ )
+ archive: ManagedRuntimeArchive | ShowRuntimeArchive | None = (
+ manifest_manager.archive_for_platform(manifest)
+ if manifest_manager is not None and manifest is not None
+ else None
+ )
+ manifest_reason = manifest_manager._install_reason if manifest_manager is not None else None
+ manifest_download_error = (
+ manifest_manager._download_error if manifest_manager is not None else None
+ )
+ disk_install = (
+ self._shared_manifest_disk_install(manifest_manager, adopt_evidence=False)
+ if manifest_manager is not None
else None
)
platform_tag = _runtime_platform_tag()
node = _resolve_node_command()
node_version = _node_version(node) if node else None
- node_supported = _node_satisfies_requirement(node_version, manifest.minimum_node) if manifest else None
+ minimum_node = (
+ _ShowManifestRuntimeManager._minimum_node(manifest) if manifest else None
+ )
+ node_supported = _node_satisfies_requirement(node_version, minimum_node) if manifest else None
installed_command: list[str] | None = configured_command
installed_dir: Path | None = None
- archive: ShowRuntimeArchive | None = None
archive_status: dict[str, Any] | None = None
installed_runtime_version: str | None = None
installed_matches: bool | None = None
@@ -1640,18 +1992,17 @@ class ShowRuntimeManager:
if manifest_status is None:
manifest_status = _persisted_manifest_status_payload(disk_install.metadata)
archive_status = _persisted_archive_status_payload(disk_install.metadata)
- if manifest:
- archive = manifest.archives.get(platform_tag)
if archive:
- for candidate in self._manifest_install_candidates(manifest, archive):
- if not self._manifest_install_matches(candidate, manifest, archive):
+ for candidate in manifest_manager.install_candidates(manifest, archive):
+ entrypoint = manifest_manager.verified_entrypoint(candidate, manifest, archive)
+ if entrypoint is None:
continue
installed = True
installed_dir = candidate
installed_runtime_version = manifest.runtime_version
installed_matches = True
if node and node_supported is not False:
- installed_command = self._manifest_runtime_command(candidate, node)
+ installed_command = [*node, str(entrypoint)]
if installed_command:
break
elif explicit_availability is None and self.runtime_source == _RUNTIME_SOURCE_ARCHIVE:
@@ -1697,24 +2048,39 @@ class ShowRuntimeManager:
"install": install_payload,
"runtime": runtime_payload,
"command": installed_command,
- "reason": explicit_availability.reason if explicit_availability else self._install_reason,
- "download_error": None if explicit_availability else self._download_error,
+ "reason": (
+ explicit_availability.reason
+ if explicit_availability
+ else manifest_reason or self._install_reason
+ if manifest_manager is not None
+ else self._install_reason
+ ),
+ "download_error": (
+ None
+ if explicit_availability
+ else manifest_download_error or self._download_error
+ if manifest_manager is not None
+ else self._download_error
+ ),
}
def probe_archive_reachability(self, *, timeout: float = 10.0) -> dict[str, Any]:
"""Check the selected archive without downloading its body or mutating the cache."""
archive_url: str | None = None
if self.runtime_source == _RUNTIME_SOURCE_MANIFEST:
- manifest = self._load_runtime_manifest()
+ manager = self._shared_manifest_manager(offline=self.offline)
+ manifest = manager.load_manifest_for_diagnostics()
if not manifest:
+ self._adopt_shared_manifest_evidence(manager)
return {
"ok": False,
"checked": False,
"reason": self._install_reason or "runtime_manifest_missing",
"download_error": self._download_error,
}
- archive = self._manifest_archive_for_platform(manifest)
+ archive = manager.archive_for_platform(manifest)
if not archive:
+ self._adopt_shared_manifest_evidence(manager)
return {
"ok": False,
"checked": False,
@@ -1946,6 +2312,20 @@ class ShowRuntimeManager:
return not self._preview_lock_missing()
def clean(self, *, keep_previous: int = 1, dry_run: bool = False) -> dict[str, Any]:
+ if self.runtime_source == _RUNTIME_SOURCE_MANIFEST:
+ result = self._shared_manifest_manager(offline=True).clean(
+ keep_previous=keep_previous,
+ dry_run=dry_run,
+ )
+ if "archives" not in result:
+ reason = result.get("reason")
+ skipped_reason = (
+ _SKIPPED_ARCHIVE_REASON_INSTALL_RUNNING
+ if reason == "runtime_install_already_running"
+ else _SKIPPED_ARCHIVE_REASON_INSPECTION_FAILED
+ )
+ result["archives"] = self._skipped_archive_report(skipped_reason)
+ return {"dry_run": dry_run, **result}
removed: list[str] = []
try:
return self._clean_locked(keep_previous=keep_previous, dry_run=dry_run, removed=removed)
@@ -2698,16 +3078,88 @@ class ShowRuntimeManager:
node = _resolve_node_command()
if not node:
return None
- disk_install = self._persisted_manifest_disk_install()
- manifest = self._load_runtime_manifest(offline=offline)
- if not manifest:
- return disk_install.command if disk_install else None
- if not self._manifest_node_supported(node, manifest):
+ manager = self._shared_manifest_manager(offline=self.offline if offline is None else offline)
+ entrypoint = manager.resolve_selected_entrypoint()
+ if entrypoint is not None:
+ self._adopt_shared_manifest_evidence(manager)
+ return [*node, str(entrypoint)]
+
+ source_reason = manager._install_reason
+ source_download_error = manager._download_error
+ if source_reason not in {
+ "runtime_manifest_download_failed",
+ "runtime_manifest_invalid",
+ "runtime_manifest_missing",
+ "runtime_manifest_unavailable_offline",
+ }:
+ self._adopt_shared_manifest_evidence(manager)
return None
- archive = self._manifest_archive_for_platform(manifest)
- if not archive:
+
+ disk_install = self._shared_manifest_disk_install(manager, adopt_evidence=False)
+ manager._install_reason = source_reason
+ manager._download_error = source_download_error
+ self._adopt_shared_manifest_evidence(manager)
+ return disk_install.command if disk_install else None
+
+ def _shared_manifest_disk_install(
+ self,
+ manager: _ShowManifestRuntimeManager,
+ *,
+ adopt_evidence: bool = True,
+ ) -> _ShowRuntimeDiskInstall | None:
+ admitted_entrypoint = manager.resolve_binary()
+ if adopt_evidence:
+ self._adopt_shared_manifest_evidence(manager)
+ if admitted_entrypoint is None:
return None
- return self._verified_manifest_runtime_command_for_manifest(manifest, archive, node)
+ try:
+ pointer = json.loads((self.runtime_dir / "current.json").read_text(encoding="utf-8"))
+ install_dir = Path(pointer["install_dir"]).resolve(strict=True)
+ metadata = json.loads(
+ (install_dir / manager.spec.metadata_filename).read_text(encoding="utf-8")
+ )
+ status_metadata = dict(metadata)
+ status_metadata["manifest_sha256"] = pointer["manifest_sha256"]
+ except (KeyError, OSError, RuntimeError, TypeError, ValueError):
+ return None
+ entrypoint = manager._project_entrypoint(install_dir)
+ if not entrypoint.is_file():
+ return None
+ node = _resolve_node_command()
+ command = [*node, str(entrypoint)] if node else None
+ return _ShowRuntimeDiskInstall(
+ install_dir=install_dir,
+ command=command,
+ metadata=status_metadata,
+ )
+
+ def _shared_manifest_manager(self, *, offline: bool) -> _ShowManifestRuntimeManager:
+ return _ShowManifestRuntimeManager(self, offline=offline)
+
+ def _adopt_shared_manifest_evidence(
+ self,
+ manager: _ShowManifestRuntimeManager,
+ result: Mapping[str, Any] | None = None,
+ ) -> None:
+ reason = result.get("reason") if result is not None else manager._install_reason
+ download_error = (
+ result.get("download_error") if result is not None else manager._download_error
+ )
+ self._download_error = download_error if isinstance(download_error, dict) else None
+ if reason:
+ provenance = "configured" if self.manifest_path or self.manifest_url else "packaged"
+ retryable = (
+ self._download_error.get("retryable")
+ if self._download_error is not None
+ else None
+ )
+ self._record_install_failure(
+ str(reason),
+ provenance=provenance,
+ retryable=retryable if isinstance(retryable, bool) else None,
+ )
+ else:
+ self._install_reason = None
@contextlib.contextmanager
def _install_guard_locked(self, *, timeout_seconds: float = 0.0):
@@ -2843,85 +3295,23 @@ class ShowRuntimeManager:
if not node:
self._install_reason = "runtime_node_missing"
return None
- manifest = self._load_runtime_manifest(offline=offline)
- if not manifest:
- return None
- 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)
- verified_existing_command = self._verified_manifest_runtime_command_for_manifest(
- manifest,
- archive,
- node,
- )
- if verified_existing_command and not force:
- install_dirs = self._manifest_install_dirs_for_command(verified_existing_command)
- verified_install_dir = min(install_dirs, key=lambda path: str(path)) if install_dirs else None
- if verified_install_dir is None:
- logger.warning(
- "Verified Show Runtime command has no discoverable install directory; skipping current pointer update"
- )
- else:
- self._write_current_manifest_pointer(manifest, archive, verified_install_dir)
- return self._managed_install_operation_command(
- verified_existing_command,
- replacement_required=False,
- )
- archive_path = self._resolve_manifest_archive(
- archive,
- offline=offline,
- provenance=("packaged" if manifest.source == _PACKAGED_RUNTIME_MANIFEST_SOURCE else "configured"),
+ if force:
+ self._invalidate_managed_runtime_projection()
+ manager = self._shared_manifest_manager(offline=offline)
+ result = manager.ensure(force=force)
+ self._adopt_shared_manifest_evidence(manager, result)
+ entrypoint = manager.installed_result_entrypoint(result)
+ if (
+ not force
+ and result.get("reason") == "runtime_install_guard_unavailable"
+ ):
+ entrypoint = manager.resolve_selected_entrypoint()
+ command = [*node, str(entrypoint)] if entrypoint is not None else None
+ return self._managed_install_operation_command(
+ command,
+ replacement_required=force,
+ replacement_completed=bool(force and result.get("changed")),
)
- if not archive_path:
- return self._managed_install_operation_command(
- verified_existing_command,
- replacement_required=force,
- )
- self.runtime_dir.mkdir(parents=True, exist_ok=True)
- tmp_dir = Path(tempfile.mkdtemp(prefix="manifest-", dir=self.runtime_dir))
- try:
- with tarfile.open(archive_path, "r:gz") as tar:
- _safe_extract_tar(tar, tmp_dir)
- command = self._manifest_runtime_command(tmp_dir, node)
- if not command:
- self._install_reason = "runtime_install_missing_bin"
- return self._managed_install_operation_command(
- verified_existing_command,
- replacement_required=force,
- )
- if os.path.lexists(install_dir):
- if not self._remove_managed_runtime_tree_for_replacement(install_dir, label="manifest"):
- return self._managed_install_operation_command(
- None,
- replacement_required=force,
- )
- verified_existing_command = None
- install_dir.parent.mkdir(parents=True, exist_ok=True)
- shutil.move(str(tmp_dir), str(install_dir))
- self._write_manifest_install_metadata(install_dir, manifest, archive)
- self._write_current_manifest_pointer(manifest, archive, install_dir)
- installed_command = self._manifest_runtime_command(install_dir, node)
- if not installed_command:
- self._install_reason = "runtime_install_missing_bin"
- # The staged tree was moved onto the managed identity before this command resolved.
- return self._managed_install_operation_command(
- installed_command,
- replacement_required=force,
- replacement_completed=force and installed_command is not None,
- )
- except Exception:
- logger.exception("Failed to install manifest Show Runtime")
- self._install_reason = "runtime_install_failed"
- return self._managed_install_operation_command(
- verified_existing_command,
- replacement_required=force,
- )
- finally:
- if tmp_dir.exists():
- shutil.rmtree(tmp_dir, ignore_errors=True)
def _load_runtime_manifest(self, *, offline: bool | None = None) -> ShowRuntimeManifest | None:
payload: bytes | None = None
@@ -3690,15 +4080,23 @@ def _normalize_runtime_source(value: str | None) -> str:
return aliases.get(normalized, normalized or _RUNTIME_SOURCE_MANIFEST)
-def _manifest_status_payload(manifest: ShowRuntimeManifest | None) -> dict[str, Any] | None:
+def _manifest_status_payload(
+ manifest: ManagedRuntimeManifest | ShowRuntimeManifest | None,
+) -> dict[str, Any] | None:
if manifest is None:
return None
+ if isinstance(manifest, ManagedRuntimeManifest):
+ minimum_node = _ShowManifestRuntimeManager._minimum_node(manifest)
+ source = manifest.loaded_from
+ else:
+ minimum_node = manifest.minimum_node
+ source = manifest.source
return {
"schema_version": manifest.schema_version,
"runtime_version": manifest.runtime_version,
- "minimum_node": manifest.minimum_node,
+ "minimum_node": minimum_node,
"sha256": manifest.digest,
- "source": manifest.source,
+ "source": source,
"platforms": sorted(manifest.archives),
}
@@ -3737,7 +4135,9 @@ def _runtime_download_error(exc: BaseException, url: str) -> dict[str, Any]:
return dependency_error_details(exc, url)
-def _archive_status_payload(archive: ShowRuntimeArchive | None) -> dict[str, Any] | None:
+def _archive_status_payload(
+ archive: ManagedRuntimeArchive | ShowRuntimeArchive | None,
+) -> dict[str, Any] | None:
if archive is None:
return None
return {
diff --git a/tests/test_managed_runtime.py b/tests/test_managed_runtime.py
index 0e37b47b9..e1683d13b 100644
--- a/tests/test_managed_runtime.py
+++ b/tests/test_managed_runtime.py
@@ -200,6 +200,103 @@ def _fixture_runtime_manager(
)
+def test_force_install_uses_sibling_target_by_default(
+ tmp_path: Path,
+) -> None:
+ manifest_path = tmp_path / "manifest.json"
+ _write_fixture_runtime_release(
+ tmp_path,
+ manifest_path,
+ label="default-force",
+ version="1.0.0",
+ )
+ manager = _fixture_runtime_manager(tmp_path / "runtime", manifest_path=manifest_path)
+ installed = manager.ensure()
+
+ refreshed = manager.ensure(force=True)
+
+ assert refreshed["ok"] is True
+ assert refreshed["install_dir"] != installed["install_dir"]
+ assert Path(installed["install_dir"]).is_dir()
+
+
+def test_force_target_replacement_failure_does_not_publish_success(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manifest_path = tmp_path / "manifest.json"
+ _write_fixture_runtime_release(
+ tmp_path,
+ manifest_path,
+ label="exact-force",
+ version="1.0.0",
+ )
+ manager = FixtureRuntimeManager(
+ spec=ManagedRuntimeSpec(
+ runtime_id="fixture-exact-force",
+ manifest_resource="unused.json",
+ version_field="runtime_version",
+ default_bin_path="bin/runtime",
+ replace_target_on_force=True,
+ ),
+ runtime_dir=tmp_path / "runtime",
+ manifest_path=manifest_path,
+ )
+ installed = manager.ensure()
+ pointer_path = manager.runtime_dir / "current.json"
+ pointer_before = pointer_path.read_bytes()
+ binary_before = Path(installed["path"]).read_bytes()
+ monkeypatch.setattr(manager, "_remove_install_target_for_replacement", lambda _path: False)
+
+ failed = manager.ensure(force=True)
+
+ assert failed["ok"] is False
+ assert failed["reason"] == "fixture-exact-force_install_failed"
+ assert pointer_path.read_bytes() == pointer_before
+ assert Path(installed["path"]).read_bytes() == binary_before
+
+
+def test_force_target_replacement_rejects_symlinked_canonical_leaf(
+ tmp_path: Path,
+) -> None:
+ manifest_path = tmp_path / "manifest.json"
+ _write_fixture_runtime_release(
+ tmp_path,
+ manifest_path,
+ label="symlink-force",
+ version="1.0.0",
+ )
+ manager = FixtureRuntimeManager(
+ spec=ManagedRuntimeSpec(
+ runtime_id="fixture-symlink-force",
+ manifest_resource="unused.json",
+ version_field="runtime_version",
+ default_bin_path="bin/runtime",
+ replace_target_on_force=True,
+ ),
+ runtime_dir=tmp_path / "runtime",
+ manifest_path=manifest_path,
+ )
+ installed = manager.ensure()
+ canonical = Path(installed["install_dir"])
+ pointer_path = manager.runtime_dir / "current.json"
+ pointer_before = pointer_path.read_bytes()
+ redirected = canonical.parent / "redirected"
+ redirected.mkdir()
+ sentinel = redirected / "sentinel"
+ sentinel.write_text("preserve", encoding="utf-8")
+ shutil.rmtree(canonical)
+ canonical.symlink_to(redirected, target_is_directory=True)
+
+ failed = manager.ensure(force=True)
+
+ assert failed["ok"] is False
+ assert failed["reason"] == "fixture-symlink-force_install_failed"
+ assert canonical.is_symlink()
+ assert sentinel.read_text(encoding="utf-8") == "preserve"
+ assert pointer_path.read_bytes() == pointer_before
+
+
def _write_fixture_runtime_release(
root: Path,
manifest_path: Path,
@@ -240,6 +337,35 @@ def _write_fixture_runtime_release(
return archive_path
+def test_binary_artifact_manifest_still_requires_binary_sha256(tmp_path: Path) -> None:
+ manifest_path = tmp_path / "manifest.json"
+ _write_fixture_runtime_release(
+ tmp_path,
+ manifest_path,
+ label="missing-binary-digest",
+ version="1.0.0",
+ )
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
+ archive = payload["archives"][managed_runtime.runtime_platform_tag()]
+ archive.pop("binary_sha256")
+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")
+ manager = FixtureRuntimeManager(
+ spec=ManagedRuntimeSpec(
+ runtime_id="fixture-binary-digest",
+ manifest_resource="unused.json",
+ version_field="runtime_version",
+ default_bin_path="bin/runtime",
+ ),
+ runtime_dir=tmp_path / "runtime",
+ manifest_path=manifest_path,
+ )
+
+ result = manager.ensure()
+
+ assert result["ok"] is False
+ assert result["reason"] == "fixture-binary-digest_manifest_invalid"
+
+
def _install_fixture_runtime_release(
manager: FixtureRuntimeManager,
root: Path,
@@ -1155,6 +1281,51 @@ def test_clean_preserves_remote_manifest_cache_for_offline_resolution(
assert Path(reused["install_dir"]) == Path(installed["install_dir"])
+def test_archive_probe_fetches_remote_manifest_without_mutating_cache(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manifest_path = tmp_path / "remote-manifest.json"
+ _write_fixture_runtime_release(
+ tmp_path,
+ manifest_path,
+ label="diagnostic",
+ version="1.0.0",
+ )
+ manifest_url = "https://example.test/runtime-manifest.json"
+ manager = _fixture_runtime_manager(
+ tmp_path / "runtime",
+ manifest_url=manifest_url,
+ )
+ cached_manifest = manager._remote_manifest_cache_path()
+ cached_manifest.parent.mkdir(parents=True)
+ cached_manifest.write_bytes(b"existing cached manifest")
+ monkeypatch.setattr(
+ managed_runtime,
+ "fetch_bytes",
+ lambda url, **_kwargs: (
+ manifest_path.read_bytes()
+ if url == manifest_url
+ else pytest.fail(f"unexpected fetch: {url}")
+ ),
+ )
+ monkeypatch.setattr(
+ managed_runtime,
+ "write_atomic",
+ lambda *_args, **_kwargs: pytest.fail("diagnostic load wrote the manifest cache"),
+ )
+ monkeypatch.setattr(
+ managed_runtime,
+ "probe_url",
+ lambda *_args, **_kwargs: {"ok": True, "checked": True},
+ )
+
+ result = manager.probe_archive_reachability()
+
+ assert result == {"ok": True, "checked": True}
+ assert cached_manifest.read_bytes() == b"existing cached manifest"
+
+
def test_clean_archive_candidates_require_known_shape_maturity_and_unprotected_digest(
tmp_path: Path,
) -> None:
diff --git a/tests/test_managed_runtime_composite_artifacts.py b/tests/test_managed_runtime_composite_artifacts.py
index 289b86833..4c76d5c56 100644
--- a/tests/test_managed_runtime_composite_artifacts.py
+++ b/tests/test_managed_runtime_composite_artifacts.py
@@ -181,6 +181,92 @@ def test_released_show_links_install_through_shared_manager(
assert (install_dir / row[2]).stat().st_ino == (install_dir / row[6]).stat().st_ino
+ "platform",
+ (
+ "darwin-arm64",
+ "darwin-x64",
+ "linux-arm64",
+ "linux-x64",
+ "win32-arm64",
+ "win32-x64",
+ ),
+)
+def test_released_show_composite_shape_installs_through_production_adapter(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ platform: str,
+) -> None:
+ fixture = _released_fixture()
+ release = fixture["release"]
+ released_manifest_bytes = (FIXTURE_ROOT / release["manifest_name"]).read_bytes()
+ assert hashlib.sha256(released_manifest_bytes).hexdigest() == release["manifest_sha256"]
+ released_manifest = json.loads(released_manifest_bytes)
+ released_archive = released_manifest["archives"][platform]
+ provenance = fixture["archives"][platform]["provenance"]
+ assert {
+ "name": released_archive["name"],
+ "sha256": released_archive["sha256"],
+ "size": released_archive["size"],
+ } == {key: provenance[key] for key in ("name", "sha256", "size")}
+
+ archive_fixture = fixture["archives"][platform]
+ archive_path = _write_released_shape_archive(tmp_path, platform, archive_fixture)
+ cli_path = archive_fixture["entrypoints"]["cli_path"][1]
+ manifest_path = tmp_path / f"{platform}-manifest.json"
+ manifest_path.write_text(
+ json.dumps(
+ {
+ "schema_version": released_manifest["schema_version"],
+ "runtime_version": released_manifest["runtime_version"],
+ "minimum_node": released_manifest["minimum_node"],
+ "archives": {
+ platform: {
+ "name": archive_path.name,
+ "url": archive_path.as_uri(),
+ "sha256": hashlib.sha256(archive_path.read_bytes()).hexdigest(),
+ "size": archive_path.stat().st_size,
+ "bin_path": cli_path,
+ }
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: platform)
+ monkeypatch.setattr(show_runtime, "_runtime_platform_tag", lambda: platform)
+ monkeypatch.setattr(
+ show_runtime,
+ "_resolve_command",
+ lambda command: ["/bin/node"] if command == "node" else None,
+ )
+ monkeypatch.setattr(show_runtime, "_node_version", lambda _node: (22, 12, 0))
+ monkeypatch.delattr(tarfile, "data_filter", raising=False)
+ runtime_dir = tmp_path / f"runtime-{platform}"
+ manager = show_runtime.ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_path=manifest_path,
+ )
+
+ result = manager.prepare()
+
+ assert result["ok"] is True
+ pointer = json.loads((runtime_dir / "current.json").read_text(encoding="utf-8"))
+ install_dir = Path(pointer["install_dir"])
+ assert result["command"] == ["/bin/node", str(install_dir / cli_path)]
+ assert (install_dir / cli_path).read_bytes() == CLI_PAYLOAD
+ for key in ("esbuild_bin", "esbuild_package", "esbuild_platform"):
+ assert (install_dir / archive_fixture["entrypoints"][key][1]).read_bytes() == ESBUILD_PAYLOAD
+ for row in archive_fixture["links"]:
+ linked = install_dir / row[2]
+ if row[1] == "symlink":
+ assert linked.is_symlink()
+ assert linked.exists()
+ else:
+ assert linked.stat().st_ino == (install_dir / row[6]).stat().st_ino
+
+
def _write_link_probe(path: Path, *, escaping: bool = False) -> None:
with tarfile.open(path, "w") as archive:
if escaping:
@@ -261,7 +347,7 @@ def _write_fallback_escape_probe(path: Path) -> None:
archive.addfile(regular, io.BytesIO(payload))
-def test_shared_fallback_refuses_links_before_extraction(
+def test_shared_fallback_rejects_symlink_pivot_before_extraction(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -278,7 +364,7 @@ def test_shared_fallback_refuses_links_before_extraction(
with tarfile.open(archive_path) as archive:
with pytest.raises(
ValueError,
- match=r"^Managed runtime archive link requires tarfile\.data_filter: a$",
+ match=r"^Managed runtime archive path/type collision: a/x$",
):
managed_runtime.safe_extract_tar(archive, destination)
@@ -288,12 +374,16 @@ def test_shared_fallback_refuses_links_before_extraction(
assert not destination.exists()
-def test_shared_fallback_refuses_hardlinks_before_extraction(
+def test_shared_fallback_materializes_confined_hardlinks(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
archive_path = tmp_path / "fallback-hardlink.tar"
with tarfile.open(archive_path, "w") as archive:
+ root = tarfile.TarInfo(".")
+ root.type = tarfile.DIRTYPE
+ root.mode = 0o755
+ archive.addfile(root)
payload = b"payload\n"
regular = tarfile.TarInfo("root/regular")
regular.size = len(payload)
@@ -305,19 +395,116 @@ def test_shared_fallback_refuses_hardlinks_before_extraction(
destination = tmp_path / "fallback-hardlink"
monkeypatch.delattr(tarfile, "data_filter", raising=False)
+ with tarfile.open(archive_path) as archive:
+ managed_runtime.safe_extract_tar(archive, destination)
+
+ assert (destination / "root/regular").read_bytes() == payload
+ assert (destination / "root/hardlink").stat().st_ino == (
+ destination / "root/regular"
+ ).stat().st_ino
+
+
+def test_shared_fallback_rejects_hardlink_target_substitution(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ archive_path = tmp_path / "fallback-hardlink-substitution.tar"
+ with tarfile.open(archive_path, "w") as archive:
+ payload = b"payload\n"
+ regular = tarfile.TarInfo("root/regular")
+ regular.size = len(payload)
+ archive.addfile(regular, io.BytesIO(payload))
+ symlink = tarfile.TarInfo("root/symlink")
+ symlink.type = tarfile.SYMTYPE
+ symlink.linkname = "regular"
+ archive.addfile(symlink)
+ hardlink = tarfile.TarInfo("root/hardlink")
+ hardlink.type = tarfile.LNKTYPE
+ hardlink.linkname = "root/symlink"
+ archive.addfile(hardlink)
+ destination = tmp_path / "fallback-hardlink-substitution"
+ monkeypatch.delattr(tarfile, "data_filter", raising=False)
+
with tarfile.open(archive_path) as archive:
with pytest.raises(
ValueError,
- match=(
- r"^Managed runtime archive link requires "
- r"tarfile\.data_filter: root/hardlink$"
- ),
+ match=r"^Unsafe managed runtime archive hardlink target: root/hardlink$",
):
managed_runtime.safe_extract_tar(archive, destination)
assert not destination.exists()
+ "invalid_shape",
+ ("unsupported", "unsafe-path", "duplicate-path", "symlink-cycle"),
+)
+def test_shared_fallback_rejects_invalid_archive_before_writing(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ invalid_shape: str,
+) -> None:
+ archive_path = tmp_path / f"fallback-{invalid_shape}.tar"
+ with tarfile.open(archive_path, "w") as archive:
+ if invalid_shape == "unsupported":
+ member = tarfile.TarInfo("root/fifo")
+ member.type = tarfile.FIFOTYPE
+ archive.addfile(member)
+ elif invalid_shape == "unsafe-path":
+ member = tarfile.TarInfo("../outside")
+ member.size = 1
+ archive.addfile(member, io.BytesIO(b"x"))
+ elif invalid_shape == "duplicate-path":
+ for name in ("root/file", "root/./file"):
+ member = tarfile.TarInfo(name)
+ member.size = 1
+ archive.addfile(member, io.BytesIO(b"x"))
+ else:
+ first = tarfile.TarInfo("root/first")
+ first.type = tarfile.SYMTYPE
+ first.linkname = "second"
+ archive.addfile(first)
+ second = tarfile.TarInfo("root/second")
+ second.type = tarfile.SYMTYPE
+ second.linkname = "first"
+ archive.addfile(second)
+ destination = tmp_path / "destination"
+ monkeypatch.delattr(tarfile, "data_filter", raising=False)
+
+ with tarfile.open(archive_path) as archive:
+ with pytest.raises(ValueError):
+ managed_runtime.safe_extract_tar(archive, destination)
+
+ assert not destination.exists()
+ assert not (tmp_path / "outside").exists()
+
+
+def test_shared_fallback_keeps_order_dependent_links_confined(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ archive_path = tmp_path / "fallback-ordering.tar"
+ _write_ordering_probe(archive_path)
+ case = tmp_path / "fallback-ordering"
+ destination = case / "destination"
+ destination.mkdir(parents=True)
+ outside = case / "outside"
+ outside.write_bytes(b"outside\n")
+ outside_stat = outside.stat()
+ monkeypatch.delattr(tarfile, "data_filter", raising=False)
+
+ with tarfile.open(archive_path) as archive:
+ managed_runtime.safe_extract_tar(archive, destination)
+
+ assert outside.read_bytes() == b"outside\n"
+ assert outside.stat().st_ino == outside_stat.st_ino
+ assert outside.stat().st_nlink == outside_stat.st_nlink
+ assert (destination / "inside-hard").stat().st_ino == (
+ destination / "outside"
+ ).stat().st_ino
+ assert (destination / "inside-hard").stat().st_ino != outside.stat().st_ino
+
+
@pytest.mark.parametrize(
("_name", "extractor"),
(
@@ -422,6 +609,8 @@ def test_filter_capability_path(
if supports_filter:
expected_calls = ["data"]
+ elif _name == "shared":
+ expected_calls = []
elif detects_before_extract:
expected_calls = [None]
else:
diff --git a/tests/test_show_runtime_archive_cleanup.py b/tests/test_show_runtime_archive_cleanup.py
index 6890d544e..39dc91f47 100644
--- a/tests/test_show_runtime_archive_cleanup.py
+++ b/tests/test_show_runtime_archive_cleanup.py
@@ -15,7 +15,7 @@ from pathlib import Path
import pytest
-from core.show_runtime import ShowRuntimeManager
+from core.show_runtime import ShowRuntimeManager, _ShowManifestRuntimeManager
def _make_manager(tmp_path: Path) -> ShowRuntimeManager:
@@ -38,12 +38,19 @@ def _sha(index: int) -> str:
def _write_current_pointer(manager: ShowRuntimeManager, sha256: str, install_dir: Path | None = None) -> None:
manager.runtime_dir.mkdir(parents=True, exist_ok=True)
+ if install_dir is None:
+ install_dir = _write_install_metadata(
+ manager,
+ version="v1",
+ sha256=sha256,
+ mtime=0,
+ )
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,
+ "install_dir": str(install_dir),
+ "manifest_sha256": "a" * 64,
"archive_sha256": sha256,
}
(manager.runtime_dir / "current.json").write_text(json.dumps(pointer), encoding="utf-8")
@@ -54,7 +61,7 @@ def _write_install_metadata(manager: ShowRuntimeManager, *, version: str, sha256
install_dir.mkdir(parents=True, exist_ok=True)
metadata = {
"provider": "manifest-cache",
- "manifest_sha256": "m" * 64,
+ "manifest_sha256": "a" * 64,
"runtime_version": version,
"platform": "test",
"archive_name": "vibe-show-runtime-node-test.tgz",
@@ -485,6 +492,7 @@ def test_install_guard_unavailable_falls_back_to_verified_install(tmp_path: Path
from core import show_runtime as module
monkeypatch.setattr(module, "_runtime_platform_tag", lambda: "test")
+ monkeypatch.setattr("core.managed_runtime.runtime_platform_tag", lambda: "test")
monkeypatch.setattr(module, "_resolve_node_command", lambda: ["node"])
manifest_payload = {
"schema_version": 1,
@@ -623,7 +631,7 @@ def test_archive_cache_status_reports_stale_plan_failure(tmp_path: Path, monkeyp
def _boom(*args, **kwargs):
raise OSError("directory disappeared")
- monkeypatch.setattr(manager, "_clean_manifest_install_dirs", _boom)
+ monkeypatch.setattr(_ShowManifestRuntimeManager, "_read_managed_install_records", _boom)
report = manager.archive_cache_status()
assert report.get("skipped_reason") == "archive_inspection_failed"
@@ -634,12 +642,10 @@ def test_candidate_stat_failure_is_an_inspection_failure(tmp_path: Path, monkeyp
_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")
+ def _stat_boom(self, **_kwargs):
+ raise OSError("archive stat failed")
- monkeypatch.setattr(Path, "lstat", _stat_boom)
+ monkeypatch.setattr(_ShowManifestRuntimeManager, "_clean_downloaded_archives", _stat_boom)
result = manager.clean()
assert result["archives"].get("skipped_reason") == "archive_inspection_failed"
@@ -767,7 +773,7 @@ def test_dry_run_planning_failure_returns_structured_report(tmp_path: Path, monk
def _boom(*args, **kwargs):
raise OSError("install dir vanished during scan")
- monkeypatch.setattr(manager, "_clean_manifest_install_dirs", _boom)
+ monkeypatch.setattr(_ShowManifestRuntimeManager, "_read_managed_install_records", _boom)
result = manager.clean(dry_run=True)
assert result["archives"].get("skipped_reason") == "archive_inspection_failed"
@@ -971,7 +977,7 @@ def test_retained_metadata_without_valid_digest_fails_closed(tmp_path: Path, dig
assert rollback_archive.exists()
-def test_preview_guard_covers_archive_planning(tmp_path: Path) -> None:
+def test_preview_guard_covers_archive_planning(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")
@@ -979,13 +985,14 @@ def test_preview_guard_covers_archive_planning(tmp_path: Path) -> None:
_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
+ real_clean = _ShowManifestRuntimeManager._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)
+ def _observe(shared_manager, **kwargs):
+ seen["manager"] = shared_manager
+ seen["fd"] = getattr(shared_manager, "_preview_guard_fd", None)
+ return real_clean(shared_manager, **kwargs)
- manager._clean_downloaded_archives = _observe
+ monkeypatch.setattr(_ShowManifestRuntimeManager, "_clean_downloaded_archives", _observe)
result = manager.clean(dry_run=True)
assert result["dry_run"] is True
@@ -993,7 +1000,7 @@ def test_preview_guard_covers_archive_planning(tmp_path: Path) -> None:
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
+ assert getattr(seen["manager"], "_preview_guard_fd", None) is None
def _stat_with_ino(info: os.stat_result, ino: int) -> os.stat_result:
@@ -1007,6 +1014,8 @@ def test_windows_downloads_identity_mismatch_fails_closed(tmp_path: Path, monkey
_write_current_pointer(manager, _sha(1))
_write_archive(manager, _sha(2), b"stale")
monkeypatch.setattr("os.name", "nt")
+ monkeypatch.setattr(_ShowManifestRuntimeManager, "_acquire_mutation_lock", lambda _self: object())
+ monkeypatch.setattr(_ShowManifestRuntimeManager, "_release_mutation_lock", lambda _self, _lock: None)
real_lstat = Path.lstat
calls = {"n": 0}
@@ -1071,18 +1080,18 @@ def test_install_guard_refuses_swap_after_lock_acquisition(tmp_path: Path, monke
assert reason == "runtime_install_guard_unavailable"
-def test_preview_discards_plan_when_lock_appears_mid_scan(tmp_path: Path) -> None:
+def test_preview_discards_plan_when_lock_appears_mid_scan(tmp_path: Path, monkeypatch) -> 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
+ real_clean = _ShowManifestRuntimeManager._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)
+ def _observe(shared_manager, **kwargs):
+ (shared_manager.runtime_dir / "manifest-live").mkdir(parents=True, exist_ok=True)
+ (shared_manager.runtime_dir / ".install.lock").write_text("busy", encoding="utf-8")
+ return real_clean(shared_manager, **kwargs)
- manager._clean_downloaded_archives = _observe
+ monkeypatch.setattr(_ShowManifestRuntimeManager, "_clean_downloaded_archives", _observe)
result = manager.clean(dry_run=True)
assert result["ok"] is False
assert result["archives"]["skipped_reason"] == "runtime_install_already_running"
@@ -1135,25 +1144,26 @@ def test_dry_run_includes_abandoned_claims(tmp_path: Path) -> None:
assert claim.exists()
-def test_archive_cache_status_uses_preview_guard(tmp_path: Path) -> None:
+def test_archive_cache_status_uses_preview_guard(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))
_write_archive(manager, _sha(2), b"stale")
seen: dict[str, object] = {}
- real_clean = manager._clean_downloaded_archives
+ real_clean = _ShowManifestRuntimeManager._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)
+ def _observe(shared_manager, **kwargs):
+ seen["manager"] = shared_manager
+ seen["fd"] = getattr(shared_manager, "_preview_guard_fd", None)
+ return real_clean(shared_manager, **kwargs)
- manager._clean_downloaded_archives = _observe
+ monkeypatch.setattr(_ShowManifestRuntimeManager, "_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
+ assert getattr(seen["manager"], "_preview_guard_fd", None) is None
def test_windows_preview_ignores_persistent_lock_file(tmp_path: Path, monkeypatch) -> None:
@@ -1162,8 +1172,8 @@ def test_windows_preview_ignores_persistent_lock_file(tmp_path: Path, monkeypatc
(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)
+ monkeypatch.setattr("core.managed_runtime.fcntl_available", lambda: False)
+ monkeypatch.setattr("core.managed_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
@@ -1176,8 +1186,8 @@ def test_windows_preview_detects_held_lock_before_staging(tmp_path: Path, monkey
(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)
+ 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["archives"]["skipped_reason"] == "runtime_install_already_running"
@@ -1204,7 +1214,7 @@ def test_clean_keeps_completed_staging_removals_on_later_failure(tmp_path: Path,
def _boom(*, keep_previous, dry_run=False, removed=None, **kwargs):
raise OSError("versions unreadable")
- monkeypatch.setattr(manager, "_clean_manifest_install_dirs", _boom)
+ monkeypatch.setattr(_ShowManifestRuntimeManager, "_read_managed_install_records", _boom)
result = manager.clean()
assert result["ok"] is False
assert str(staging) in result["removed"]
@@ -1222,7 +1232,7 @@ def test_clean_keeps_completed_install_removals_when_prune_fails(tmp_path: Path,
def _boom(self, versions_dir):
raise OSError("parent became nonempty")
- monkeypatch.setattr(ShowRuntimeManager, "_prune_empty_manifest_version_dirs", _boom)
+ monkeypatch.setattr(_ShowManifestRuntimeManager, "_prune_empty_version_dirs", _boom)
result = manager.clean()
assert result["ok"] is False
assert str(stale_install) in result["removed"]
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 330c199c7..5cc6a763b 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -439,6 +439,21 @@ def _write_runtime_archive(tmp_path: Path, *, text: str = "#!/usr/bin/env node\n
return archive_path
+def _write_runtime_archive_with_entrypoints(
+ tmp_path: Path,
+ entrypoints: tuple[str, ...],
+) -> Path:
+ archive_path = tmp_path / "vibe-show-runtime-entrypoints.tgz"
+ payload = b"#!/usr/bin/env node\n"
+ with tarfile.open(archive_path, "w:gz") as archive:
+ for entrypoint in entrypoints:
+ member = tarfile.TarInfo(entrypoint)
+ member.mode = 0o755
+ member.size = len(payload)
+ archive.addfile(member, io.BytesIO(payload))
+ return archive_path
+
+
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as file:
@@ -490,7 +505,7 @@ def _install_remote_manifest_runtime(monkeypatch, tmp_path: Path):
)
monkeypatch.setattr("core.show_runtime._node_version", lambda _node: (22, 12, 0))
monkeypatch.setattr(
- "core.show_runtime.fetch_bytes",
+ "core.managed_runtime.fetch_bytes",
lambda url, **_kwargs: manifest_path.read_bytes()
if url == manifest_url
else pytest.fail(f"unexpected fetch: {url}"),
@@ -524,6 +539,8 @@ def _write_cached_runtime_install_at(
manifest_source: str = "package:show_runtime_manifest.json",
mtime: float,
) -> tuple[Path, Path]:
+ manifest_sha256 = hashlib.sha256(f"manifest:{name}".encode()).hexdigest()
+ archive_sha256 = hashlib.sha256(f"archive:{name}".encode()).hexdigest()
cli_path = install_dir / "node_modules" / "@avibe" / "show-runtime" / "dist" / "cli.js"
cli_path.parent.mkdir(parents=True)
cli_path.write_text(f"{name}\n", encoding="utf-8")
@@ -532,8 +549,11 @@ def _write_cached_runtime_install_at(
{
"provider": "manifest-cache",
"manifest_source": manifest_source,
+ "manifest_sha256": manifest_sha256,
"runtime_version": name,
"platform": _runtime_platform_tag(),
+ "archive_name": f"{archive_sha256}.tgz",
+ "archive_sha256": archive_sha256,
}
),
encoding="utf-8",
@@ -542,6 +562,25 @@ def _write_cached_runtime_install_at(
return install_dir, cli_path
+def _write_cached_runtime_pointer(runtime_dir: Path, install_dir: Path) -> None:
+ metadata = json.loads(
+ (install_dir / ".vibe-show-runtime.json").read_text(encoding="utf-8")
+ )
+ (runtime_dir / "current.json").write_text(
+ json.dumps(
+ {
+ "provider": "manifest-cache",
+ "runtime_version": metadata["runtime_version"],
+ "platform": metadata["platform"],
+ "install_dir": str(install_dir),
+ "manifest_sha256": metadata["manifest_sha256"],
+ "archive_sha256": metadata["archive_sha256"],
+ }
+ ),
+ encoding="utf-8",
+ )
+
+
def test_private_show_page_requires_remote_login(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -7727,7 +7766,7 @@ def test_show_runtime_reason_literals_have_declared_evidence():
reason_literals = {
value
for value in re.findall(r'(["\'])(runtime_[a-z0-9_]+)\1', source)
- if value[1] not in {"runtime_source", "runtime_version"}
+ if value[1] not in {"runtime_id", "runtime_source", "runtime_version"}
}
declared = {reason for reason, _provenance, _retryable in SHOW_RUNTIME_FAILURE_DECLARATIONS}
assert {value for _quote, value in reason_literals} <= declared
@@ -9528,11 +9567,14 @@ def test_show_runtime_manager_forced_manifest_fallback_reports_failed_operation_
installed = manager.prepare()
assert installed["ok"] is True
- def fail_archive_resolution(*_args, **_kwargs):
- manager._install_reason = "runtime_archive_download_failed"
+ def fail_archive_resolution(shared_manager, _archive):
+ shared_manager._install_reason = "runtime_archive_download_failed"
return None
- monkeypatch.setattr(manager, "_resolve_manifest_archive", fail_archive_resolution)
+ monkeypatch.setattr(
+ "core.show_runtime._ShowManifestRuntimeManager._resolve_manifest_archive",
+ fail_archive_resolution,
+ )
result = manager.prepare(force=True)
@@ -9568,6 +9610,54 @@ def test_show_runtime_manager_force_refreshes_matching_manifest_install(monkeypa
assert installed_cli.read_text(encoding="utf-8") == "healthy runtime\n"
+def test_show_runtime_manager_force_publication_failure_invalidates_cached_command_and_repairs(
+ monkeypatch,
+ tmp_path,
+):
+ archive_path = _write_runtime_archive(tmp_path, text="healthy runtime\n")
+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=tmp_path / "runtime",
+ manifest_path=manifest_path,
+ )
+ monkeypatch.setattr(
+ "core.show_runtime._resolve_command",
+ lambda command: ["/bin/node"] if command == "node" else None,
+ )
+ installed = manager.prepare()
+ installed_cli = Path(installed["command"][1])
+ original_write_pointer = show_runtime._ShowManifestRuntimeManager._write_current_pointer
+ writes = 0
+
+ def fail_first_pointer_write(shared_manager, install_dir, manifest, archive):
+ nonlocal writes
+ writes += 1
+ if writes == 1:
+ raise OSError("pointer publication failed")
+ return original_write_pointer(shared_manager, install_dir, manifest, archive)
+
+ monkeypatch.setattr(
+ show_runtime._ShowManifestRuntimeManager,
+ "_write_current_pointer",
+ fail_first_pointer_write,
+ )
+
+ failed = manager.prepare(force=True)
+
+ assert failed["ok"] is False
+ assert failed["reason"] == "runtime_install_failed"
+ assert failed["command"] is None
+ assert manager._managed_command is None
+ assert not installed_cli.exists()
+
+ repaired = manager.prepare()
+
+ assert repaired["ok"] is True
+ assert repaired["command"] == installed["command"]
+ assert installed_cli.read_text(encoding="utf-8") == "healthy runtime\n"
+
+
def test_show_runtime_manager_preserves_structured_http_download_error(monkeypatch, tmp_path):
archive_path = _write_runtime_archive(tmp_path)
archive_url = "https://github.com/avibe-bot/avibe/releases/download/v-test/runtime.tgz?token=secret"
@@ -9641,7 +9731,7 @@ def test_manifest_download_failure_publishes_measured_retryability(
}
)
- monkeypatch.setattr("core.show_runtime.fetch_bytes", fail_manifest)
+ monkeypatch.setattr("core.managed_runtime.fetch_bytes", fail_manifest)
result = manager.prepare()
@@ -9820,6 +9910,49 @@ def test_show_runtime_archive_probe_uses_body_free_head_request(monkeypatch, tmp
assert requests[0].get_method() == "HEAD"
+def test_show_runtime_manifest_probe_fetches_without_mutating_remote_cache(
+ monkeypatch,
+ tmp_path,
+):
+ archive_path = _write_runtime_archive(tmp_path)
+ manifest_path = _write_runtime_manifest(
+ tmp_path,
+ archive_path,
+ url="https://example.test/runtime.tgz",
+ )
+ manifest_url = "https://example.test/show-runtime-manifest.json"
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=tmp_path / "runtime",
+ manifest_url=manifest_url,
+ )
+ shared_manager = manager._shared_manifest_manager(offline=False)
+ cached_manifest = shared_manager._remote_manifest_cache_path()
+ cached_manifest.parent.mkdir(parents=True)
+ cached_manifest.write_bytes(b"existing Show manifest cache")
+ monkeypatch.setattr(
+ "core.managed_runtime.fetch_bytes",
+ lambda url, **_kwargs: (
+ manifest_path.read_bytes()
+ if url == manifest_url
+ else pytest.fail(f"unexpected fetch: {url}")
+ ),
+ )
+ monkeypatch.setattr(
+ "core.managed_runtime.write_atomic",
+ lambda *_args, **_kwargs: pytest.fail("Show diagnostic probe wrote the manifest cache"),
+ )
+ monkeypatch.setattr(
+ "core.show_runtime.probe_url",
+ lambda *_args, **_kwargs: {"ok": True, "checked": True},
+ )
+
+ result = manager.probe_archive_reachability()
+
+ assert result == {"ok": True, "checked": True}
+ assert cached_manifest.read_bytes() == b"existing Show manifest cache"
+
+
def test_show_runtime_manager_manifest_install_dir_includes_runtime_and_archive_identity(monkeypatch, tmp_path):
old_archive_path = _write_runtime_archive(tmp_path / "old", text="old runtime\n")
old_manifest_path = _write_runtime_manifest(tmp_path / "old", old_archive_path)
@@ -9852,6 +9985,63 @@ def test_show_runtime_manager_manifest_install_dir_includes_runtime_and_archive_
assert new_manager.status()["install"]["matches_manifest"] is True
[email protected]("manifest_source", ("path", "packaged"))
+def test_show_runtime_manager_revalidates_selected_manifest_identity_before_reuse(
+ monkeypatch,
+ tmp_path,
+ manifest_source,
+):
+ old_archive = _write_runtime_archive(tmp_path / "old", text="old runtime\n")
+ old_manifest = _write_runtime_manifest(tmp_path / "old", old_archive)
+ if manifest_source == "path":
+ selected_manifest = old_manifest
+ manager_kwargs = {"manifest_path": selected_manifest}
+ else:
+ package_root = tmp_path / "package"
+ selected_manifest = package_root / show_runtime._RUNTIME_MANIFEST_RESOURCE
+ selected_manifest.parent.mkdir(parents=True)
+ selected_manifest.write_bytes(old_manifest.read_bytes())
+ monkeypatch.setattr(
+ "core.managed_runtime.package_resources.files",
+ lambda _package: package_root,
+ )
+ manager_kwargs = {}
+
+ runtime_dir = tmp_path / "runtime"
+ monkeypatch.setattr(
+ "core.show_runtime._resolve_command",
+ lambda command: ["/bin/node"] if command == "node" else None,
+ )
+ old_manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ **manager_kwargs,
+ )
+ old_result = old_manager.prepare()
+ old_cli = Path(old_result["command"][1])
+
+ new_archive = _write_runtime_archive(tmp_path / "new", text="new runtime\n")
+ new_manifest = _write_runtime_manifest(
+ tmp_path / "new",
+ new_archive,
+ runtime_version="runtime-new-ref",
+ )
+ selected_manifest.write_bytes(new_manifest.read_bytes())
+ new_manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ **manager_kwargs,
+ )
+
+ result = new_manager.prepare()
+
+ new_cli = Path(result["command"][1])
+ assert result["ok"] is True
+ assert new_cli != old_cli
+ assert new_cli.read_text(encoding="utf-8") == "new runtime\n"
+ assert old_cli.read_text(encoding="utf-8") == "old runtime\n"
+
+
def test_show_runtime_manager_manifest_install_identity_ignores_other_platform_edits(monkeypatch, tmp_path):
archive_path = _write_runtime_archive(tmp_path, text="current platform runtime\n")
manifest_path = _write_runtime_manifest(tmp_path, archive_path)
@@ -10051,6 +10241,7 @@ def test_show_runtime_prepare_prunes_old_packaged_installs_and_keeps_rollback(mo
old_install, _old_cli = _write_cached_runtime_install(runtime_dir, "old", mtime=100)
previous_install, _previous_cli = _write_cached_runtime_install(runtime_dir, "previous", mtime=200)
current_install, current_cli = _write_cached_runtime_install(runtime_dir, "current", mtime=300)
+ _write_cached_runtime_pointer(runtime_dir, current_install)
custom_install, _custom_cli = _write_cached_runtime_install(
runtime_dir,
"custom",
@@ -10092,6 +10283,7 @@ def test_show_runtime_prepare_preserves_nested_retained_rollback(monkeypatch, tm
runtime_dir = tmp_path / "runtime"
old_install, _old_cli = _write_cached_runtime_install(runtime_dir, "old", mtime=10)
current_install, current_cli = _write_cached_runtime_install(runtime_dir, "current", mtime=300)
+ _write_cached_runtime_pointer(runtime_dir, current_install)
rollback_parent = runtime_dir / "versions" / "rollback" / _runtime_platform_tag()
_rollback_parent, rollback_parent_cli = _write_cached_runtime_install_at(
rollback_parent,
@@ -10144,6 +10336,7 @@ def test_show_runtime_prepare_prunes_siblings_under_current_legacy_parent(monkey
"current",
mtime=300,
)
+ _write_cached_runtime_pointer(runtime_dir, current_install)
stale_sibling, _stale_cli = _write_cached_runtime_install_at(
current_parent / "stale-fingerprint",
"stale-current",
@@ -10180,6 +10373,7 @@ def test_show_runtime_prepare_preserves_descendants_of_current_legacy_parent(mon
previous_install, _previous_cli = _write_cached_runtime_install(runtime_dir, "previous", mtime=250)
current_parent = runtime_dir / "versions" / "current" / _runtime_platform_tag()
_parent_install, parent_cli = _write_cached_runtime_install_at(current_parent, "current-legacy", mtime=400)
+ _write_cached_runtime_pointer(runtime_dir, current_parent)
current_child, current_child_cli = _write_cached_runtime_install_at(
current_parent / "current-fingerprint",
"current-child",
@@ -10214,6 +10408,7 @@ def test_show_runtime_prepare_preserves_custom_child_under_stale_packaged_parent
old_install, _old_cli = _write_cached_runtime_install(runtime_dir, "old", mtime=20)
previous_install, _previous_cli = _write_cached_runtime_install(runtime_dir, "previous", mtime=250)
current_install, current_cli = _write_cached_runtime_install(runtime_dir, "current", mtime=300)
+ _write_cached_runtime_pointer(runtime_dir, current_install)
stale_parent = runtime_dir / "versions" / "stale-parent" / _runtime_platform_tag()
_parent_install, parent_cli = _write_cached_runtime_install_at(stale_parent, "stale-parent", mtime=80)
custom_child, custom_cli = _write_cached_runtime_install_at(
@@ -10380,6 +10575,119 @@ def test_show_runtime_clean_skips_legacy_parent_of_current_fingerprint(monkeypat
assert Path(result["command"][1]).exists() is True
[email protected]("include_canonical", (False, True))
+def test_show_runtime_manager_rejects_noncanonical_manifest_entrypoint(
+ monkeypatch,
+ tmp_path,
+ include_canonical,
+):
+ canonical = "node_modules/@avibe/show-runtime/dist/cli.js"
+ alternate = "node_modules/@avibe/show-runtime/dist/alternate.js"
+ entrypoints = (alternate, canonical) if include_canonical else (alternate,)
+ archive_path = _write_runtime_archive_with_entrypoints(tmp_path, entrypoints)
+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
+ payload["archives"][_runtime_platform_tag()]["bin_path"] = alternate
+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=tmp_path / "runtime",
+ manifest_path=manifest_path,
+ )
+ monkeypatch.setattr(
+ "core.show_runtime._resolve_command",
+ lambda command: ["/bin/node"] if command == "node" else None,
+ )
+
+ result = manager.prepare()
+
+ assert result["ok"] is False
+ assert result["reason"] == "runtime_manifest_invalid"
+ assert result["command"] is None
+ assert not (manager.runtime_dir / "current.json").exists()
+
+
+ ("selection_error", "expected_reason"),
+ (
+ ("missing_platform", "runtime_platform_unsupported"),
+ ("noncanonical_entrypoint", "runtime_manifest_invalid"),
+ ),
+)
+def test_show_runtime_status_reports_selected_manifest_archive_error_with_installed_runtime(
+ monkeypatch,
+ tmp_path,
+ selection_error,
+ expected_reason,
+):
+ archive_path = _write_runtime_archive(tmp_path)
+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)
+ runtime_dir = tmp_path / "runtime"
+ monkeypatch.setattr(
+ "core.show_runtime._resolve_command",
+ lambda command: ["/bin/node"] if command == "node" else None,
+ )
+ installed = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_path=manifest_path,
+ ).prepare()
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
+ platform_tag = _runtime_platform_tag()
+ if selection_error == "missing_platform":
+ payload["archives"]["fixture-unsupported"] = payload["archives"].pop(platform_tag)
+ else:
+ payload["archives"][platform_tag]["bin_path"] = (
+ "node_modules/@avibe/show-runtime/dist/alternate.js"
+ )
+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_path=manifest_path,
+ )
+
+ status = manager.status()
+
+ assert status["install"]["state"] == "installed"
+ assert status["install"]["runtime_version"] == "runtime-test-ref"
+ assert status["command"] == installed["command"]
+ assert status["reason"] == expected_reason
+
+
+ "minimum_node",
+ (20, [">=22.12.0"], {"range": ">=22.12.0"}),
+ ids=("number", "list", "object"),
+)
+def test_show_runtime_manager_rejects_non_string_manifest_node_requirement(
+ monkeypatch,
+ tmp_path,
+ minimum_node,
+):
+ archive_path = _write_runtime_archive(tmp_path)
+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
+ payload["minimum_node"] = minimum_node
+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=tmp_path / "runtime",
+ manifest_path=manifest_path,
+ )
+ monkeypatch.setattr(
+ "core.show_runtime._resolve_command",
+ lambda command: ["/bin/node"] if command == "node" else None,
+ )
+
+ result = manager.prepare()
+
+ assert result["ok"] is False
+ assert result["reason"] == "runtime_manifest_invalid"
+ assert result["command"] is None
+ assert not (manager.runtime_dir / "current.json").exists()
+
+
def test_show_runtime_manager_rejects_node_below_manifest_minimum(monkeypatch, tmp_path):
archive_path = _write_runtime_archive(tmp_path)
manifest_path = _write_runtime_manifest(tmp_path, archive_path)
@@ -10398,6 +10706,42 @@ def test_show_runtime_manager_rejects_node_below_manifest_minimum(monkeypatch, t
assert result["status"]["node_supported"] is False
+def test_show_runtime_manager_revalidates_changed_node_prerequisite_before_reuse(
+ monkeypatch,
+ tmp_path,
+):
+ archive_path = _write_runtime_archive(tmp_path, text="installed runtime\n")
+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)
+ runtime_dir = tmp_path / "runtime"
+ monkeypatch.setattr(
+ "core.show_runtime._resolve_command",
+ lambda command: ["/bin/node"] if command == "node" else None,
+ )
+ monkeypatch.setattr("core.show_runtime._node_version", lambda _node: (22, 12, 0))
+ initial = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_path=manifest_path,
+ ).prepare()
+ installed_cli = Path(initial["command"][1])
+
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
+ payload["minimum_node"] = ">=99.0.0"
+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_path=manifest_path,
+ )
+
+ result = manager.prepare()
+
+ assert result["ok"] is False
+ assert result["reason"] == "runtime_node_unsupported"
+ assert result["command"] is None
+ assert installed_cli.read_text(encoding="utf-8") == "installed runtime\n"
+
+
def test_show_runtime_manager_rejects_manifest_archive_checksum_mismatch(monkeypatch, tmp_path):
archive_path = _write_runtime_archive(tmp_path)
manifest_path = _write_runtime_manifest(tmp_path, archive_path, sha256="0" * 64)
@@ -10465,6 +10809,80 @@ def test_show_runtime_manager_installs_manifest_archive_from_verified_offline_ca
assert result["reason"] is None
+def test_show_runtime_manager_falls_back_to_installed_record_when_manifest_source_is_missing(
+ monkeypatch,
+ tmp_path,
+):
+ archive_path = _write_runtime_archive(tmp_path)
+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)
+ runtime_dir = tmp_path / "runtime"
+ monkeypatch.setattr(
+ "core.show_runtime._resolve_command",
+ lambda command: ["/bin/node"] if command == "node" else None,
+ )
+ installed = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_path=manifest_path,
+ ).prepare()
+ manifest_path.unlink()
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_path=manifest_path,
+ )
+
+ availability = asyncio.run(manager._resolve_managed_availability())
+
+ assert availability.command == installed["command"]
+ assert manager.status()["reason"] == "runtime_manifest_missing"
+
+
[email protected]("manifest_source", ("path", "packaged"))
+def test_show_runtime_manager_falls_back_when_selected_manifest_is_invalid(
+ monkeypatch,
+ tmp_path,
+ manifest_source,
+):
+ archive_path = _write_runtime_archive(tmp_path)
+ valid_manifest = _write_runtime_manifest(tmp_path, archive_path)
+ if manifest_source == "path":
+ selected_manifest = valid_manifest
+ manager_kwargs = {"manifest_path": selected_manifest}
+ else:
+ package_root = tmp_path / "package"
+ selected_manifest = package_root / show_runtime._RUNTIME_MANIFEST_RESOURCE
+ selected_manifest.parent.mkdir(parents=True)
+ selected_manifest.write_bytes(valid_manifest.read_bytes())
+ monkeypatch.setattr(
+ "core.managed_runtime.package_resources.files",
+ lambda _package: package_root,
+ )
+ manager_kwargs = {}
+
+ runtime_dir = tmp_path / "runtime"
+ monkeypatch.setattr(
+ "core.show_runtime._resolve_command",
+ lambda command: ["/bin/node"] if command == "node" else None,
+ )
+ installed = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ **manager_kwargs,
+ ).prepare()
+ selected_manifest.write_text("not-json", encoding="utf-8")
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ **manager_kwargs,
+ )
+
+ availability = asyncio.run(manager._resolve_managed_availability())
+
+ assert availability.command == installed["command"]
+ assert manager.status()["reason"] == "runtime_manifest_invalid"
+
+
def test_show_runtime_manager_status_does_not_read_manifest_for_legacy_sources(tmp_path):
manager = ShowRuntimeManager(
workspace_root=tmp_path / "show",
@@ -10596,7 +11014,7 @@ def test_show_runtime_remote_manifest_install_remains_installed_when_source_is_u
def fail_manifest_fetch(*_args, **_kwargs):
raise OSError("manifest host unavailable")
- monkeypatch.setattr("core.show_runtime.fetch_bytes", fail_manifest_fetch)
+ monkeypatch.setattr("core.managed_runtime.fetch_bytes", fail_manifest_fetch)
status = manager.status()
assert status["install"]["state"] == "installed"
@@ -10609,6 +11027,59 @@ def test_show_runtime_remote_manifest_install_remains_installed_when_source_is_u
assert status["reason"] == "runtime_manifest_download_failed"
+def test_show_runtime_offline_remote_cache_record_resolves_for_fresh_manager(monkeypatch, tmp_path):
+ archive_path = _write_runtime_archive(tmp_path)
+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)
+ manifest_url = "https://example.test/show-runtime-manifest.json"
+ runtime_dir = tmp_path / "runtime"
+ monkeypatch.setattr(
+ "core.show_runtime._resolve_command",
+ lambda command: ["test-node"] if command == "node" else None,
+ )
+ monkeypatch.setattr("core.show_runtime._node_version", lambda _node: (22, 12, 0))
+ monkeypatch.setattr(
+ "core.managed_runtime.fetch_bytes",
+ lambda url, **_kwargs: manifest_path.read_bytes()
+ if url == manifest_url
+ else pytest.fail(f"unexpected fetch: {url}"),
+ )
+ warming_manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_url=manifest_url,
+ )._shared_manifest_manager(offline=False)
+ assert warming_manager.load_manifest(allow_network=True) is not None
+ digest = _sha256(archive_path)
+ cached_archive = runtime_dir / "downloads" / f"{digest}.tgz"
+ cached_archive.parent.mkdir(parents=True, exist_ok=True)
+ cached_archive.write_bytes(archive_path.read_bytes())
+
+ offline_manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_url=manifest_url,
+ offline=True,
+ )
+ installed = offline_manager.prepare()
+ install_dir = Path(installed["command"][1]).parents[4]
+ metadata = json.loads(
+ (install_dir / ".vibe-show-runtime.json").read_text(encoding="utf-8")
+ )
+ assert metadata["manifest_source"] == f"cache:{manifest_url}"
+
+ fresh_manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ manifest_url=manifest_url,
+ offline=True,
+ auto_install=False,
+ )
+ resolved = fresh_manager.prepare(automatic=True)
+
+ assert resolved["install"]["state"] == "installed"
+ assert resolved["command"] == installed["command"]
+
+
def test_show_runtime_status_keeps_installed_identity_separate_from_selected_manifest(monkeypatch, tmp_path):
runtime_dir, manifest_url, install_dir, command = _install_remote_manifest_runtime(monkeypatch, tmp_path)
selected_archive = _write_runtime_archive(tmp_path, text="#!/usr/bin/env node\n// selected runtime\n")
@@ -10675,7 +11146,15 @@ def test_show_runtime_disk_install_fact_does_not_require_node(monkeypatch, tmp_p
@pytest.mark.parametrize(
"corruption",
- ("outside-versions", "source-lineage", "pointer-metadata", "invalid-json"),
+ (
+ "outside-versions",
+ "source-lineage",
+ "unrelated-cache-source",
+ "malformed-cache-source",
+ "non-string-source",
+ "pointer-metadata",
+ "invalid-json",
+ ),
)
def test_show_runtime_disk_install_pointer_fails_closed(monkeypatch, tmp_path, corruption):
runtime_dir, manifest_url, install_dir, _command = _install_remote_manifest_runtime(monkeypatch, tmp_path)
@@ -10689,6 +11168,18 @@ def test_show_runtime_disk_install_pointer_fails_closed(monkeypatch, tmp_path, c
metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
metadata["manifest_source"] = "https://other.example/show-runtime-manifest.json"
metadata_path.write_text(json.dumps(metadata), encoding="utf-8")
+ elif corruption == "unrelated-cache-source":
+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
+ metadata["manifest_source"] = "cache:https://other.example/show-runtime-manifest.json"
+ metadata_path.write_text(json.dumps(metadata), encoding="utf-8")
+ elif corruption == "malformed-cache-source":
+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
+ metadata["manifest_source"] = "cache:"
+ metadata_path.write_text(json.dumps(metadata), encoding="utf-8")
+ elif corruption == "non-string-source":
+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
+ metadata["manifest_source"] = {"cache": manifest_url}
+ metadata_path.write_text(json.dumps(metadata), encoding="utf-8")
elif corruption == "pointer-metadata":
pointer = json.loads(pointer_path.read_text(encoding="utf-8"))
pointer["archive_sha256"] = "f" * 64