Skip to content

The agent that grows with you

refactor(hermes_cli): compact docstrings/comments in update_cmd*, update_abort_recovery, uninstall (keep every WHY)

Teknium1767ee8119db
diff --git a/hermes_cli/uninstall.py b/hermes_cli/uninstall.py
index faf0ebd7f89..fa14d4bf0d8 100644
--- a/hermes_cli/uninstall.py
+++ b/hermes_cli/uninstall.py
@@ -52,10 +52,8 @@ def _confirm_yes(text: str) -> bool:
def _remove_each(candidates, remove) -> list:
- """Run ``remove(path)`` for each candidate; collect those it reports removed (truthy).
-
- Failures are downgraded to the shared ``Could not remove <path>: <err>`` warning.
- """
+ """Run ``remove(path)`` per candidate, collecting the ones it reports removed; failures become
+ the shared ``Could not remove <path>: <err>`` warning."""
removed = []
for path in candidates:
try:
@@ -75,7 +73,8 @@ _SHELL_RC_NAMES = (".bashrc", ".bash_profile", ".profile", ".zshrc", ".zprofile"
def _strip_hermes_path_lines(content: str) -> str:
- """Drop the ``# Hermes Agent`` marker (+ its PATH line) and any hermes PATH line; squash blank runs."""
+ """Drop the ``# Hermes Agent`` marker (+ its PATH line) and any hermes PATH line; squash blank
+ runs."""
new_lines = []
skip_next = False
for line in content.split('\n'):
@@ -105,13 +104,10 @@ def remove_path_from_shell_configs():
new_content = _strip_hermes_path_lines(content)
if new_content != content:
from utils import atomic_write_text
- # This is the user's own shell rc, not a Hermes-owned file, and nothing here backs
- # it up. A bare write_text() truncates it before the new content lands, so a crash
- # or SIGINT mid-write leaves an empty/truncated ~/.zshrc -- and the enclosing
- # `except Exception` downgrades that to a warning, so the next login just starts a
- # bare shell. atomic_replace also resolves a symlinked rc file (dotfiles repos keep
- # the symlink). preserve_mode keeps the rc's permission bits (normally 0644) and
- # owner (sudo-run uninstalls) instead of mkstemp's 0600/root.
+ # The user's own rc, never backed up: a bare write_text() truncates before the new
+ # content lands, and a crash mid-write (downgraded to a warning below) would leave
+ # an empty ~/.zshrc. Atomic replace also follows a symlinked rc (dotfiles repos);
+ # preserve_mode keeps its 0644 bits and owner (sudo-run uninstalls).
atomic_write_text(config_path, new_content, preserve_mode=True)
removed_from.append(config_path)
except Exception as e:
@@ -148,15 +144,9 @@ def _node_symlink_candidate_dirs() -> "list[Path]":
def remove_node_symlinks(hermes_home: Path) -> list:
- """Remove the node/npm/npx symlinks the installer placed on PATH.
-
- - ``/usr/local/bin/`` on root FHS installs (Linux, uid 0) - ``$PREFIX/bin/`` on Termux -
- ``~/.local/bin/`` otherwise (the common non-root case)
-
- We check all candidate directories so that uninstall works regardless of how the install was
- done (e.g. a root FHS install that placed links in ``/usr/local/bin``, or an older install that
- used ``~/.local/bin`` before the FHS fix).
- """
+ """Remove the node/npm/npx symlinks the installer placed on PATH. Every candidate dir is
+ checked (``/usr/local/bin`` root FHS, ``$PREFIX/bin`` Termux, ``~/.local/bin`` otherwise / older
+ installs) so uninstall works regardless of how the install was done."""
node_dir = (hermes_home / "node").resolve()
def _unlink_ours(link: Path) -> bool:
@@ -176,12 +166,8 @@ def remove_node_symlinks(hermes_home: Path) -> list:
def uninstall_gateway_service():
- """Stop/uninstall the gateway service on every platform and kill standalone gateways.
-
- Delegates to the gateway module: systemd user+system units (Linux), launchd (macOS),
- Scheduled Task + Startup folder (Windows), plus standalone ``hermes gateway run`` processes.
- Termux/Android has no systemd, so only the process kill applies there.
- """
+ """Kill standalone gateways, then remove the per-platform service (systemd user+system /
+ launchd / Scheduled Task + Startup folder). Termux/Android has neither: only the kill applies."""
import platform
stopped_something = False
@@ -249,12 +235,8 @@ def _remove_launchd_gateway() -> bool:
def _remove_windows_gateway() -> bool:
- """Windows: uninstall Scheduled Task + Startup-folder entry.
-
- The gateway_windows module already knows how to locate and remove both code paths (schtasks
- /Delete + .cmd unlink) and how to stop any running detached pythonw gateway process. We call
- into it so the uninstall logic stays in exactly one place.
- """
+ """Windows: uninstall Scheduled Task + Startup-folder entry via ``gateway_windows`` (it owns
+ schtasks /Delete, the .cmd unlink and stopping the detached pythonw gateway)."""
from hermes_cli import gateway_windows
if not any(probe() for probe in (
gateway_windows.is_installed, gateway_windows.is_task_registered, gateway_windows.is_startup_entry_installed,
@@ -290,12 +272,9 @@ _GATEWAY_SERVICE_REMOVERS = {
def _hermes_path_markers(hermes_home: Path, *, include_managed_bin: bool = False) -> list[str]:
- """Path-entry substrings that identify Hermes-owned User-PATH entries.
-
- ``include_managed_bin`` adds the managed binary dir (``<root>\bin``, holding the hermes
- launchers and the managed uv) — only wanted when that dir is about to be deleted (full uninstall
- from the default root), so a keep-data uninstall leaves the still-working managed uv resolvable.
- """
+ """Prefixes identifying Hermes-owned User-PATH entries. ``include_managed_bin`` adds
+ ``<root>\bin`` (launchers + managed uv) — only when that dir is about to be deleted (full
+ uninstall from the default root), so a keep-data uninstall keeps the working uv resolvable."""
root = str(hermes_home).rstrip("\\/")
# Match on prefix so sub-entries (git\cmd, git\bin, git\usr\bin, node, etc.) all get swept.
subs = ("hermes-agent", "git", "node", "venv") + (("bin",) if include_managed_bin else ())
@@ -342,11 +321,9 @@ def remove_hermes_env_vars_windows() -> list[str]:
def _edit_user_environment(edit, *, warn_label: str) -> list[str]:
- """Open HKCU\\Environment read/write and run ``edit(winreg, key, removed)``.
-
- Returns whatever ``edit`` appended to ``removed`` — even when a later registry call raised, so
- callers report exactly what was touched. ``[]`` off-Windows (no ``winreg``).
- """
+ """Open HKCU\\Environment read/write and run ``edit(winreg, key, removed)``. Returns what
+ ``edit`` appended to ``removed`` even if a later registry call raised (callers report exactly
+ what was touched); ``[]`` off-Windows (no ``winreg``)."""
removed: list[str] = []
try:
import winreg
@@ -370,13 +347,10 @@ def remove_portable_tooling_windows(hermes_home: Path) -> list[Path]:
def remove_windows_bin_launchers(*, windows: bool | None = None) -> list[Path]:
- """Delete the ``hermes`` launchers install.ps1 staged in the managed ``bin`` dir.
-
- Every uninstall mode deletes the checkout, so launchers pointing at ``<checkout>/venv``
- would dangle and error, which reads worse than command-not-found; the managed uv is kept for
- keep-data reinstalls. A launcher that is this process's own trampoline is locked against
- deletion but not rename, so it is renamed aside with a non-executable suffix instead.
- """
+ """Delete the ``hermes`` launchers install.ps1 staged in the managed ``bin`` dir: every mode
+ deletes the checkout, so a launcher pointing at ``<checkout>/venv`` would dangle (worse than
+ command-not-found); the managed uv stays for keep-data reinstalls. Our own running trampoline is
+ locked against deletion but not rename, so it is renamed aside with a non-executable suffix."""
if windows is None:
windows = _is_windows()
if not windows:
@@ -431,17 +405,13 @@ def _discover_named_profiles():
def _uninstall_profile(profile) -> None:
- """Fully uninstall a named profile: stop its gateway, remove its alias, wipe its home.
-
- Shells out to ``hermes -p <name> gateway stop|uninstall`` because service names and unit/
- plist paths derive from the current HERMES_HOME and can't easily be switched in-process.
- """
+ """Fully uninstall a named profile: stop its gateway, remove its alias, wipe its home. Shells
+ out to ``hermes -p <name> gateway stop|uninstall`` because service names / unit paths derive
+ from the current HERMES_HOME and can't be switched in-process."""
name = profile.name
log_info(f"Uninstalling profile '{name}'...")
- # 1. Stop and remove this profile's gateway service.
- # Use `python -m hermes_cli.main` so we don't depend on a `hermes`
- # wrapper that may be half-removed mid-uninstall.
+ # 1. Gateway service, via `python -m hermes_cli.main` (the `hermes` wrapper may be half-gone).
hermes_invocation = [sys.executable, "-m", "hermes_cli.main", "--profile", name]
for subcmd in ("stop", "uninstall"):
try:
@@ -467,12 +437,8 @@ def _uninstall_profile(profile) -> None:
def run_gui_uninstall(args):
- """GUI-only uninstall: remove the Chat GUI, leave the agent + data intact.
-
- Mirrors ``hermes uninstall --gui``. Removes the desktop app's built artifacts, the packaged app
- bundle (best-effort), and the Electron userData dir — nothing under ``$HERMES_HOME``
- config/sessions/.env, and never the Python agent or its venv.
- """
+ """``hermes uninstall --gui``: remove the desktop app's built artifacts, packaged bundle
+ (best-effort) and Electron userData — never config/sessions/.env, the agent or its venv."""
from hermes_cli.gui_uninstall import (
agent_is_installed, gui_install_summary, uninstall_gui)
@@ -520,11 +486,8 @@ def run_gui_uninstall(args):
def run_uninstall(args):
- """Run the uninstall process.
-
- Full uninstall removes code and ``~/.hermes/``; keep-data removes only the code so the
- configs, data and logs survive a reinstall.
- """
+ """Interactive/``--yes`` uninstall: full removes code and ``~/.hermes/``; keep-data removes only
+ the code so configs, data and logs survive a reinstall."""
project_root = get_project_root()
hermes_home = get_hermes_home()
@@ -534,18 +497,13 @@ def run_uninstall(args):
project_root=project_root, hermes_home=hermes_home, full_uninstall=full_flag)
return
- # Detect named profiles when uninstalling from the default root —
- # offer to clean them up too instead of leaving zombie HERMES_HOMEs
- # and systemd units behind.
+ # Named profiles (only when uninstalling from the default root) are offered for cleanup too,
+ # instead of leaving zombie HERMES_HOMEs and systemd units behind.
is_default_profile = _is_default_hermes_home(hermes_home)
named_profiles = _discover_named_profiles() if is_default_profile else []
- # Non-interactive fast path (``--yes``): no prompts. ``--full`` selects a
- # full wipe (code + ~/.hermes data); otherwise keep-data. Named profiles
- # are NOT auto-removed here — that's a destructive, surprising default for
- # an unattended run, so it stays opt-in to the interactive flow. This is
- # the path the desktop app's detached cleanup script uses for its
- # lite/full modes.
+ # ``--yes`` (the desktop app's detached cleanup script): no prompts; ``--full`` = full wipe.
+ # Named profiles are NOT auto-removed here — too destructive a default for an unattended run.
if bool(getattr(args, "yes", False)):
_perform_uninstall(
project_root=project_root, hermes_home=hermes_home, full_uninstall=full_flag,
@@ -592,10 +550,8 @@ def run_uninstall(args):
full_uninstall = (choice == "2")
- # When doing a full uninstall from the default profile, also offer to
- # remove any named profiles — stopping their gateway services, unlinking
- # their alias wrappers, and wiping their HERMES_HOME dirs. Otherwise
- # those leave zombie services and data behind.
+ # Full uninstall from the default profile: offer to remove named profiles too (gateway
+ # services, alias wrappers, HERMES_HOME dirs) — otherwise they leave zombie services behind.
remove_profiles = False
n_profiles = len(named_profiles)
profile_names = ", ".join(p.name for p in named_profiles)
@@ -652,7 +608,8 @@ def _print_uninstall_dry_run(*, project_root: Path, hermes_home: Path, full_unin
def _remove_step(label: str, remove, success_fmt: str, none_msg: str) -> None:
- """Announce ``label``, run ``remove()``, then log one success line per removed item (or ``none_msg``)."""
+ """Announce ``label``, run ``remove()``, then log one success line per removed item (or
+ ``none_msg``)."""
log_info(label)
removed = remove()
for item in removed:
@@ -680,12 +637,9 @@ def _perform_uninstall(
full_uninstall: bool,
remove_profiles: bool,
named_profiles: list) -> None:
- """Execute the uninstall steps; shared by the interactive and ``--yes`` paths.
-
- Order: stop gateway -> strip PATH (rc files + Windows registry) -> remove wrapper and node
- symlinks -> remove desktop Chat GUI artifacts -> delete the checkout -> (Windows) remove
- PortableGit/Node -> optionally wipe ``$HERMES_HOME`` and named profiles.
- """
+ """The uninstall steps shared by the interactive and ``--yes`` paths: stop gateway -> strip PATH
+ (rc files + Windows registry) -> wrapper/launchers/node symlinks -> Chat GUI artifacts -> delete
+ the checkout -> (Windows) PortableGit/Node -> optionally ``$HERMES_HOME`` and named profiles."""
print()
print(color("Uninstalling...", Colors.CYAN, Colors.BOLD))
print()
@@ -695,15 +649,12 @@ def _perform_uninstall(
if not uninstall_gateway_service():
log_info("No gateway service or processes found")
- # 2-3b. PATH entries (POSIX rc files, then the Windows User-scope registry), wrapper script,
- # Windows launchers, node/npm/npx symlinks. Windows notes: hermes_home is %VAR%-expanded so
- # marker matching runs against fully resolved paths (install.ps1 writes literal
- # C:\Users\<u>\AppData\Local\hermes\git\cmd, not %LOCALAPPDATA%); the managed binary dir
- # (hermes\bin: launchers + managed uv) leaves the PATH only when the full wipe below is
- # about to delete it, so keep-data mode keeps the still-working uv resolvable; the launchers
- # themselves always go — both modes delete the checkout, so a surviving launcher would
- # dangle and error, worse than command-not-found. Symlinks are removed only when they still
- # point into this Hermes home's node dir (never clobber nvm / user-managed Node).
+ # 2-3b. PATH entries (rc files, then the Windows User registry), wrapper, Windows launchers,
+ # node symlinks. Windows: hermes_home is %VAR%-expanded because install.ps1 writes literal
+ # C:\Users\<u>\AppData\Local\hermes\git\cmd; hermes\bin (launchers + managed uv) leaves the
+ # PATH only when the full wipe below deletes it (keep-data keeps uv resolvable), while the
+ # launchers themselves always go (see remove_windows_bin_launchers). Symlinks go only when
+ # they still point into this home's node dir (never clobber nvm / user-managed Node).
windows = _is_windows()
sweep_managed_bin = windows and full_uninstall and _is_default_hermes_home(hermes_home)
for on_this_platform, label, remove, success_fmt, none_msg in (
@@ -724,11 +675,9 @@ def _perform_uninstall(
if on_this_platform:
_remove_step(label, remove, success_fmt, none_msg)
- # 3c. Desktop Chat GUI artifacts (built renderer/release, node_modules, packaged app bundle,
- # Electron userData). Both CLI flows remove the agent code, so the GUI — just another
- # consumer of the same checkout — goes with it. uninstall_gui() never touches config /
- # sessions / .env, so it's safe in keep-data mode; the packaged app + Electron userData
- # live OUTSIDE HERMES_HOME, so the full-uninstall rmtree below would not reach them.
+ # 3c. Desktop Chat GUI artifacts: both flows remove the agent code, so the GUI goes with it.
+ # uninstall_gui() never touches config/sessions/.env (safe in keep-data mode); the packaged
+ # app + Electron userData live OUTSIDE HERMES_HOME, so the rmtree below wouldn't reach them.
log_info("Removing desktop Chat GUI artifacts...")
try:
from hermes_cli.gui_uninstall import uninstall_gui
@@ -741,8 +690,8 @@ def _perform_uninstall(
log_info("Removing installation directory...")
_rmtree_step(project_root)
- # 4b. Windows-only installer artifacts that are NOT user data (PortableGit, bundled Node,
- # gateway-service dir): install tooling under HERMES_HOME, safe to remove in keep-data mode.
+ # 4b. Windows installer tooling under HERMES_HOME (PortableGit, Node, gateway-service) is not
+ # user data: safe to remove in keep-data mode too.
if windows:
_remove_step(
"Removing Windows installer artifacts (PortableGit, Node, gateway-service)...",
@@ -751,9 +700,8 @@ def _perform_uninstall(
# 5. Optionally remove ~/.hermes/ data directory (and named profiles)
if full_uninstall:
- # 5a. Stop and remove each named profile's gateway service and alias wrapper. The profile
- # HERMES_HOME dirs live under ``<default>/profiles/<name>/`` and are swept by the rmtree
- # below, but services + alias scripts live OUTSIDE the default root.
+ # 5a. Named profiles' homes live under <default>/profiles/ (swept by the rmtree below),
+ # but their services + alias scripts live OUTSIDE the default root.
if remove_profiles:
for prof in named_profiles:
_uninstall_profile(prof)
@@ -804,12 +752,9 @@ class _UninstallArgs:
def main(argv=None) -> int:
- """Module entrypoint: ``python -m hermes_cli.uninstall --mode <gui|lite|full>``.
-
- This module imports only stdlib + ``hermes_constants`` + ``hermes_cli.colors`` (and lazily
- ``hermes_cli.gui_uninstall``), so it runs fine under a bare system Python with no site-packages
- from the venv.
- """
+ """``python -m hermes_cli.uninstall --mode <gui|lite|full>``. Imports only stdlib +
+ ``hermes_constants`` + ``hermes_cli.colors`` (lazily ``gui_uninstall``), so it runs under a
+ bare system Python without the venv."""
import argparse
parser = argparse.ArgumentParser(prog="python -m hermes_cli.uninstall")
parser.add_argument(
diff --git a/hermes_cli/update_abort_recovery.py b/hermes_cli/update_abort_recovery.py
index cf035495384..1990148b657 100644
--- a/hermes_cli/update_abort_recovery.py
+++ b/hermes_cli/update_abort_recovery.py
@@ -1,11 +1,7 @@
-"""Fresh-process recovery after the update's in-process restart phase aborts.
-
-``hermes update`` performs its fleet restart in the interpreter that started before ``git pull``.
-
-It is deliberately a separate owner from ``update_cmd``: the abort path has its own vocabulary
-(``verified`` / ``relaunch_attempted`` / ``failed``, serve units, survivors) and its own fail-closed
-contract, and the update monolith must not grow another authority surface (review on #96235).
-"""
+"""Fresh-process recovery after the update's in-process restart phase aborts (the fleet restart
+runs in the interpreter that started before ``git pull``). Deliberately a separate owner from
+``update_cmd``: its own vocabulary (``verified`` / ``relaunch_attempted`` / ``failed``, serve units,
+survivors) and its own fail-closed contract."""
from __future__ import annotations
@@ -25,17 +21,11 @@ def _serve_unit_recovery_available() -> bool:
def _surviving_pre_update_serve_runtimes(plan) -> list[dict]:
- """Pre-update serve/dashboard runtimes that are STILL the same process.
-
- Identity is the process incarnation ``(pid, create_time)``, never the PID alone.
- ``ledger_entries()`` re-verifies that pair on every read and prunes anything that is gone, so a
- live entry is a real process — but the numeric PID can be reused, and a serve that was restarted
- correctly can come back on the same number.
-
- Anything still here after the recovery pass is a live runtime on the pre-update code generation,
- which is precisely the unsafe state #92145 reports. Fail closed on missing evidence: an
- unreadable ledger, or an incarnation neither side can produce, counts the runtime as surviving.
- """
+ """Pre-update serve/dashboard runtimes that are STILL the same process — i.e. live on the
+ pre-update code generation. Identity is the incarnation ``(pid, create_time)``, never the PID
+ alone: ``ledger_entries()`` prunes dead entries, but a correctly restarted serve can come back
+ on the same number. Fail closed on missing evidence (unreadable ledger, no incarnation on either
+ side): the runtime counts as surviving."""
planned: dict[int, dict] = {}
try:
for runtime in getattr(plan, "runtimes", ()) or ():
@@ -93,11 +83,8 @@ def _without_incarnation(row: dict) -> dict:
def _qualified_serve_skips(skip_units) -> list[dict]:
- """Scope-qualify the units the aborted phase already settled.
-
- ``restarted_scoped_units`` records ``<scope>/<unit>`` because ``hermes-serve.service`` can exist
- in BOTH the user and the system manager, and those are two different processes.
- """
+ """Scope-qualify the units the aborted phase already settled: ``<scope>/<unit>`` because
+ ``hermes-serve.service`` can exist in BOTH the user and system manager (two processes)."""
rows: list[dict] = []
for entry in sorted(skip_units or ()):
scope, sep, unit = str(entry).partition("/")
@@ -114,13 +101,8 @@ def _recover_gateway_restart_after_abort(
gateway_mode: bool,
skip_profiles: set[str] | None = None,
skip_units: set[str] | None = None) -> dict[str, list]:
- """Retry supervised gateway restarts from a clean Python process.
-
- ``hermes update`` normally performs the fleet restart in the interpreter that started before
- ``git pull``.
-
- Only profiles classified as supervisor-owned by the pre-update inventory are handed off.
- """
+ """Retry supervised gateway restarts from a clean Python process (the in-process restart ran
+ in the pre-``git pull`` interpreter). Only inventory-classified supervisor-owned profiles."""
from hermes_cli.update_cmd import _gateway_recovery_partition
candidates, skipped = _gateway_recovery_partition(plan, skip_profiles=skip_profiles)
profiles = sorted(candidates)
@@ -148,11 +130,9 @@ def _recover_gateway_restart_after_abort(
for marker in ("_HERMES_GATEWAY", "HERMES_GATEWAY", "HERMES_GATEWAY_MODE"):
env.pop(marker, None)
- # A gateway-triggered update may run inside the gateway's systemd cgroup.
- # Put the recovery process in a transient user scope before it asks systemd
- # to restart that gateway, otherwise KillMode can terminate the recovery
- # process together with the old service. If systemd-run is unavailable,
- # fail closed rather than pretending the in-cgroup child is independent.
+ # A gateway-triggered update may run inside the gateway's systemd cgroup: put the recovery in a
+ # transient user scope or KillMode terminates it with the old service. No systemd-run -> fail
+ # closed rather than pretend the in-cgroup child is independent.
if gateway_mode and sys.platform == "linux":
systemd_run = shutil.which("systemd-run")
if not systemd_run:
@@ -173,9 +153,8 @@ def _recover_gateway_restart_after_abort(
"errors": "replace",
"check": False,
"env": env,
- # Gateway profiles run sequentially at up to 90s each; the serve pass
- # adds its own restart + settle budget on top, so give the child room
- # for both rather than killing a recovery that was working.
+ # Gateway profiles run sequentially at up to 90s each, plus the serve pass's own
+ # restart + settle budget — don't kill a recovery that was working.
"timeout": max(180, 30 + 90 * len(profiles) + (150 if recover_serve else 0))}
if sys.platform == "win32":
kwargs["creationflags"] = (
@@ -214,8 +193,7 @@ def _recover_gateway_restart_after_abort(
serve_units = {
"verified": sorted(raw_serve["verified"]), "failed": sorted(raw_serve["failed"])}
elif recover_serve:
- # An unreadable serve block cannot be read as "nothing to do": the
- # units it describes are exactly the ones that host tui_gateway and
+ # An unreadable serve block is not "nothing to do": those units host tui_gateway and
# may still be serving the pre-update generation.
logger.warning("Fresh recovery returned an invalid serve-unit result")
serve_units = {"verified": [], "failed": ["<unreadable>"]}
@@ -245,13 +223,10 @@ def _recover_gateway_restart_after_abort(
def _warn_stale_serve_runtimes(rows) -> None:
- """Name the serve/dashboard processes that survived on pre-update code.
-
- ``hermes serve`` hosts ``tui_gateway.server``; if its unit was never restarted it keeps the
- pre-pull ``sys.modules`` graph, every chat turn fails with an ``ImportError`` for a symbol
- that imports fine on disk, and no gateway row reveals the culprit. Print the PIDs and the
- exact command that fixes it.
- """
+ """Name the serve/dashboard processes still on pre-update code: ``hermes serve`` hosts
+ ``tui_gateway.server``, and an un-restarted unit keeps the pre-pull ``sys.modules`` graph so
+ every chat turn fails with an ``ImportError`` no gateway row explains. Print PIDs + the fixing
+ command."""
if not rows:
return
print(
@@ -271,13 +246,9 @@ def _warn_stale_serve_runtimes(rows) -> None:
def _abort_recovery_is_complete(
*, planned_gateway_profiles, covered_gateway_profiles, recovery_result, stale_runtime_rows
) -> bool:
- """May a fresh-process recovery clear the incomplete flag?
-
- Only when EVERY inventoried runtime family is accounted for.
-
- ``planned_gateway_profiles`` being empty is deliberately NOT completeness: with no gateway leg
- to prove, the caller's own fail-closed contract (``_restart_phase_failure_is_incomplete``) plus
- the stale-runtime rows decide the outcome.
+ """May a fresh-process recovery clear the incomplete flag? Only when EVERY inventoried runtime
+ family is accounted for. Empty ``planned_gateway_profiles`` is deliberately NOT completeness:
+ with no gateway leg to prove, ``_restart_phase_failure_is_incomplete`` + the stale rows decide.
"""
if not planned_gateway_profiles:
return False
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 17bde3c9981..d61d12d1999 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -1,10 +1,9 @@
"""Hermes update pipeline: dispatchers (``_cmd_update_impl``/``_cmd_update_check``) + git plumbing.
Each concern lives in ``update_cmd_<concern>.py`` and is re-imported here so
-``hermes_cli.update_cmd.<name>`` keeps resolving (and stays monkeypatchable).
-``_m()`` is the lazy ``hermes_cli.main`` handle kept for main-side test patches.
-Imports are one-way: main -> update_cmd -> update_cmd_* (never the reverse at
-import time; ``_m()`` resolves at call time, so no cycle).
+``hermes_cli.update_cmd.<name>`` keeps resolving (and stays monkeypatchable). Imports are
+one-way: main -> update_cmd -> update_cmd_*; ``_m()`` resolves ``hermes_cli.main`` at call
+time (no cycle, main-side test patches stay effective).
"""
import logging
@@ -18,18 +17,15 @@ import time as _time
from dataclasses import dataclass
from pathlib import Path
-# Re-exported: update_cmd_* modules import lazily from here so patches stick.
-from hermes_cli.config import get_hermes_home # noqa: F401
+from hermes_cli.config import get_hermes_home # noqa: F401 (re-exported; patched via update_cmd)
from hermes_cli.update_cmd_common import _best_effort
from hermes_constants import get_default_hermes_root, venv_python_path
-# Re-exported: main and the split modules address these via update_cmd (tests patch here).
+# Re-exports: every split-module name stays reachable (and monkeypatchable) as update_cmd.<name>.
from hermes_cli.update_abort_recovery import ( # noqa: F401
_abort_recovery_is_complete, _qualified_serve_skips, _recover_gateway_restart_after_abort,
_serve_unit_recovery_available, _surviving_pre_update_serve_runtimes,
_warn_stale_serve_runtimes)
-# Re-exports from the split modules: every moved name stays reachable (and monkeypatchable)
-# as ``hermes_cli.update_cmd.<name>``; the split modules import origin-internal names lazily.
from hermes_cli.update_cmd_windows import ( # noqa: F401
_HOLDER_VALUE_FLAGS_FALLBACK, _clear_windows_venv_holders_or_exit,
_cold_start_windows_gateway_after_update, _desktop_owns_gateway_lifecycle,
@@ -131,17 +127,17 @@ def _updates_config() -> dict:
def _no_prompt_git_kwargs() -> dict:
- """``subprocess.run`` kwargs for network git calls: GitHub answers anonymous fetches with
- 401 during outages and git would then block forever on ``Username for ...``; disable only
- the *prompt* (credential helpers/askpass still run) so it fails fast into ``_classify_fetch_failure``."""
+ """``subprocess.run`` kwargs for network git: GitHub answers anonymous fetches with 401 during
+ outages and git would block forever on ``Username for ...``; disable only the *prompt*
+ (credential helpers/askpass still run) so it fails fast into ``_classify_fetch_failure``."""
env = dict(os.environ)
env["GIT_TERMINAL_PROMPT"] = "0"
env["GCM_INTERACTIVE"] = "Never"
return {"stdin": subprocess.DEVNULL, "env": env}
-# CLI-startup imports (+ web_server.py, the desktop backend a fresh Windows install
-# launches) that must parse post-update; the syntax guard auto-rolls-back on failure.
+# CLI-startup files (+ web_server.py, launched by a fresh Windows Desktop install) that must
+# parse post-update; the syntax guard rolls back when one doesn't.
_UPDATE_CRITICAL_FILES = (
"hermes_cli/main.py", "hermes_cli/config.py", "hermes_cli/__init__.py",
"hermes_cli/web_server.py", "cli.py", "run_agent.py", "model_tools.py", "toolsets.py",
@@ -195,12 +191,9 @@ def _validate_python_files_syntax(
def _validate_critical_files_syntax(root) -> tuple[bool, str | None, str | None]:
- """Compile ``_UPDATE_CRITICAL_FILES`` -> ``(ok, failing_path, error_message)``.
-
- A syntax error there means the CLI can't bootstrap, so validate post-pull and
- auto-roll-back. The .pyc goes to a temp dir, not ``__pycache__/``: avoids racing
- concurrent test workers and leaving a stale pyc for a different interpreter.
- """
+ """Compile ``_UPDATE_CRITICAL_FILES`` -> ``(ok, failing_path, error_message)``. The .pyc goes
+ to a temp dir, not ``__pycache__/`` (no race with test workers, no stale pyc for another
+ interpreter)."""
return _validate_python_files_syntax(root, _UPDATE_CRITICAL_FILES)
@@ -401,12 +394,9 @@ def _format_concurrent_instances_message(
def _classify_concurrent_instance(pid: int) -> str:
- """Classify ``pid`` as "gateway" / "non-gateway" / "unknown" (psutil can't read it).
-
- Uses ``_is_pausable_gateway``, the same matcher as the Desktop preflight exemption and
- venv-holder guard, so "gateway" is exactly the set the downstream pause/restart machinery
- stops. The gate treats "unknown" as non-gateway (better block than proceed blind).
- """
+ """Classify ``pid`` as "gateway" / "non-gateway" / "unknown" (psutil can't read it). Uses
+ ``_is_pausable_gateway`` (same matcher as the Desktop preflight and venv-holder guard) so
+ "gateway" is exactly what the pause/restart machinery stops; "unknown" gates as non-gateway."""
try:
import psutil # noqa: PLC0415
except Exception:
@@ -424,8 +414,8 @@ def _classify_concurrent_instance(pid: int) -> str:
def _filter_non_gateway_concurrent_instances(
matches: list[tuple[int, str]]) -> list[tuple[int, str]]:
- """Drop gateway matches (the pause + post-update restart machinery handles them);
- anything else (TUI, Desktop backend child, another REPL) has no pause path, so the gate aborts."""
+ """Drop gateway matches (the pause + post-update restart machinery handles them); anything else
+ (TUI, Desktop backend child, another REPL) has no pause path, so the gate aborts."""
return [(pid, name) for pid, name in matches if _classify_concurrent_instance(pid) != "gateway"]
@@ -651,8 +641,8 @@ def _repair_current_checkout(
def _reconcile_diverged_checkout(git_cmd, branch: str, pre_pull_sha) -> None:
- """Fast-forward failed: merge on a custom branch (local commits survive) or reset --hard on
- the same branch (rescue ref first when histories share no ancestor). ``sys.exit(1)`` on failure."""
+ """Fast-forward failed: merge on a custom branch (local commits survive) or reset --hard on the
+ same branch (rescue ref first when histories share no ancestor). ``sys.exit(1)`` on failure."""
# Diverged. A custom branch (local commits atop origin/<branch>) also can't ff,
# and reset --hard would discard that work: merge instead, stop on conflict.
_cur_branch = (_git_run(git_cmd, ["branch", "--show-current"]).stdout or "").strip()
@@ -807,19 +797,16 @@ class _CheckoutPlan:
def _apply_parked_branch_guard(
git_cmd, branch, current_branch, *, switch_branch, _windows_gateway_resume
) -> tuple[bool, bool, "str | None"]:
- """Decide how a checkout parked on another branch is brought to *branch*.
-
- Returns ``(parked_branch_switched, in_place_update, switch_block_reason)``; ``sys.exit(1)``
- when the branch is dirty/unverifiable (code update SKIPPED) or the target is missing.
+ """Decide how a checkout parked on another branch is brought to *branch* (stash-switch-pull-
+ switch-back used to "update" main while the running code stayed behind).
+
+ By branch contents + updates.parked_branch_strategy: fully merged -> switch back;
+ unmerged -> "switch" (default; loud "kept" notice) or "update_in_place" (merge origin/<target>
+ INTO the branch, checkout never moves; --switch-branch overrides once); dirty/unverifiable ->
+ touch nothing, warn, ``sys.exit(1)`` with the code update SKIPPED (also when the target is
+ missing). Returns ``(parked_branch_switched, in_place_update, switch_block_reason)``.
"""
switch_block_reason = None # only meaningful when parked_branch_switched
- # Parked-branch guard (stash-switch-pull-switch-back used to "update" main while the
- # running code stayed behind). By branch contents + updates.parked_branch_strategy:
- # fully merged -> switch back to the target.
- # unmerged: N -> "switch" (default): switch anyway with a loud "kept" notice;
- # "update_in_place": merge origin/<target> INTO the branch (checkout
- # never moves). --switch-branch overrides for one run.
- # anything else -> dirty/unverifiable/opted out: touch nothing, warn, mark SKIPPED, stop.
parked_branch_switched = False
in_place_update = False
if current_branch != branch and current_branch != "HEAD":
@@ -1228,10 +1215,9 @@ def _cmd_update_impl(args, gateway_mode: bool):
if _m()._is_windows() and not getattr(args, "force_venv", False):
_clear_windows_venv_holders_or_exit(args, gateway_mode, _windows_gateway_resume)
- # Self-lock deferral (this process IS the venv python and can't rewrite its own mapped
- # .pyd) deliberately does NOT run here: pre-fetch it stranded users on the OLD checkout
- # and eager cryptography imports made every Windows update an exit-2 loop. It runs via
- # _abort_dependency_sync_if_self_locked() right before the dependency sync instead.
+ # Self-lock deferral deliberately does NOT run here (pre-fetch it stranded users on the OLD
+ # checkout and made every Windows update an exit-2 loop); it runs right before the
+ # dependency sync via _abort_dependency_sync_if_self_locked().
# After every fail-closed venv guard, before either path can remove the release tree.
desktop_dir = _m().PROJECT_ROOT / "apps" / "desktop"
diff --git a/hermes_cli/update_cmd_config.py b/hermes_cli/update_cmd_config.py
index cead271daec..0ca4d06206d 100644
--- a/hermes_cli/update_cmd_config.py
+++ b/hermes_cli/update_cmd_config.py
@@ -1,8 +1,6 @@
"""Post-``hermes update`` config-schema migration for the active profile and every sibling.
-
-Split out of ``update_cmd.py``; names are re-imported there so ``hermes_cli.update_cmd.<name>``
-still resolves/monkeypatches. Origin helpers are imported lazily per function (no cycle; patches hold).
-"""
+Names are re-imported by ``update_cmd`` (``hermes_cli.update_cmd.<name>`` resolves/monkeypatches);
+origin helpers are imported lazily."""
import logging
import sys
@@ -15,14 +13,10 @@ logger = logging.getLogger("hermes_cli.update_cmd")
def _reload_config_modules() -> None:
- """Force-reload modules from disk after git pull.
-
- ``hermes update`` runs in the PRE-pull process, so cached ``config_defaults`` /
- ``config`` / ``config_migrations`` hold OLD code and ``check_config_version()``
- reports "up to date" despite a newer pulled version with a migration to run.
- Also reloads ``_subprocess_compat`` / ``dashboard_procs`` so the later dashboard
- cleanup sees symbols the update added instead of dying with ImportError.
- """
+ """Force-reload config modules after git pull: the updater is the PRE-pull process, so the
+ cached modules hold OLD code and ``check_config_version()`` would report "up to date" despite a
+ pulled migration. ``_subprocess_compat`` / ``dashboard_procs`` reload too so the later dashboard
+ cleanup sees symbols the update added."""
import importlib
importlib.invalidate_caches()
for mod_name in (
@@ -40,7 +34,8 @@ def _reload_config_modules() -> None:
def _run_config_check_fresh() -> tuple:
- """Return ``(current_ver, latest_ver)`` using freshly-reloaded modules (see ``_reload_config_modules``)."""
+ """Return ``(current_ver, latest_ver)`` using freshly-reloaded modules (see
+ ``_reload_config_modules``)."""
from hermes_cli.update_cmd import _reload_config_modules
_reload_config_modules()
from hermes_cli.config import check_config_version
@@ -48,7 +43,8 @@ def _run_config_check_fresh() -> tuple:
def _run_migrate_config_fresh(*, interactive: bool = False, quiet: bool = False) -> dict:
- """Run config migration using freshly-reloaded modules (see ``_reload_config_modules``); returns results dict."""
+ """Run config migration using freshly-reloaded modules (see ``_reload_config_modules``); returns
+ results dict."""
from hermes_cli.update_cmd import _reload_config_modules
_reload_config_modules()
from hermes_cli.config import migrate_config
@@ -57,15 +53,11 @@ def _run_migrate_config_fresh(*, interactive: bool = False, quiet: bool = False)
def _migrate_sibling_profile_configs() -> list[tuple[str, int, int]]:
"""Migrate every SIBLING profile's config.yaml (the shared checkout serves all profiles;
- migrating only the active one left siblings on configs the new code couldn't read).
-
- Per sibling home (active one skipped — caller already did it): scope reads/writes via the
- context-local HERMES_HOME override (thread-safe — never ``os.environ``) and run the
- NON-INTERACTIVE quiet migration; prompt-requiring settings wait for that profile's own
- interactive session. Returns ``[(profile_name, from_version, to_version), ...]`` for
- profiles actually migrated. Never raises; a failing profile is skipped (its startup
- migration remains the fallback).
- """
+ siblings were left on configs the new code couldn't read). Per sibling (active skipped): scope
+ via the context-local HERMES_HOME override (never ``os.environ``) and run the NON-INTERACTIVE
+ quiet migration — prompt-requiring settings wait for that profile's own session. Returns
+ ``[(name, from_version, to_version), ...]``; never raises (a failing profile falls back to its
+ startup migration)."""
from hermes_cli.update_cmd import _run_config_check_fresh, _run_migrate_config_fresh
migrated: list[tuple[str, int, int]] = []
with _best_effort('Sibling profile enumeration failed: %s'):
@@ -165,12 +157,9 @@ def _check_and_apply_config_migration(
assume_yes: bool = False,
gateway_mode: bool = False,
pre_update_snapshot_id: str | None = None) -> None:
- """Check/apply config migrations on an update completion path.
-
- Must use freshly-reloaded modules (see ``_reload_config_modules``) and run on EVERY
- completion path (post-pull, venv-repair retry, Node-deps repair on ``commit_count == 0``)
- so an interrupted update that already pulled code doesn't strand an old config version.
- """
+ """Check/apply config migrations with freshly-reloaded modules. Runs on EVERY completion path
+ (post-pull, venv-repair, Node-deps repair on ``commit_count == 0``) so an interrupted update
+ that already pulled code doesn't strand an old config version."""
from hermes_cli.update_cmd import (
_gateway_prompt,
_migrate_sibling_profile_configs,
diff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.py
index 6f1b82e0b44..9510dd7366c 100644
--- a/hermes_cli/update_cmd_deps.py
+++ b/hermes_cli/update_cmd_deps.py
@@ -1,8 +1,6 @@
-"""Post-``hermes update`` dependency sync: venv preflight, editable reinstall, lazy refresh, npm/Desktop rebuilds, self-lock deferral.
-
-Split out of ``update_cmd.py``; names are re-imported there so ``hermes_cli.update_cmd.<name>``
-still resolves/monkeypatches. Origin helpers are imported lazily per function (no cycle; patches hold).
-"""
+"""Post-``hermes update`` dependency sync: venv preflight, editable reinstall, lazy refresh,
+npm/Desktop rebuilds, self-lock deferral. Names are re-imported by ``update_cmd`` (so
+``hermes_cli.update_cmd.<name>`` resolves/monkeypatches); origin helpers are imported lazily."""
import logging
from contextlib import suppress
@@ -26,11 +24,10 @@ _INSTALL_DEFINING_FILES = "pyproject.toml", "setup.py", "setup.cfg", "MANIFEST.i
def _editable_install_is_current(git_cmd, cwd, pre_pull_sha: str | None) -> bool:
"""True when the pulled commits cannot have invalidated the editable install.
- ``uv pip install -e .`` always rewrites console-script shims; on Windows that rewrite is
- why ``hermes.exe`` must be quarantined (lost race = ``os error 32``), so skip it when it
- provably changes nothing. Safe because the editable finder uses a *static* module list:
- only a new top-level module/package (needing a ``pyproject.toml`` diff, like deps and
- scripts) can stale it. Fails closed: unresolvable pre-pull SHA or failed diff -> False.
+ ``uv pip install -e .`` always rewrites console-script shims (on Windows that is why
+ ``hermes.exe`` must be quarantined; lost race = ``os error 32``), so skip it when it provably
+ changes nothing. Safe because the editable finder uses a *static* module list: only a
+ ``pyproject.toml`` diff can stale it. Fails closed: no pre-pull SHA or failed diff -> False.
"""
if not pre_pull_sha:
return False
@@ -56,12 +53,11 @@ def _critical_module_import_failures(
root, *, report_runtime_errors: bool = False) -> dict[str, tuple[str, str]]:
"""Import each ``_UPDATE_CRITICAL_MODULES`` entry in a subprocess; return failures in probe order.
- Syntax validation only *parses*, so a partially-updated tree (reachable via the Windows
- ZIP copy loop) parses yet dies with ``ImportError: cannot import name``. A subprocess
- keeps the half-updated tree's import side effects out of the updater's ``sys.modules``;
- uses the venv interpreter when present since ``hermes update`` may run under another Python.
- Generic import-time exceptions are tolerated by default (may depend on local config);
- ``report_runtime_errors=True`` exposes them so two checkout states can be compared.
+ Syntax validation only *parses*: a partially-updated tree (Windows ZIP copy loop) parses yet
+ dies with ``ImportError: cannot import name``. The subprocess (venv interpreter when present —
+ the updater may run under another Python) keeps its import side effects out of our
+ ``sys.modules``. Generic import-time exceptions are tolerated (may depend on local config)
+ unless ``report_runtime_errors=True``.
"""
from hermes_cli.update_cmd import _UPDATE_CRITICAL_MODULES, _m
from hermes_constants import FIRST_PARTY_MODULE_ROOTS
@@ -214,8 +210,8 @@ def _capture_active_tool_dependencies() -> list[str]:
def _restore_active_tool_dependencies(
dependencies: list[str], install_cmd_prefix: list[str], *, env: dict[str, str] | None = None
) -> None:
- """Restore allowlisted ``hermes tools`` dependencies (from a pre-rebuild probe) into a rebuilt venv.
- Never raises: a failed optional tool must not block the update, but must be reported."""
+ """Restore allowlisted ``hermes tools`` dependencies (from a pre-rebuild probe) into a rebuilt
+ venv. Never raises: a failed optional tool must not block the update, but must be reported."""
from hermes_cli.update_cmd import _m
if not dependencies:
return
@@ -284,13 +280,10 @@ def _refresh_active_lazy_features(
*,
env: dict[str, str] | None = None,
features: list[str] | None = None) -> bool:
- """Refresh previously-activated lazy backends (cold ones untouched) after a code update.
-
- The core install never touches ``lazy_deps`` backends, so a bumped :data:`LAZY_DEPS` pin
- would otherwise leave them stale forever. Returns True when the venv is safe to use
- (refreshed, nothing active, or import repair succeeded); False when a failed lazy install
- left broken core imports repair couldn't fix. Never raises.
- """
+ """Refresh previously-activated lazy backends (cold ones untouched): the core install never
+ touches them, so a bumped :data:`LAZY_DEPS` pin would leave them stale forever. Returns True
+ when the venv is safe (refreshed / nothing active / import repair succeeded), False when a
+ failed lazy install left broken core imports repair couldn't fix. Never raises."""
from hermes_cli.update_cmd import _m
try:
from tools import lazy_deps
@@ -364,12 +357,9 @@ def _refresh_active_lazy_features(
def _refresh_active_memory_provider_dependencies() -> None:
- """Refresh pip deps for the configured external memory provider.
-
- Bridge packages live in each provider's ``plugin.yaml``, not Hermes extras or ``LAZY_DEPS``,
- so the core reinstall can strip/downgrade them; re-run the ACTIVE provider's install after
- core install and lazy refresh so its writes land last. Never raises.
- """
+ """Refresh pip deps for the configured external memory provider: its bridge packages live in
+ ``plugin.yaml`` (not Hermes extras / ``LAZY_DEPS``), so the core reinstall can strip them;
+ re-run the ACTIVE provider's install last so its writes land last. Never raises."""
try:
from hermes_cli.config import load_config
cfg = load_config()
@@ -455,14 +445,10 @@ def _ensure_uv_for_termux(pip_cmd: list[str]) -> str | None:
def _npm_manifest_paths() -> tuple[Path, ...]:
- """Manifests whose changes must defeat the update-skip.
-
- The lockfile alone isn't enough: a package.json can be edited without running npm, and
- `hermes update` is the step expected to sync node_modules. Workspaces come from the root
- `workspaces` globs so a new one can't escape the key; every workspace manifest counts
- (desktop too) because the single lockfile spans the whole graph. Falls back to root
- manifests only if package.json is unreadable.
- """
+ """Manifests whose changes must defeat the update-skip. The lockfile alone isn't enough (a
+ package.json can be edited without running npm); workspaces come from the root ``workspaces``
+ globs so a new one can't escape the key, and every workspace counts (desktop too) because the
+ single lockfile spans the whole graph. Root manifests only if package.json is unreadable."""
from hermes_cli.update_cmd import _m
root_pkg = _m().PROJECT_ROOT / "package.json"
paths = [_m().PROJECT_ROOT / "package-lock.json", root_pkg]
@@ -479,7 +465,8 @@ def _npm_manifest_paths() -> tuple[Path, ...]:
def _npm_manifests_digest() -> str | None:
- """Combined sha256 over lockfile + all workspace package.json; None when lockfile missing (never skip)."""
+ """Combined sha256 over lockfile + all workspace package.json; None when lockfile missing (never
+ skip)."""
from hermes_cli.update_cmd import _m
if not (_m().PROJECT_ROOT / "package-lock.json").exists():
return None
@@ -540,13 +527,9 @@ def _repair_node_deps_on_current_checkout(
pre_update_snapshot_id: str | None = None,
completion_message: str = "✓ Already up to date!",
had_desktop_app_before_update: bool = False) -> bool:
- """Repair Node deps on the ``commit_count == 0`` path.
-
- A current checkout doesn't imply healthy Node deps (a failed npm install says "re-run
- hermes update" but the early return skipped the refresh). ``_update_node_dependencies``
- self-gates on the hash recorded only after a SUCCESSFUL install, so this is a cheap
- no-op when healthy and a real repair otherwise.
- """
+ """Repair Node deps on the ``commit_count == 0`` path: a failed npm install says "re-run hermes
+ update" but the early return used to skip the refresh. ``_update_node_dependencies`` self-gates
+ on the hash recorded only after a SUCCESSFUL install, so this is a cheap no-op when healthy."""
from hermes_cli.update_cmd import (
_check_and_apply_config_migration,
_m,
@@ -653,12 +636,9 @@ def _update_node_dependencies() -> list[str]:
def _venv_core_imports_healthy() -> tuple[bool, str]:
- """Probe the venv (in ITS interpreter — updater may run under another Python) for core imports.
-
- Catches a half-updated venv where the checkout is current but a dependency sync died
- partway; otherwise "Already up to date!" never re-syncs. Returns ``(healthy, detail)``.
- Never raises; unknown states report healthy so a probe failure can't force reinstalls.
- """
+ """Probe the venv (in ITS interpreter — the updater may run under another Python) for core
+ imports, catching a half-updated venv that "Already up to date!" would otherwise never re-sync.
+ Returns ``(healthy, detail)``; never raises, unknown states report healthy."""
from hermes_cli.update_cmd import _m
venv_dir = _m().PROJECT_ROOT / "venv"
venv_python = venv_python_path(venv_dir, windows=_m()._is_windows())
@@ -879,15 +859,12 @@ def _path_uid(path) -> Optional[int]:
def _venv_foreign_owned_paths(venv_root, limit: int = 5) -> list:
- """Bounded scan for venv entries not owned by the current user; returns up to ``limit``
- ``(path_str, uid)`` tuples.
-
- A venv touched by ``sudo pip``/``sudo hermes`` has root-owned files, and a later normal
- update dies mid-mutation with ``venv/bin/hermes`` already deleted — never mutate a venv we
- can't safely mutate. Deliberately BOUNDED (venv root, ``venv/bin``, top-level of first
- site-packages, children of each ``*.dist-info``; ~2000 stats max). POSIX-only: ``[]`` on
- Windows and as root. Swallows per-entry ``OSError``; ``[]`` on any structural surprise —
- must NEVER raise or add noticeable latency.
+ """Up to ``limit`` ``(path_str, uid)`` venv entries not owned by the current user.
+
+ A venv touched by ``sudo pip``/``sudo hermes`` dies mid-update with ``venv/bin/hermes`` already
+ deleted — never mutate a venv we can't safely mutate. Deliberately BOUNDED (venv root,
+ ``venv/bin``, first site-packages top level, ``*.dist-info`` children; ~2000 stats). POSIX-only:
+ ``[]`` on Windows and as root; ``[]`` on any surprise — must NEVER raise or add latency.
"""
from hermes_cli.update_cmd import _path_uid
try: