Skip to content

The agent that grows with you

fix(pm): a corrupt cached package no longer blocks every install

Ben Barclay67d3d5076ca0
diff --git a/pm/cli.py b/pm/cli.py
index 94fb0907bc9..874758f714a 100644
--- a/pm/cli.py
+++ b/pm/cli.py
@@ -471,9 +471,42 @@ def cmd_doctor(args) -> int:
bad += 1
continue
print(f"✓ {name} {fact['version']}")
+ bad += _doctor_uv_cache(repair=getattr(args, "repair", False))
return 1 if bad else 0
+def _doctor_uv_cache(*, repair: bool) -> int:
+ """Report (and with --repair, remove) uv cache entries an interrupted install corrupted.
+
+ Read-only by default like the rest of doctor. Installs already purge a
+ corrupt entry they trip over; this finds them before an install does.
+ """
+ from pm.environment import managed_environment
+ from pm.packages import uv_cache_path
+ from pm.uv_cache_health import corrupt_cached_packages
+
+ cache = uv_cache_path()
+ corrupt = sorted(corrupt_cached_packages(cache))
+ if not corrupt:
+ print(f"✓ uv cache: no corrupt entries in {cache}")
+ return 0
+ if not repair:
+ print(f"✗ uv cache: corrupt entries for {', '.join(corrupt)} in {cache}; "
+ "run `hermes pm doctor --repair` (installs also remove them when they hit one)")
+ return 1
+ try:
+ managed_environment(cache, cache=cache).purge_cached_packages(corrupt)
+ except InstallError as exc:
+ print(f"✗ uv cache: {exc}")
+ return 1
+ left = sorted(corrupt_cached_packages(cache))
+ if left:
+ print(f"✗ uv cache: still corrupt after cleaning: {', '.join(left)} in {cache}")
+ return 1
+ print(f"✓ uv cache: removed corrupt entries for {', '.join(corrupt)}; they are fetched again on next use")
+ return 0
+
+
def _gc_store(store, facts) -> tuple[int, int]:
"""The sweep core shared by `pm gc` and `pm bundle`.
@@ -942,6 +975,8 @@ def main(argv=None) -> int:
p.set_defaults(func=cmd_env)
p = sub.add_parser("doctor", help="check installed state against the lockfile")
+ p.add_argument("--repair", action="store_true",
+ help="remove corrupt entries from PM's uv cache so they are fetched again")
p.set_defaults(func=cmd_doctor)
p = sub.add_parser("repair", help="rebuild the recorded dependency environment without changing its graph")
diff --git a/pm/environment.py b/pm/environment.py
index 35e2b65547b..d6d1edb4f16 100644
--- a/pm/environment.py
+++ b/pm/environment.py
@@ -6,7 +6,7 @@ staged toolchain directly without recursing through the worker it is building.
from __future__ import annotations
import codecs
-from collections.abc import Iterator, Mapping, Sequence
+from collections.abc import Callable, Iterator, Mapping, Sequence
from contextlib import contextmanager
from dataclasses import dataclass, replace
import io
@@ -69,6 +69,11 @@ _BYTECODE_COMPILE_MARKER = "failed to bytecode-compile"
# to ride the same path or repair/bootstrap never sees the retry signal.
_STREAM_TAIL_MARKERS = _RESOLVER_MARKERS + (_BYTECODE_COMPILE_MARKER,)
+# Retries after purging corrupt cached packages. Each round must name a package
+# not purged before, so this bounds a cache with several damaged entries, never
+# a loop on one broken wheel.
+_CACHE_RECOVERY_ROUNDS = 3
+
class ResolutionConflict(InstallError):
"""uv's resolver proved the union has no valid solution."""
@@ -425,7 +430,13 @@ class PythonEnvironment:
command += ["--extra", extra]
for group in sorted(set(groups)):
command += ["--group", group]
- result = self._run(command, cwd=source, timeout=timeout)
+ result = self._with_cache_recovery(
+ "sync", lambda: self._sync_attempt(command, cwd=source, timeout=timeout))
+ if result.returncode:
+ raise classify_uv_failure("sync", result.returncode, result.stderr or result.stdout)
+
+ def _sync_attempt(self, command: list[str], *, cwd: Path, timeout: int) -> subprocess.CompletedProcess:
+ result = self._run(command, cwd=cwd, timeout=timeout)
if _is_bytecode_compile_failure(result):
# Compile is an optimization. Retry once without the flag so a
# locked temp script cannot fail pm repair/bootstrap. Imports
@@ -436,9 +447,87 @@ class PythonEnvironment:
"Modules will compile on first import.\n"
)
fallback = [arg for arg in command if arg != "--compile-bytecode"]
- result = self._run(fallback, cwd=source, timeout=timeout)
+ result = self._run(fallback, cwd=cwd, timeout=timeout)
+ return result
+
+ def _with_cache_recovery(self, stage: str, attempt: Callable[[], subprocess.CompletedProcess],
+ ) -> subprocess.CompletedProcess:
+ """Run *attempt*; if a corrupt cached package failed it, purge it and retry.
+
+ An install interrupted by a machine stop can leave a cache entry whose
+ files are NUL bytes, and uv reuses it on every sync, so a plain retry
+ never helps. Only uv's install-step corruption shapes trigger this
+ (pm.uv_cache_health); every other failure returns untouched for the
+ caller to classify. Each purge also takes every entry that fails the
+ same validation, so one retry normally covers several damaged packages.
+ uv stops at the first broken entry, though, and a dangling pointer is
+ invisible to the scan, so a retry that trips over a DIFFERENT package
+ purges that one too. A package that fails again after its purge ends
+ the loop: the source itself is serving a broken wheel.
+ """
+ from pm.uv_cache_health import corrupt_cached_packages, failed_cached_packages
+
+ purged: set[str] = set()
+ result = attempt()
+ for _ in range(_CACHE_RECOVERY_ROUNDS):
+ if not result.returncode:
+ return result
+ failed = failed_cached_packages(f"{result.stderr or ''}\n{result.stdout or ''}")
+ if not failed or failed <= purged:
+ break
+ names = sorted((failed | corrupt_cached_packages(self.cache)) - purged)
+ if self.output is not None:
+ self.output.write(f"The cached copy of {', '.join(names)} is corrupt; "
+ "removing it from the uv cache and retrying the install.\n")
+ self.purge_cached_packages(names)
+ purged.update(names)
+ result = attempt()
+ if not result.returncode or not purged:
+ return result
+ text = f"{result.stderr or ''}\n{result.stdout or ''}"
+ cache = native(self.cache)
+ still = failed_cached_packages(text)
+ if still:
+ remedy = ("the package source is serving a broken wheel; retry later or pin another version"
+ if still <= purged else "run `hermes pm doctor --repair`, then retry")
+ raise InstallError(
+ "venv",
+ f"uv {stage} exited {result.returncode}: the cached copy of {', '.join(sorted(still))} is "
+ f"still invalid after removing {', '.join(sorted(purged))} from the uv cache at {cache}: "
+ f"{text.strip()[-600:]}",
+ remedy,
+ )
+ if self.offline:
+ raise InstallError(
+ "venv",
+ f"uv {stage} exited {result.returncode}: removed the corrupt cached copy of "
+ f"{', '.join(sorted(purged))} from {cache}, and offline mode cannot fetch it again: "
+ f"{text.strip()[-600:]}",
+ "retry with network access",
+ )
+ return result
+
+ def purge_cached_packages(self, names: Sequence[str]) -> None:
+ """Remove *names* from the uv cache.
+
+ ``uv cache clean`` waits for other uv processes holding the cache, so
+ another profile's sync never loses files it is reading. Archives it
+ leaves behind that still fail validation are then deleted
+ (pm.uv_cache_health.remove_corrupt_entries).
+ """
+ from pm.uv_cache_health import remove_corrupt_entries
+
+ cache = native(self.cache)
+ try:
+ result = replace(self, output=None)._run(["cache", "clean", *names],
+ cwd=self.cache.parent, timeout=900)
+ except InstallError as exc:
+ raise InstallError("uv", f"could not clean the uv cache at {cache}: {exc.cause}",
+ "stop other Hermes installs and retry") from exc
if result.returncode:
- raise classify_uv_failure("sync", result.returncode, result.stderr or result.stdout)
+ raise InstallError("uv", f"could not remove {', '.join(names)} from the uv cache at "
+ f"{cache}: {(result.stderr or result.stdout)[-600:]}")
+ remove_corrupt_entries(self.cache, set(names))
def export_requirements(self, source: Path, out: Path, *, extras: Sequence[str] = (),
timeout: int = 1800) -> None:
@@ -481,7 +570,8 @@ class PythonEnvironment:
if wheelhouse is not None:
command += ["--no-index", "--only-binary", ":all:",
"--find-links", str(wheelhouse.absolute())]
- result = self._run(command, cwd=requirements.parent, timeout=timeout)
+ result = self._with_cache_recovery(
+ "pip", lambda: self._run(command, cwd=requirements.parent, timeout=timeout))
if result.returncode:
raise classify_uv_failure("pip", result.returncode, result.stderr or result.stdout)
diff --git a/pm/packages.py b/pm/packages.py
index c54fa87f2a6..797331701ef 100644
--- a/pm/packages.py
+++ b/pm/packages.py
@@ -352,6 +352,13 @@ def _copy_seed_file(src: str | os.PathLike, dst: str | os.PathLike) -> str | os.
return dst
+def uv_cache_path() -> Path:
+ """Where the hermes-owned uv cache lives; unlike uv_cache_dir(), never seeds or writes."""
+ from hermes_constants import get_default_hermes_root
+
+ return get_default_hermes_root() / "cache" / "uv"
+
+
def uv_cache_dir() -> Path:
"""The hermes-owned uv cache: machine-scoped and shared (keyed by
content — two profiles reuse one cache), anchored to the DEFAULT
@@ -362,11 +369,9 @@ def uv_cache_dir() -> Path:
from it is near-free (probed: 0.4s vs 1.2s cold) — the blow-away-
on-update contract depends on it. uv's default cache location is
per-user/platform-opinionated and never used by pm."""
- from hermes_constants import get_default_hermes_root
-
from pm.paths import repo_root, store_root
- machine_cache = get_default_hermes_root() / "cache" / "uv"
+ machine_cache = uv_cache_path()
marker = machine_cache / ".seeded"
# The marker names the lock whose payload was merged. An update ships a new payload cache for
# a new lock; a bare "done" marker skipped it forever, so plugin rebuilds fetched the new pins
diff --git a/pm/uv_cache_health.py b/pm/uv_cache_health.py
new file mode 100644
index 00000000000..e10fa10526f
--- /dev/null
+++ b/pm/uv_cache_health.py
@@ -0,0 +1,131 @@
+"""Find corrupt entries in PM's uv cache.
+
+uv unpacks every wheel into ``<cache>/.tmpXXXX`` and renames the directory
+into ``archive-v0/<id>``; it never flushes the file data first. When the
+machine stops mid-install (a hosted restart, a power cut), the rename can
+survive while the files read back as NUL bytes. uv then reuses that entry on
+every later sync and fails at install time with "The wheel is invalid", and
+retrying cannot help. These helpers recognise that failure and name the
+packages to purge. Deletion always goes through ``uv cache clean`` (the caller),
+which takes uv's cache lock, so a concurrent sync never loses files mid-read.
+
+Stdlib only: the bootstrap runner imports pm.environment on an older system
+python.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+import re
+
+# uv's install step names the wheel it was linking from the cache:
+# error: Failed to install: lxml-6.1.3-cp314-...whl (lxml==6.1.3)
+_FAILED_INSTALL = re.compile(r"failed to install: ([^\s()]+?\.whl)\b", re.IGNORECASE)
+
+# Causes that mean the cached copy itself is unusable. A fetch, resolver or
+# disk-full failure never prints these, so it is never mistaken for corruption.
+_CORRUPT_CAUSES = (
+ "the wheel is invalid", # WHEEL/METADATA unreadable, .dist-info missing
+ "`record` file is invalid", # RECORD unreadable
+)
+# A cache pointer naming an archive whose files are gone ("No such file or
+# directory (os error 2)"; Windows also says "os error 3" for a missing dir).
+_MISSING_ARCHIVE = re.compile(r"archive-v0[\\/][^\s`'\"]+.*\(os error [23]\)", re.IGNORECASE)
+
+# PEP 508 project names only: these become `uv cache clean` arguments.
+_NAME = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?")
+_DIST_INFO = re.compile(r"(?P<name>.+?)-[^-]+\.dist-info")
+
+
+def normalize(name: str) -> str:
+ """PEP 503 normal form, the spelling uv's cache uses."""
+ return re.sub(r"[-_.]+", "-", name).lower()
+
+
+def _valid(name: str) -> str | None:
+ return normalize(name) if _NAME.fullmatch(name) else None
+
+
+def failed_cached_packages(output: str) -> set[str]:
+ """Packages uv could not install because their cached copy is corrupt.
+
+ Empty unless uv failed in its install step AND the cause is one of the
+ cache-integrity shapes above, so a resolver, network or build failure is
+ never retried as corruption.
+ """
+ text = output or ""
+ lowered = text.lower()
+ if not (any(cause in lowered for cause in _CORRUPT_CAUSES) or _MISSING_ARCHIVE.search(text)):
+ return set()
+ names = set()
+ for match in _FAILED_INSTALL.finditer(text):
+ name = _valid(match.group(1).split("-", 1)[0])
+ if name:
+ names.add(name)
+ return names
+
+
+def _readable(path: Path, marker: bytes, limit: int = 65536) -> bool:
+ try:
+ with path.open("rb") as stream:
+ head = stream.read(limit)
+ except OSError:
+ return False
+ return marker in head and b"\0" not in head
+
+
+def corrupt_cache_entries(cache: Path) -> dict[str, list[Path]]:
+ """Unpacked cache entries uv cannot install from, by package.
+
+ Checks the three files uv reads first (WHEEL, METADATA, RECORD); an
+ interrupted write leaves them empty or NUL-filled. Entries without a
+ .dist-info (unknown layouts) and symlinked entries are skipped, never
+ guessed at. Read-only.
+ """
+ archive = cache / "archive-v0"
+ found: dict[str, list[Path]] = {}
+ try:
+ buckets = list(archive.iterdir())
+ except OSError:
+ return found
+ for bucket in buckets:
+ try:
+ if bucket.is_symlink() or not bucket.is_dir():
+ continue
+ infos = [entry for entry in bucket.iterdir() if entry.name.endswith(".dist-info")]
+ except OSError:
+ continue
+ for info in infos:
+ match = _DIST_INFO.fullmatch(info.name)
+ name = match and _valid(match.group("name"))
+ if not name:
+ continue
+ if not (_readable(info / "WHEEL", b"Wheel-Version:")
+ and _readable(info / "METADATA", b"Name:")
+ and _readable(info / "RECORD", b",")):
+ found.setdefault(name, []).append(bucket)
+ return found
+
+
+def corrupt_cached_packages(cache: Path) -> set[str]:
+ """Packages with at least one corrupt unpacked cache entry."""
+ return set(corrupt_cache_entries(cache))
+
+
+def remove_corrupt_entries(cache: Path, names: set[str]) -> None:
+ """Delete the corrupt archive entries of *names* that ``uv cache clean`` left behind.
+
+ Where uv links a wheel to its archive by symlink (Linux), clean drops the
+ link and leaves the archive, which nothing uses again. ``uv cache prune``
+ is not an option: PM seeds this cache from a bundle copy whose links are
+ real directories, and prune treats their archives as unreachable, so the
+ next install fails. An archive entry is never rewritten once uv renames it
+ into place, so deleting one that fails validation cannot take a good copy
+ from a concurrent install. rmtree refuses a symlinked root and does not
+ follow links inside it.
+ """
+ import shutil
+
+ for name, buckets in corrupt_cache_entries(cache).items():
+ if name in names:
+ for bucket in buckets:
+ shutil.rmtree(bucket, ignore_errors=True)
diff --git a/tests/pm/test_uv_cache_corruption.py b/tests/pm/test_uv_cache_corruption.py
new file mode 100644
index 00000000000..0e1430c7c42
--- /dev/null
+++ b/tests/pm/test_uv_cache_corruption.py
@@ -0,0 +1,206 @@
+"""A corrupt entry in PM's uv cache must not fail every later install.
+
+A machine stop during an install can leave an unpacked wheel in uv's cache
+whose files read back as NUL bytes: uv renames its unpack directory into
+``archive-v0`` without flushing the data first. uv then reuses that entry on
+every sync and fails with "The wheel is invalid", so retrying never helps. PM
+purges the damaged package(s) through ``uv cache clean`` and retries, and
+gives up with a clear message when a fresh copy is broken too.
+"""
+from __future__ import annotations
+
+import io
+import json
+import os
+from pathlib import Path
+import shutil
+import sys
+
+import pytest
+
+from pm.environment import PythonEnvironment
+from pm.package import InstallError
+from pm.uv_cache_health import corrupt_cached_packages, failed_cached_packages
+from tests.pm._fixtures import _run, _wheel
+
+LIVE_FAILURE = """\
+Building hermes-agent @ file:///opt/data/installs/351f/environments/g/workspace
+ Built hermes-agent @ file:///opt/data/installs/351f/environments/g/workspace
+Prepared 1 package in 2.82s
+error: Failed to install: lxml-6.1.3-cp314-cp314-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl (lxml==6.1.3)
+ cause: The wheel is invalid: Invalid Wheel-Version in `WHEEL` file: None
+"""
+
+
[email protected](("output", "expected"), [
+ (LIVE_FAILURE, {"lxml"}),
+ ("error: Failed to install: Foo_Bar-1.0-py3-none-any.whl (foo-bar==1.0)\n"
+ " cause: `RECORD` file is invalid\n cause: CSV deserialize error", {"foo-bar"}),
+ ("error: Failed to install: alpha-1.0-py3-none-any.whl (alpha==1.0)\n"
+ " cause: failed to read directory `/c/archive-v0/waZDcAKYSZH8lwFY`: No such file or directory (os error 2)",
+ {"alpha"}),
+ ("error: Failed to install: alpha-1.0-py3-none-any.whl (alpha==1.0)\n"
+ " cause: failed to read directory `C:\\Users\\a\\cache\\uv\\archive-v0\\waZD`: "
+ "The system cannot find the path specified. (os error 3)", {"alpha"}),
+])
+def test_cache_corruption_names_the_package(output, expected):
+ assert failed_cached_packages(output) == expected
+
+
[email protected]("output", [
+ "error: No solution found when resolving dependencies:\n Because alpha==2 was not found ...",
+ "error: Failed to fetch: `https://pypi.org/simple/alpha/`\n Caused by: Request failed after 3 retries",
+ "error: Failed to install: alpha-1.0-py3-none-any.whl (alpha==1.0)\n"
+ " cause: failed to hardlink file from /c/archive-v0/abc/alpha/__init__.py to /v/lib/alpha/__init__.py: "
+ "No space left on device (os error 28)",
+ "error: Failed to install: alpha-1.0-py3-none-any.whl (alpha==1.0)\n"
+ " cause: failed to create directory `/v/lib/alpha`: Permission denied (os error 13)",
+ " Caused by: The wheel is invalid: Invalid Wheel-Version", # no install step to name a package
+ "error: Failed to install: --force-1.0-py3-none-any.whl (x==1)\n cause: The wheel is invalid: x",
+])
+def test_other_failures_are_not_cache_corruption(output):
+ assert failed_cached_packages(output) == set()
+
+
+def project(tmp_path):
+ uv = shutil.which("uv")
+ assert uv, "cache recovery tests require uv on PATH"
+ source = tmp_path / "source"
+ source.mkdir()
+ wheels = tmp_path / "wheels"
+ wheels.mkdir()
+ for name in ("alpha_dep", "beta_dep"):
+ _wheel(wheels, name)
+ (source / "pyproject.toml").write_text(
+ '[project]\nname="cache-root"\nversion="1"\nrequires-python=">=3.11"\n'
+ 'dependencies=["alpha-dep==1.0", "beta-dep==1.0"]\n'
+ '[tool.uv]\npackage=false\nno-index=true\n'
+ f'find-links=[{json.dumps(wheels.as_posix())}]\n', encoding="utf-8")
+ home = tmp_path / "home"
+ home.mkdir()
+ env = {key: value for key, value in os.environ.items()
+ if not key.startswith(("UV_", "PYTHON")) and key != "VIRTUAL_ENV"}
+ env.update(HOME=str(home), USERPROFILE=str(home), XDG_CONFIG_HOME=str(home), XDG_CONFIG_DIRS=str(home))
+ environment = _environment(Path(uv), tmp_path, "first", env)
+ environment.lock(source, timeout=120)
+ environment.create()
+ environment.sync(source, timeout=120) # populates the cache
+ return source, Path(uv), env, wheels
+
+
+def _environment(uv: Path, root: Path, name: str, env, output=None) -> PythonEnvironment:
+ return PythonEnvironment(uv=uv, python=Path(sys.executable), destination=root / name / "venv",
+ cache=root / "cache", env=env, offline=True, output=output)
+
+
+def _cached(cache: Path, name: str) -> Path:
+ matches = list((cache / "archive-v0").glob(f"*/{name}-1.0.dist-info"))
+ assert len(matches) == 1, matches
+ return matches[0]
+
+
+def _nul_fill(path: Path) -> None:
+ """What a crash leaves: the file keeps its size, its data never reached the disk."""
+ size = max(path.stat().st_size, 1)
+ path.write_bytes(b"\0" * size)
+
+
+def _record_uv_calls(monkeypatch) -> list[list[str]]:
+ calls: list[list[str]] = []
+ real = PythonEnvironment._run
+
+ def recording(self, args, *, cwd, timeout):
+ calls.append(list(args))
+ return real(self, args, cwd=cwd, timeout=timeout)
+
+ monkeypatch.setattr(PythonEnvironment, "_run", recording)
+ return calls
+
+
+def test_sync_recovers_from_nul_filled_cache_entries(project, tmp_path, monkeypatch):
+ """The live shape: two packages damaged by one crash, the first a NUL WHEEL file."""
+ source, uv, env, _ = project
+ cache = tmp_path / "cache"
+ _nul_fill(_cached(cache, "alpha_dep") / "WHEEL")
+ for part in _cached(cache, "beta_dep").iterdir():
+ _nul_fill(part)
+ assert corrupt_cached_packages(cache) == {"alpha-dep", "beta-dep"}
+ calls = _record_uv_calls(monkeypatch)
+ notes = io.StringIO()
+
+ second = _environment(uv, tmp_path, "second", env, output=notes)
+ second.create()
+ second.sync(source, timeout=120)
+
+ assert _run([str(second.executable), "-I", "-c", "import alpha_dep, beta_dep; print(alpha_dep.__version__)"],
+ cwd=tmp_path, env=env) == "1.0"
+ # One purge covered both packages, then exactly one retry.
+ assert [c[:2] for c in calls].count(["cache", "clean"]) == 1
+ assert ["cache", "prune"] not in [c[:2] for c in calls] # prune breaks PM's seeded cache
+ assert sorted(next(c for c in calls if c[:2] == ["cache", "clean"])[2:]) == ["alpha-dep", "beta-dep"]
+ assert sum(c[0] == "sync" for c in calls) == 2
+ assert corrupt_cached_packages(cache) == set()
+ assert "alpha-dep, beta-dep is corrupt" in notes.getvalue()
+
+
+def test_a_wheel_broken_at_the_source_fails_once_with_a_clear_message(project, tmp_path, monkeypatch):
+ """Purging cannot fix a source that serves a broken wheel: one retry, then a named error."""
+ source, uv, env, wheels = project
+ cache = tmp_path / "cache"
+ (wheels / "alpha_dep-1.0-py3-none-any.whl").unlink()
+ _wheel(wheels, "alpha_dep", extra={"alpha_dep-1.0.dist-info/WHEEL": "\0" * 40})
+ # The lock's hash would reject the new bytes before install; forget it so uv takes the wheel.
+ (source / "uv.lock").unlink()
+ _environment(uv, tmp_path, "relock", env).lock(source, timeout=120)
+ shutil.rmtree(cache)
+ calls = _record_uv_calls(monkeypatch)
+
+ broken = _environment(uv, tmp_path, "broken", env)
+ broken.create()
+ with pytest.raises(InstallError) as caught:
+ broken.sync(source, timeout=120)
+
+ message = str(caught.value)
+ assert "alpha-dep" in message and str(cache) in message and "still invalid" in message
+ assert "broken wheel" in caught.value.remedy
+ assert [c[:2] for c in calls].count(["cache", "clean"]) == 1
+ assert sum(c[0] == "sync" for c in calls) == 2
+
+
+def test_a_failure_that_is_not_cache_corruption_is_not_retried(project, tmp_path, monkeypatch):
+ """A missing distribution (offline, nothing cached) fails once and never touches the cache."""
+ source, uv, env, wheels = project
+ cache = tmp_path / "cache"
+ (wheels / "alpha_dep-1.0-py3-none-any.whl").unlink()
+ shutil.rmtree(cache)
+ calls = _record_uv_calls(monkeypatch)
+
+ missing = _environment(uv, tmp_path, "missing", env)
+ missing.create()
+ with pytest.raises(InstallError):
+ missing.sync(source, timeout=120)
+
+ assert not any(c[:1] == ["cache"] for c in calls)
+ assert sum(c[0] == "sync" for c in calls) == 1
+
+
+def test_doctor_reports_then_repairs_corrupt_cache_entries(project, tmp_path, monkeypatch, capsys):
+ from pm import cli
+ import pm.packages
+
+ _, uv, env, _ = project
+ cache = tmp_path / "cache"
+ _nul_fill(_cached(cache, "alpha_dep") / "METADATA")
+ monkeypatch.setattr(pm.packages, "uv_cache_path", lambda: cache)
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (uv, Path(sys.executable)))
+ monkeypatch.setattr("pm.environment._base_environment", lambda base=None: dict(env))
+
+ assert cli._doctor_uv_cache(repair=False) == 1
+ assert "alpha-dep" in capsys.readouterr().out
+ assert corrupt_cached_packages(cache) == {"alpha-dep"} # read-only without --repair
+
+ assert cli._doctor_uv_cache(repair=True) == 0
+ assert "removed corrupt entries for alpha-dep" in capsys.readouterr().out
+ assert corrupt_cached_packages(cache) == set()
+ assert cli._doctor_uv_cache(repair=False) == 0
diff --git a/website/docs/reference/package-management.md b/website/docs/reference/package-management.md
index ea477f61952..188aa0c8012 100644
--- a/website/docs/reference/package-management.md
+++ b/website/docs/reference/package-management.md
@@ -540,7 +540,7 @@ hermes pm install chromium
| `pm install --without NAME` | Do a bare install without the default optional package `NAME` (`chromium` or `cua-driver`), and record that choice. Later bare installs and `hermes update` also leave it out. The installers' `--skip-browser` / `-SkipBrowser` and `--skip-computer-use` / `-SkipComputerUse` (`--without cua-driver`) use this. The browser opt-out passes the legacy name `--without agent-browser`, which every PM release accepts and this one reads as `chromium`; a choice recorded under that name still skips `chromium`. |
| `pm install --tools-only` | Install that tool closure and put it on PATH, then stop. The venv sync does not run. |
| `pm env [names...]` | Print installed packages' PM-contributed environment values as JSON. It does not install missing packages, though a cold Hermes launch may prepare its own Python runtime first. |
-| `pm doctor` | Check installed tool identities, files, and digests against the lock. |
+| `pm doctor` | Check installed tool identities, files, and digests against the lock, and look for corrupt entries in PM's uv cache. `--repair` removes those entries so they are fetched again. |
| `pm repair` | Rebuild the recorded Python dependency set in a new generation, validate it, then select it. Does not update pins, features, or plugin configuration. |
| `pm environment NAME --extra EXTRA` / `--requirement REQ` | Make the isolated side environment `HERMES_HOME/environments/NAME` current and print only its Python path on stdout (progress goes to stderr), for shell callers such as skills: `PY="$(hermes pm environment documents --extra documents --extra documents-pdf)"`. `--extra` installs the pinned requirements of extras declared in `pyproject.toml`; `--requirement` takes bounded ad hoc requirements. The environment records its own lock, and only a changed requirement set or Python pin builds a new generation. Concurrent calls serialize on the environment's lock, and a rebuild lands in a new generation, so a caller already using the previous one keeps its files. An explicit install: it runs even where lazy installs are off. Never `pip install` into the result. |
| `pm status` | Print the latest sync/update receipt as JSON, or report that no receipt exists. |
@@ -617,6 +617,7 @@ without upload times, it stops with `has no publish time`; use
- **New environment requires restart:** restart the affected Hermes process. Do not add a second site-packages tree to its live imports.
- **Dependency conflict:** read `hermes pm status`. Correct the plugin requirements before retrying admission.
- **Damaged Python dependencies:** run `hermes pm repair`, then restart Hermes. Repair replays the selected generation's saved workspace and lock without parsing plugin configuration. An unreadable record or missing saved lock fails without selecting a reduced dependency set. Before a generation exists, repair uses the shipped or committed lock and recorded feature set.
+- **Corrupt cached package** (`The wheel is invalid`, `RECORD file is invalid`): a machine stop during an install can leave a uv cache entry whose files are empty or NUL-filled. Installs remove the damaged package from PM's uv cache and retry on their own; `hermes pm doctor` reports such entries and `hermes pm doctor --repair` removes them. If the same package is still invalid after a fresh download, the package source is serving a broken wheel.
- **Interrupted dependency install:** startup requests the same PM repair before dependency activation. Automatic attempts are bounded; `pm repair` retries explicitly. A failed repair preserves the previous selection and its retry marker.
- **Damaged Python executable or application source:** repair or reinstall through the package owner. PM cannot run without those files. Signed payload files are never modified by dependency repair.
- **Unknown package or extra:** use the declared name. `pm install` takes package names, not Python extra names or pip specifications.