Skip to content

The agent that grows with you

merge: integrate origin/main while preserving PM ownership

ethernetf622ea76b37c
diff --cc hermes_cli/profile_distribution.py
index 8d37d789fca,9e458af6c0b..7a2e4f775a4
--- a/hermes_cli/profile_distribution.py
+++ b/hermes_cli/profile_distribution.py
@@@ -15,13 -15,13 +15,14 @@@ import subproces
import tempfile
from dataclasses import dataclass, field
from datetime import datetime, timezone
-from pathlib import Path, PurePosixPath
+from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
-import yaml
+import hermes_yaml as yaml
from hermes_cli._subprocess_compat import noninteractive_git_env
+from hermes_cli.archive_safe import normalize_archive_parts
+ from utils import rmtree_readonly
MANIFEST_FILENAME = "distribution.yaml"
diff --cc tests/hermes_cli/test_plugin_install_ref.py
index c1d3f40d165,ece3d8ca2c0..7f62de6039d
--- a/tests/hermes_cli/test_plugin_install_ref.py
+++ b/tests/hermes_cli/test_plugin_install_ref.py
@@@ -360,7 -350,7 +360,8 @@@ def test_metadata_write_failure_rolls_b
def test_reinstall_after_manual_directory_removal_retains_pin(monkeypatch, tmp_path):
- from hermes_cli.plugins_cmd import _install_plugin_core, _rmtree_force
+ from hermes_cli.plugins_cmd import _install_plugin_core
++ from utils import rmtree_readonly
repo, old_sha, _new_sha = _plugin_repo(tmp_path)
home = tmp_path / "home"
@@@ -368,7 -358,7 +369,7 @@@
target, _manifest, _name = _install_plugin_core(
repo.as_uri(), force=False, ref=old_sha
)
- _rmtree_force(target)
- shutil.rmtree(target)
++ rmtree_readonly(target)
target, _manifest, _name = _install_plugin_core(repo.as_uri(), force=False)
diff --cc tests/hermes_cli/test_plugins_cmd.py
index 5527de754b7,598a72966ab..c86a30de11b
--- a/tests/hermes_cli/test_plugins_cmd.py
+++ b/tests/hermes_cli/test_plugins_cmd.py
@@@ -420,8 -478,59 +420,23 @@@ class TestCmdRemove
cmd_remove("nonexistent-plugin")
assert exc_info.value.code == 1
-
+ def test_remove_plugin_core_deletes_read_only_git_tree(self, tmp_path):
+ """Git leaves loose objects read-only: removal must clear that, not abort (#117179)."""
+ from hermes_cli.plugins_cmd import _remove_plugin_core
+
+ target = tmp_path / "plugins" / "demo"
+ obj_dir = target / ".git" / "objects" / "4b"
+ obj_dir.mkdir(parents=True)
+ obj = obj_dir / "825dc642cb6eb9a060e54bf8d69288fbee4904"
+ obj.write_text("blob", encoding="utf-8")
+ obj.chmod(0o444)
+ obj_dir.chmod(0o555)
+
+ _remove_plugin_core(target)
+
+ assert not target.exists()
-# ── cmd_list tests ─────────────────────────────────────────────────────────
-
-
-class TestCmdList:
- """Test the list command."""
-
- @patch("hermes_cli.plugins_cmd._plugins_dir")
- def test_list_empty_plugins_dir(self, mock_plugins_dir):
- from hermes_cli.plugins_cmd import cmd_list
-
- mock_plugins_dir_val = MagicMock()
- mock_plugins_dir_val.iterdir.return_value = []
- mock_plugins_dir.return_value = mock_plugins_dir_val
-
- cmd_list()
-
- @patch("hermes_cli.plugins_cmd._plugins_dir")
- @patch("hermes_cli.plugins_cmd._read_manifest")
- def test_list_with_plugins(self, mock_read_manifest, mock_plugins_dir):
- from hermes_cli.plugins_cmd import cmd_list
-
- mock_plugins_dir_val = MagicMock()
- mock_plugin_dir = MagicMock()
- mock_plugin_dir.name = "test-plugin"
- mock_plugin_dir.is_dir.return_value = True
- mock_plugin_dir.__truediv__ = lambda self, x: MagicMock(
- exists=MagicMock(return_value=False)
- )
- mock_plugins_dir_val.iterdir.return_value = [mock_plugin_dir]
- mock_plugins_dir.return_value = mock_plugins_dir_val
- mock_read_manifest.return_value = {"name": "test-plugin", "version": "1.0.0"}
-
- cmd_list()
-
-
# ── _copy_example_files tests ─────────────────────────────────────────────────
diff --cc tests/hermes_cli/test_profile_distribution.py
index 356892d83ab,a2cee719952..c30fdeb6ba3
--- a/tests/hermes_cli/test_profile_distribution.py
+++ b/tests/hermes_cli/test_profile_distribution.py
@@@ -211,6 -214,36 +214,36 @@@ class TestLooksLikeGitUrl
def test_accepts_git_sources(self, src):
assert _looks_like_git_url(src)
- @pytest.mark.windows_only
++ @pytest.mark.platforms("windows")
+ def test_git_source_removes_read_only_git_metadata(self, tmp_path, monkeypatch):
+ origin = tmp_path / "origin"
+ subprocess.run(["git", "init", "--quiet", str(origin)], check=True)
+ (origin / MANIFEST_FILENAME).write_text("name: demo\nversion: 1.0.0\n", encoding="utf-8")
+ subprocess.run(["git", "-C", str(origin), "add", "."], check=True)
+ subprocess.run([
+ "git", "-C", str(origin), "-c", "user.name=Test", "-c",
+ "[email protected]", "commit", "--quiet", "-m", "init",
+ ], check=True)
+ saw_read_only_objects = []
+
+ def clone_local(_url, dest):
+ subprocess.run(["git", "clone", "--quiet", str(origin), str(dest)], check=True)
+ objects = [path for path in (dest / ".git" / "objects").rglob("*") if path.is_file()]
+ saw_read_only_objects.append(
+ bool(objects) and any(
+ path.stat().st_file_attributes & stat.FILE_ATTRIBUTE_READONLY for path in objects
+ )
+ )
+
+ monkeypatch.setattr("hermes_cli.profile_distribution._git_clone", clone_local)
+
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ staged, _provenance = _stage_source("https://example.invalid/demo.git", workdir)
+
+ assert saw_read_only_objects == [True]
+ assert not (staged / ".git").exists()
+
# ===========================================================================
# Install — fresh and force (from a local-directory source)
diff --cc tests/test_utils_rmtree_readonly.py
index 00000000000,93d92134768..7f84c254f6f
mode 000000,100644..100644
--- a/tests/test_utils_rmtree_readonly.py
+++ b/tests/test_utils_rmtree_readonly.py
@@@ -1,0 -1,74 +1,74 @@@
+ """``utils.rmtree_readonly`` removes trees that ``shutil.rmtree`` refuses.
+
+ Git marks loose object files read-only on Windows (``WinError 5``), and package
+ installs arrive as read-only trees on POSIX, so every cleanup path that deletes a
+ clone needs the retry. Regression coverage for #117170, #117176, #117179 and #117184.
+ """
+
+ from __future__ import annotations
+
+ import os
+ import stat
+ from pathlib import Path
+
+ import pytest
+
+ import utils
+ from utils import rmtree_readonly
+
+
+ def _read_only_object_dir(root: Path) -> Path:
+ """A clone-shaped tree whose loose object and its directory are read-only."""
+ obj_dir = root / ".git" / "objects" / "4b"
+ obj_dir.mkdir(parents=True)
+ obj = obj_dir / "825dc642cb6eb9a060e54bf8d69288fbee4904"
+ obj.write_text("blob", encoding="utf-8")
+ obj.chmod(0o444)
+ obj_dir.chmod(0o555) # POSIX unlink needs a writable parent
+ return obj_dir
+
+
+ def test_checkpoint_clear_all_removes_tree_with_read_only_object(tmp_path):
+ """Driven through a production call site (#117170): ``checkpoint_manager.clear_all`` must
+ reach ``rmtree_readonly`` — a bare ``shutil.rmtree`` there reports ``deleted=False``."""
+ from tools.checkpoint_manager import clear_all
+
+ root = tmp_path / "checkpoints"
+ obj_dir = _read_only_object_dir(root)
+ assert not (obj_dir / "825dc642cb6eb9a060e54bf8d69288fbee4904").stat().st_mode & stat.S_IWUSR
+
+ out = clear_all(root)
+
+ assert out["deleted"] is True
+ assert not root.exists()
+
+
+ def test_removes_read_only_file_in_writable_directory(tmp_path):
+ """The Git-for-Windows shape: the file is read-only, its directory is writable."""
+ root = tmp_path / "plugins" / "demo"
+ obj_dir = root / ".git" / "objects" / "4b"
+ obj_dir.mkdir(parents=True)
+ (obj_dir / "825dc642cb6eb9a060e54bf8d69288fbee4904").write_text("blob", encoding="utf-8")
+ (obj_dir / "825dc642cb6eb9a060e54bf8d69288fbee4904").chmod(stat.S_IREAD)
+
+ rmtree_readonly(root)
+
+ assert not root.exists()
+
+
+ def test_non_permission_failures_propagate(tmp_path, monkeypatch):
+ """Only ``PermissionError`` is retried — everything else keeps rmtree semantics."""
+ attempts: list = []
+
+ def _fake(path, **kwargs):
+ attempts.append(path)
+ raise OSError(39, "Directory not empty", str(path))
+
+ monkeypatch.setattr(utils.shutil, "rmtree", _fake)
+
+ with pytest.raises(OSError) as excinfo:
+ rmtree_readonly(tmp_path)
+
+ assert excinfo.value.errno == 39
+ assert len(attempts) == 1 # no second attempt for a non-permission failure
diff --cc tools/checkpoint_manager.py
index 07921c88fce,ef9cfc93188..e99913bc853
--- a/tools/checkpoint_manager.py
+++ b/tools/checkpoint_manager.py
@@@ -54,15 -17,17 +54,15 @@@ import loggin
import os
import re
import shutil
-import stat as stat_mod
import subprocess
import time
-from dataclasses import dataclass, field
from pathlib import Path
-from typing import Dict, Iterator, List, NamedTuple, Optional, Set, Tuple
-
from hermes_constants import get_hermes_home
-from hermes_cli._subprocess_compat import windows_hide_flags
+from hermes_cli._subprocess_compat import selected_git_env, windows_hide_flags
from hermes_cli.gitlock import clear_stale_tmp_packs
+from typing import Dict, List, Optional, Set, Tuple
+
- from utils import env_int
+ from utils import env_int, rmtree_readonly
logger = logging.getLogger(__name__)
@@@ -1624,189 -1023,110 +1624,189 @@@ def _workdir_is_observably_gone
if parent_dev is not None and parent_ino is not None:
st = parent.stat()
if (st.st_dev, st.st_ino) != (parent_dev, parent_ino):
+ # A different directory is visible at the parent's path than
+ # the one the project lived in — the volume is detached (its
+ # underlay showing through) or was swapped. Not a deletion.
return False
elif require_parent_identity:
+ # No recorded identity to check against — we cannot tell the
+ # project's real parent from an underlay directory exposed by an
+ # unmount. Unsure never deletes; retention still reclaims.
return False
- with os.scandir(parent) as entries:
- return next(entries, None) is not None or os.path.ismount(parent)
+ if _dir_has_any_entry(parent):
+ return True
+ # Empty parent: only evidence if that directory is a mount point, i.e.
+ # the volume is attached right now and simply does not hold the
+ # project. An empty plain directory is an unmounted mount point as
+ # readily as an emptied project root.
+ return os.path.ismount(parent)
except OSError:
- return False # probe failed (permission, I/O error) — not evidence of deletion
+ # Probe failed (permission, I/O error) — not evidence of deletion.
+ return False
-def _int_or_none(value) -> Optional[int]:
- return value if isinstance(value, int) and not isinstance(value, bool) else None
+def _dir_has_any_entry(directory: Path) -> bool:
+ """True when ``directory`` contains at least one entry.
+ Stops after the first entry rather than materializing the listing; a
+ project root can hold a large tree.
+ """
+ with os.scandir(directory) as entries:
+ for _ in entries:
+ return True
+ return False
-def _sweep(entries, result: Dict[str, int], delete) -> None:
- """Shared orphan/stale sweep. ``entries`` yields ``(item, gone, allowed, is_stale)`` where
- ``is_stale`` is a thunk (may do I/O, so only evaluated for non-orphans); "orphan" wins."""
- for item, gone, allowed, is_stale in entries:
- result["scanned"] += 1
- reason = "orphan" if gone and allowed else "stale" if is_stale() else None
- if reason is not None:
- delete(item, reason)
+def prune_checkpoints(
+ retention_days: int = 7,
+ delete_orphans: bool = True,
+ checkpoint_base: Optional[Path] = None,
+ max_total_size_mb: int = 0,
+ orphan_allowlist: Optional[set] = None,
+) -> Dict[str, int]:
+ """Delete stale/orphan checkpoints and reclaim store space.
-def _rmtree_counted(child: Path, result: Dict[str, int], key: str, fail_fmt: str, label) -> None:
- """rmtree ``child``, crediting bytes + ``result[key]``; failures count as ``errors`` when tracked."""
- try:
- size = _dir_size_bytes(child)
- rmtree_readonly(child)
- result["bytes_freed"] += size
- result[key] += 1
- except OSError as exc:
- if "errors" in result:
- result["errors"] += 1
- logger.warning(fail_fmt, label, exc)
-
-
-def _prune_legacy_archives(base: Path, cutoff: float, result: Dict[str, int]) -> None:
- """Delete ``legacy-*`` archives whose mtime predates ``cutoff`` (skipped when retention is off)."""
- for child in _legacy_archives(base) if cutoff > 0 else ():
- mtime = _mtime_or_none(child)
- if mtime is not None and mtime < cutoff:
- _rmtree_counted(child, result, "deleted_stale", "Failed to delete legacy archive %s: %s", child)
-
-
-def _prune_pre_v2_repos(base: Path, cutoff: float, delete_orphans: bool,
- orphan_allowlist: Optional[set], result: Dict[str, int]) -> None:
- """Sweep pre-v2 per-project shadow repos exactly as the v1 pruner did (scan shared with
- ``store_status``; the frozen layout has no recorded parent identity, so orphan detection
- uses the structural checks only)."""
- def entries():
- for repo in _pre_v2_shadow_repos(base):
- child = repo["path"]
- gone = delete_orphans and not repo["marker_unreadable"] and (
- repo["workdir"] is None
- or _workdir_is_observably_gone(repo["workdir"], require_parent_identity=False))
- yield (child, gone, orphan_allowlist is None or str(child) in orphan_allowlist,
- lambda c=child: cutoff > 0 and 0 < _newest_mtime(c) < cutoff)
+ A project entry is deleted when either:
- _sweep(entries(), result, lambda child, reason: _rmtree_counted(
- child, result, f"deleted_{reason}", "Failed to prune checkpoint repo %s: %s", child.name))
+ * ``delete_orphans=True`` and its ``workdir`` no longer exists on disk
+ (the original project was deleted / moved); OR
+ * its ``last_touch`` is older than ``retention_days`` days.
+ ``orphan_allowlist``, when not ``None``, restricts orphan deletion to
+ the given identities (v2 project ``_hash`` strings and/or pre-v2 shadow
+ repo paths as ``str``). This lets a caller that showed the user a
+ confirmation preview (built from ``store_status()``) bind the resulting
+ deletion to exactly what was displayed — a project that only becomes
+ orphaned *after* the preview (e.g. its workdir vanishes while the human
+ is answering the prompt) is skipped rather than swept up under the
+ earlier confirmation. Pass ``None`` (the default) to delete every
+ currently-orphaned project, e.g. for ``--force`` or unattended callers
+ that never show a preview.
-def _prune_v2_projects(store: Path, cutoff: float, delete_orphans: bool,
- orphan_allowlist: Optional[set], result: Dict[str, int]) -> None:
- """Drop the ref, index and metadata of orphan/stale projects in the shared store."""
- def entries():
- for meta in _list_projects(store):
- dir_hash = meta.get("_hash") or ""
- workdir = meta.get("workdir") or ""
- if not dir_hash:
- continue
- gone = delete_orphans and (not workdir or _workdir_is_observably_gone(
- workdir, parent_dev=_int_or_none(meta.get("workdir_parent_dev")),
- parent_ino=_int_or_none(meta.get("workdir_parent_ino"))))
- yield (dir_hash, gone, orphan_allowlist is None or dir_hash in orphan_allowlist,
- lambda m=meta: cutoff > 0 and 0 < float(m.get("last_touch", 0) or 0) < cutoff)
-
- def delete(dir_hash: str, reason: str) -> None:
- _delete_ref(store, _ref_name(dir_hash))
- _unlink_quiet(_index_path(store, dir_hash))
- _unlink_quiet(_project_meta_path(store, dir_hash))
- result[f"deleted_{reason}"] += 1
-
- _sweep(entries(), result, delete)
-
-
-def prune_checkpoints(retention_days: int = 7, delete_orphans: bool = True, checkpoint_base: Optional[Path] = None,
- max_total_size_mb: int = 0, orphan_allowlist: Optional[set] = None) -> Dict[str, int]:
- """Delete stale/orphan checkpoints and reclaim store space. Never raises. Deleted when
- ``delete_orphans`` and the workdir is observably gone, OR last touch predates ``retention_days``
- (``<= 0`` disables). ``orphan_allowlist`` (v2 ``_hash`` strings and/or pre-v2 repo paths as
- ``str``) binds orphan deletion to exactly what a ``store_status()`` preview showed — a project
- orphaned after the preview is skipped; ``None`` deletes every current orphan (``--force``,
- unattended). ``max_total_size_mb > 0`` drops the oldest commit per project until the store fits."""
+ Additionally, if ``max_total_size_mb > 0`` and the store exceeds that
+ after orphan/stale pruning, the oldest commit per remaining project is
+ dropped until the store is under the cap.
+
+ Legacy-archive dirs (``legacy-*``) older than ``retention_days`` are
+ also deleted.
+
+ Returns a dict with counts ``{"scanned", "deleted_orphan",
+ "deleted_stale", "errors", "bytes_freed"}``.
+
+ Never raises — maintenance must never block interactive startup.
+ """
base = checkpoint_base or _resolve_checkpoint_base()
- result = _empty_prune_result()
+ result = {
+ "scanned": 0,
+ "deleted_orphan": 0,
+ "deleted_stale": 0,
+ "errors": 0,
+ "bytes_freed": 0,
+ }
if not base.exists():
return result
+
+ from tools.checkpoint_pruning import PruneError, store_lock
+
+ try:
+ with store_lock(base):
+ return _prune_checkpoints(base, result, retention_days, delete_orphans, max_total_size_mb, orphan_allowlist)
+ except (PruneError, OSError) as exc:
+ result["errors"] += 1
+ logger.warning("Checkpoint maintenance stopped: %s", exc)
+ return result
+
+
+def _prune_checkpoints(
+ base: Path, result: Dict[str, int], retention_days: int, delete_orphans: bool,
+ max_total_size_mb: int, orphan_allowlist: Optional[set],
+) -> Dict[str, int]:
size_before = _dir_size_bytes(base)
- cutoff = time.time() - retention_days * 86400 if retention_days > 0 else 0.0
- _prune_legacy_archives(base, cutoff, result)
- _prune_pre_v2_repos(base, cutoff, delete_orphans, orphan_allowlist, result)
+
+ # --- Legacy pre-v2 per-project shadow repos (kept directly under base) ---
+ # Pre-v2 layout: ``base/<hash>/HEAD`` etc. We treat these exactly as the
+ # v1 pruner did so behaviour is unchanged for anyone still on that layout
+ # or sitting on a mid-migration system.
+ cutoff = 0.0
+ if retention_days > 0:
+ cutoff = time.time() - retention_days * 86400
+
+ for child in base.iterdir():
+ if not child.is_dir():
+ continue
+ if child.name == _STORE_DIRNAME:
+ continue
+ if child.name.startswith(_LEGACY_PREFIX):
+ # Legacy archive: prune by dir mtime using same retention rule.
+ if retention_days <= 0:
+ continue
+ try:
+ m = child.stat().st_mtime
+ except OSError:
+ continue
+ if m >= cutoff:
+ continue
+ try:
+ size = _dir_size_bytes(child)
- shutil.rmtree(child)
++ rmtree_readonly(child)
+ result["bytes_freed"] += size
+ result["deleted_stale"] += 1
+ except OSError as exc:
+ result["errors"] += 1
+ logger.warning("Failed to delete legacy archive %s: %s", child, exc)
+
+ # Pre-v2 per-project shadow repos. Scanned via the same helper
+ # `store_status()` uses for its orphan preview, so a confirmation prompt
+ # built from that preview always matches what gets deleted here.
+ for repo in _pre_v2_shadow_repos(base):
+ child = repo["path"]
+ result["scanned"] += 1
+ reason: Optional[str] = None
+ if (
+ delete_orphans
+ and not repo["marker_unreadable"]
+ and (
+ repo["workdir"] is None
+ # The frozen pre-v2 layout has no metadata channel to carry a
+ # recorded parent identity, so only the structural checks
+ # (parent present + populated / live mount point) apply here.
+ or _workdir_is_observably_gone(
+ repo["workdir"], require_parent_identity=False,
+ )
+ )
+ and (orphan_allowlist is None or str(child) in orphan_allowlist)
+ ):
+ reason = "orphan"
+ if reason is None and retention_days > 0:
+ newest = 0.0
+ try:
+ for p in child.rglob("*"):
+ try:
+ mt = p.stat().st_mtime
+ newest = max(newest, mt)
+ except OSError:
+ continue
+ except OSError:
+ pass
+ if newest > 0 and newest < cutoff:
+ reason = "stale"
+ if reason is None:
+ continue
+ try:
+ size = _dir_size_bytes(child)
- shutil.rmtree(child)
++ rmtree_readonly(child)
+ result["bytes_freed"] += size
+ if reason == "orphan":
+ result["deleted_orphan"] += 1
+ else:
+ result["deleted_stale"] += 1
+ except OSError as exc:
+ result["errors"] += 1
+ logger.warning("Failed to prune checkpoint repo %s: %s", child.name, exc)
+
+ # --- v2 shared store: per-project ref pruning via metadata ---
store = _store_path(base)
- if _store_has_head(store):
+ if (store / "HEAD").exists():
# A gc killed by the store timeout strands tmp_pack_* files that gc.auto=0 means git
# itself never reclaims; sweep them even when no ref moved (a sweep is a directory
# listing, unlike the pack-rewriting gc gated on refs below).
@@@ -2079,17 -1262,9 +2079,15 @@@ def store_status(checkpoint_base: Optio
return out
+def _rmtree_force(path: Path) -> None:
- from hermes_cli.fs_utils import rmtree_force
-
- rmtree_force(path)
++ rmtree_readonly(path)
+
+
def clear_all(checkpoint_base: Optional[Path] = None) -> Dict[str, int]:
"""Nuke the entire checkpoint base (store + legacy). Irreversible.
- Returns ``{"bytes_freed": N, "deleted": bool}``."""
+
+ Returns ``{"bytes_freed": N, "deleted": bool}``.
+ """
base = checkpoint_base or _resolve_checkpoint_base()
out = {"bytes_freed": 0, "deleted": False}
if not base.exists():