Skip to content

The agent that grows with you

fix(pm): reclaim dependency state of deleted checkouts (pm gc + startup worktree prune)

Tekniumef4b04680883
diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.py
index ce77b82df55..bba0a4218b9 100644
--- a/hermes_cli/worktree_ops.py
+++ b/hermes_cli/worktree_ops.py
@@ -996,6 +996,19 @@ def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:
_prune_orphaned_branches(repo_root, protect=kept_branches)
+ # Trees removed by any path (this pass, `git worktree remove` by hand, a campaign's own
+ # cleanup) leave their ~200 MB dependency state under <home>/installs/ forever; reclaim it.
+ # Startup maintenance must never block a launch; the traceback goes to the debug log.
+ try:
+ from pm.environments import installs_root
+ from pm.install_states import collect_orphan_install_states
+
+ reclaimed = collect_orphan_install_states(installs_root())
+ if reclaimed:
+ logger.info("Reclaimed %d dependency state dir(s) of deleted checkouts", len(reclaimed))
+ except Exception:
+ logger.debug("Orphan install-state reclaim failed", exc_info=True)
+
# The conservative startup pass accumulates trees it can never reclaim; say so once per launch.
try:
from hermes_cli.worktree_gc import worktrees_summary
diff --git a/pm/cli.py b/pm/cli.py
index 3ef9ef6d038..f1bf1f7c1f0 100644
--- a/pm/cli.py
+++ b/pm/cli.py
@@ -521,8 +521,11 @@ def cmd_gc(args) -> int:
from pm.runtime import collect_runtime_generations
generations = collect_generations(repo_root())
runtimes = collect_runtime_generations(install_state_dir(repo_root()) / "pm-runtime")
+ from pm.environments import installs_root
+ from pm.install_states import collect_orphan_install_states
+ orphans = collect_orphan_install_states(installs_root())
print(f"gc: removed {removed}, kept {kept}; removed {len(generations)} dependency generations, "
- f"{len(runtimes)} PM runtime generations")
+ f"{len(runtimes)} PM runtime generations, {len(orphans)} install state dir(s) of deleted checkouts")
return 0
diff --git a/pm/install_states.py b/pm/install_states.py
new file mode 100644
index 00000000000..11a2c208ec1
--- /dev/null
+++ b/pm/install_states.py
@@ -0,0 +1,78 @@
+"""Reclaim per-checkout dependency state whose checkout is gone.
+
+Dependency state lives under ``<home>/installs/<install_key>`` where the key hashes the
+checkout path (:func:`pm.environments.install_key`). Every ``hermes -w`` worktree, review tree
+or scratch clone that boots the agent therefore commits a full environment (venv, test venv,
+PM runtime, ~200 MB each), and nothing removed it when the tree was deleted: one developer
+host carried 402 such orphans (80 GB) after a fortnight of worktree campaigns.
+
+The state dir records the checkout it belongs to in ``inputs/.project-root`` (written by
+:func:`pm.environments.record_activation_inputs`); a dir whose recorded checkout no longer
+exists has no possible reader. Removal still fails closed on anything a live process could
+hold: the install lock, or a generation lease.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import shutil
+from pathlib import Path
+
+logger = logging.getLogger(__name__)
+
+
+def orphan_install_states(installs: Path) -> list[Path]:
+ """State dirs whose recorded checkout is gone. Dirs without a record are left alone."""
+ if not installs.is_dir():
+ return []
+ orphans: list[Path] = []
+ for state in sorted(installs.iterdir()):
+ record = state / "inputs" / ".project-root"
+ if not state.is_dir() or not record.is_file():
+ continue
+ try:
+ root = record.read_text(encoding="utf-8-sig").strip()
+ except OSError:
+ continue
+ if root and not Path(root).exists():
+ orphans.append(state)
+ return orphans
+
+
+def _held(state: Path) -> bool:
+ """True while a process may still be using this state dir: the install lock is taken or a
+ generation lease is held. Any lock we cannot even open counts as held."""
+ from hermes_cli.runtime_state import leases_held
+ from pm.filesystem import lock_fd
+
+ lock = state / ".install.lock"
+ if lock.exists():
+ try:
+ fd = os.open(lock, os.O_RDWR)
+ except OSError:
+ return True
+ try:
+ if not lock_fd(fd, wait=False):
+ return True
+ finally:
+ os.close(fd)
+ environments = state / "environments"
+ if environments.is_dir():
+ for generation in environments.iterdir():
+ if generation.is_dir() and (generation / ".leases").is_dir() and leases_held(generation):
+ return True
+ return False
+
+
+def collect_orphan_install_states(installs: Path) -> list[Path]:
+ """Remove every unheld orphan state dir under *installs*; returns what was removed."""
+ removed: list[Path] = []
+ for state in orphan_install_states(installs):
+ if _held(state):
+ logger.debug("orphan install state %s is still held; skipped", state.name)
+ continue
+ shutil.rmtree(state, ignore_errors=True)
+ if not state.exists():
+ removed.append(state)
+ return removed
diff --git a/tests/pm/test_install_states_gc.py b/tests/pm/test_install_states_gc.py
new file mode 100644
index 00000000000..270b305c823
--- /dev/null
+++ b/tests/pm/test_install_states_gc.py
@@ -0,0 +1,53 @@
+"""Dependency state of a deleted checkout is reclaimed; state anything live could still read is
+kept (``pm/install_states.py``)."""
+
+from __future__ import annotations
+
+import os
+
+from pm.filesystem import lock_fd
+from pm.install_states import collect_orphan_install_states, orphan_install_states
+
+
+def _state(installs, key, project_root):
+ state = installs / key
+ (state / "inputs").mkdir(parents=True)
+ (state / "inputs" / ".project-root").write_text(str(project_root), encoding="utf-8")
+ (state / "environments" / "gen" / "venv").mkdir(parents=True)
+ return state
+
+
+def test_only_states_of_deleted_checkouts_are_reclaimed(tmp_path):
+ installs = tmp_path / "installs"
+ live_root = tmp_path / "checkout-live"
+ live_root.mkdir()
+ live = _state(installs, "aaaa", live_root)
+ gone = _state(installs, "bbbb", tmp_path / "checkout-deleted")
+ # Pre-record state (no .project-root) has no evidence either way: never touched.
+ unknown = installs / "cccc"
+ (unknown / "environments").mkdir(parents=True)
+
+ assert orphan_install_states(installs) == [gone]
+ assert collect_orphan_install_states(installs) == [gone]
+ assert live.is_dir() and unknown.is_dir() and not gone.exists()
+
+
+def test_held_orphan_is_kept(tmp_path):
+ installs = tmp_path / "installs"
+ locked = _state(installs, "dddd", tmp_path / "gone-a")
+ leased = _state(installs, "eeee", tmp_path / "gone-b")
+
+ fd = os.open(locked / ".install.lock", os.O_CREAT | os.O_RDWR, 0o600)
+ assert lock_fd(fd, wait=False)
+ lease_dir = leased / "environments" / "gen" / ".leases"
+ lease_dir.mkdir()
+ lease_fd = os.open(lease_dir / "reader", os.O_CREAT | os.O_RDWR, 0o600)
+ assert lock_fd(lease_fd, wait=False)
+ try:
+ assert collect_orphan_install_states(installs) == []
+ assert locked.is_dir() and leased.is_dir()
+ finally:
+ os.close(fd)
+ os.close(lease_fd)
+ # Locks released (owner exited): both are reclaimed on the next pass.
+ assert sorted(p.name for p in collect_orphan_install_states(installs)) == ["dddd", "eeee"]
diff --git a/website/docs/reference/package-management.md b/website/docs/reference/package-management.md
index b50f6a55ec2..9bb369b11e8 100644
--- a/website/docs/reference/package-management.md
+++ b/website/docs/reference/package-management.md
@@ -535,7 +535,7 @@ hermes pm install chromium
| `pm doctor` | Check installed tool identities, files, and digests against the lock. |
| `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 status` | Print the latest sync/update receipt as JSON, or report that no receipt exists. |
-| `pm gc` | Remove unreferenced tool-store entries, eligible download partials, and unused lease-managed Python generations. |
+| `pm gc` | Remove unreferenced tool-store entries, eligible download partials, unused lease-managed Python generations, and the `installs/INSTALL_KEY/` state of checkouts that no longer exist (a deleted worktree or clone; skipped while its install lock or a generation lease is still held). The worktree pruner that runs at startup reclaims those orphaned state dirs too. |
`pm env` excludes inherited process variables, including credentials. Its
output can still reveal local installation paths; review it before sharing.