Skip to content

The agent that grows with you

refactor(update): hand-compact comments/docstrings in split modules (AST-identical); re-export get_hermes_home/shutil; repoint source-inspection tests

Tekniuma59680217fcd
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 971fdec2e32..6053aa7efda 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -26,12 +26,16 @@ loaded, so there is no import cycle).
import logging
import os
import shlex
+import shutil # noqa: F401 (tests patch update_cmd.shutil.*; split modules resolve it here)
import subprocess
import sys
import time as _time
from dataclasses import dataclass
from pathlib import Path
+# Both re-exported: the split update_cmd_* modules import them lazily from
+# here so tests that monkeypatch ``update_cmd.get_hermes_home`` stay effective.
+from hermes_cli.config import get_hermes_home # noqa: F401
from hermes_constants import get_default_hermes_root, venv_python_path
# Abort recovery lives in its own bounded module (review on #96235). Re-exported
diff --git a/hermes_cli/update_cmd_config.py b/hermes_cli/update_cmd_config.py
index 5a7e0a7a419..897464383c7 100644
--- a/hermes_cli/update_cmd_config.py
+++ b/hermes_cli/update_cmd_config.py
@@ -1,9 +1,7 @@
-"""Config-schema migration after ``hermes update``: run the fresh-process config check / migrate for the active profile and every sibling profile.
+"""Post-``hermes update`` config-schema migration for the active profile and every sibling.
-Split out of ``hermes_cli/update_cmd.py``; every moved name is re-imported there, so
-``hermes_cli.update_cmd.<name>`` keeps resolving (and monkeypatching) as before.
-Origin-internal helpers are imported lazily inside each function (no import cycle;
-test patches on ``hermes_cli.update_cmd.<name>`` stay effective).
+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).
"""
import logging
@@ -17,16 +15,11 @@ 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 modules hold OLD
- code: ``DEFAULT_CONFIG["_config_version"]`` is stale and
- ``check_config_version()`` reports "up to date" even when the pulled code
- has a newer version with a migration to run. Reloads
- ``config_defaults`` / ``config`` / ``config_migrations`` from disk.
-
- Also reloads ``_subprocess_compat`` and ``dashboard_procs`` so the later
- dashboard cleanup (``_finish_dashboard_update_cleanup`` →
- ``_scan_dashboard_processes``) sees symbols the update added (e.g.
- ``bounded_probe_run``) instead of dying with ImportError in this process.
+ ``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.
"""
import importlib
@@ -47,11 +40,7 @@ def _reload_config_modules() -> None:
def _run_config_check_fresh() -> tuple:
- """Check config version using freshly-reloaded modules.
-
- See ``_reload_config_modules`` for why this is necessary.
- Returns ``(current_ver, latest_ver)``.
- """
+ """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
@@ -60,11 +49,7 @@ 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`` for why this is necessary.
- Returns the migration 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
@@ -73,23 +58,15 @@ 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 to the current version.
-
- #91277 Phase 2 (fleet-wide config migration; #20438/#54926/#79048): the
- shared checkout serves every profile, but ``hermes update`` historically
- migrated only the active profile's config — siblings drifted versions
- until their gateway hit a config the new code couldn't read.
-
- Per profile home (skipping the active one, already migrated by the
- caller): scope config reads/writes via the context-local HERMES_HOME
- override (thread-safe — never ``os.environ``), check the version, and
- run the NON-INTERACTIVE, quiet migration. Prompt-requiring settings are
- left for the profile's own next interactive session, identical to the
- gateway-mode contract for the active profile.
-
- Returns ``[(profile_name, from_version, to_version), ...]`` for profiles
- actually migrated. Never raises; a failing profile is skipped (its own
- startup migration remains the fallback).
+ """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).
"""
from hermes_cli.update_cmd import _run_config_check_fresh, _run_migrate_config_fresh
migrated: list[tuple[str, int, int]] = []
@@ -141,13 +118,11 @@ def _check_and_apply_config_migration(
gateway_mode: bool = False,
pre_update_snapshot_id: str | None = None,
) -> None:
- """Check and apply configuration migrations on an update completion path (#91360).
+ """Check/apply config migrations on an update completion path.
- Must use freshly-reloaded modules (see ``_reload_config_modules``), and
- must run on EVERY completion path — normal post-pull, venv-repair retry,
- and the Node-deps repair on the ``commit_count == 0`` branch — so an
- interrupted update that already pulled new code doesn't strand the user
- on an older config version.
+ 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.
"""
from hermes_cli.update_cmd import (
_gateway_prompt,
@@ -159,8 +134,7 @@ def _check_and_apply_config_migration(
print()
print("→ Checking configuration for new options...")
- # Reload config modules BEFORE any config reads so get_missing_*,
- # check_config_version, and migrate_config all use the updated code.
+ # Reload BEFORE any config reads so all checks use the updated code.
_reload_config_modules()
from hermes_cli.config import (
@@ -168,9 +142,7 @@ def _check_and_apply_config_migration(
get_missing_config_fields,
)
- # Defensive (#91360): this helper runs on repair/retry completion paths
- # too — a config-check failure must not break an otherwise-successful
- # update. Log, point at the manual command, and return.
+ # A config-check failure must not break an otherwise-successful update.
try:
missing_env = get_missing_env_vars(required_only=True)
missing_config = get_missing_config_fields()
@@ -188,9 +160,8 @@ def _check_and_apply_config_migration(
needs_migration = has_new_options or current_ver < latest_ver
if version_bump_only:
- # Only the format version changed (new defaults merge transparently).
- # Prompting "configure new options now?" would look like a no-op on
- # yes (ScottFive / Tt2021) — apply silently and say what happened.
+ # Only the format version changed (defaults merge transparently); prompting
+ # would look like a no-op on yes — apply silently and say what happened.
print()
print(
f" ℹ Updating config format (v{current_ver} → v{latest_ver})…"
@@ -200,10 +171,8 @@ def _check_and_apply_config_migration(
interactive=False, quiet=True
)
print(" ✓ Config format updated (no new settings to configure)")
- # quiet=True also mutes steps that RESET/REMOVE a setting (e.g. the
- # v33→v34 personality reset, #81946). Re-surface them so an
- # unattended update never silently changes config (#86656). Here
- # missing_config is empty, so config_added holds only mutations.
+ # quiet=True also mutes steps that RESET/REMOVE a setting; re-surface them so an
+ # unattended update never silently changes config (config_added holds only mutations here).
for _note in _mig_results.get("config_added") or []:
print(f" ℹ {_note}")
for _warn in _mig_results.get("warnings") or []:
@@ -213,8 +182,7 @@ def _check_and_apply_config_migration(
print(" Run 'hermes config migrate' to retry.")
elif needs_migration:
print()
- # Show WHAT changed, not just a count, so the user can make an
- # informed yes/no decision (previously the prompt named nothing).
+ # Show WHAT changed, not just a count, for an informed yes/no.
if missing_env:
print(
f" ⚠️ {len(missing_env)} new required setting(s) need configuration"
@@ -251,8 +219,7 @@ def _check_and_apply_config_migration(
except EOFError:
response = "n"
except UnicodeDecodeError:
- # Non-UTF-8 locales / embedded terminals can make input()
- # raise this; uncaught, it crashes the update at this prompt.
+ # Non-UTF-8 locales / embedded terminals can make input() raise this.
print(
" ⚠ Could not read input (encoding issue). Skipping. "
"Run 'hermes config migrate' manually to configure."
@@ -261,9 +228,8 @@ def _check_and_apply_config_migration(
if response in {"", "y", "yes", "auto"}:
print()
- # Gateway mode, --yes and non-interactive contexts can't prompt
- # for API keys; still run the non-interactive pass so new defaults
- # and version bumps land before the restarted gateway validates.
+ # Gateway/--yes/non-interactive can't prompt for API keys; still run the
+ # non-interactive pass so defaults and version bumps land before the gateway restarts.
interactive_migration = not (
gateway_mode or assume_yes or response == "auto"
)
@@ -280,11 +246,8 @@ def _check_and_apply_config_migration(
else:
print(" ✓ Configuration is up to date")
- # Fleet-wide config migration (#91277 Phase 2; #20438/#54926/#79048):
- # the migration above touched only the active profile; siblings drifted
- # (field repro: gateway on new code but config v33 vs v37). Run the same
- # NON-INTERACTIVE migration per sibling home via the context-local
- # HERMES_HOME override (never os.environ — other threads must not see it).
+ # The migration above touched only the active profile; run the same NON-INTERACTIVE
+ # migration per sibling home via the context-local HERMES_HOME override (never os.environ).
try:
_migrated_siblings = _migrate_sibling_profile_configs()
for _name, _from_ver, _to_ver in _migrated_siblings:
@@ -295,9 +258,8 @@ def _check_and_apply_config_migration(
except Exception as exc:
logger.debug("Sibling config migration failed: %s", exc)
- # Safety net: migrations have left cron/jobs.json valid-but-empty
- # (#34600) and the desktop scheduler has overwritten it with a partial
- # set (#52144). Restore from the pre-update snapshot if jobs went missing.
+ # Safety net: migrations/desktop scheduler have emptied or truncated cron/jobs.json;
+ # restore from the pre-update snapshot if jobs went missing.
try:
from hermes_cli.backup import restore_cron_jobs_if_emptied
@@ -313,9 +275,8 @@ def _check_and_apply_config_migration(
# Never let the cron safety net break an otherwise-good update.
logger.debug("Cron jobs auto-restore check failed: %s", exc)
- # #64160: Desktop update/repair cycles have rewritten model.provider /
- # model.default and dropped moa: (settings the gateway and cron consume).
- # Restore only those protected keys from the same pre-update snapshot.
+ # Desktop update/repair cycles have rewritten model.provider/model.default and dropped
+ # moa:; restore only those protected keys from the same pre-update snapshot.
try:
from hermes_cli.backup import restore_config_model_settings_if_rewritten
@@ -333,9 +294,7 @@ def _check_and_apply_config_migration(
# Never let the config safety net break an otherwise-good update.
logger.debug("Config model-settings auto-restore check failed: %s", exc)
- # #66140: run the same cron-jobs safety net for every sibling
- # profile against ITS OWN pre-update snapshot (same-generation by
- # construction — both taken by this run).
+ # Same cron-jobs safety net per sibling profile against ITS OWN pre-update snapshot.
try:
from hermes_cli.backup import restore_cron_jobs_all_profiles
@@ -352,7 +311,7 @@ def _check_and_apply_config_migration(
except Exception as exc:
logger.debug("Sibling cron auto-restore check failed: %s", exc)
- # #64160: same config model-settings safety net for sibling profiles.
+ # Same config model-settings safety net for sibling profiles.
try:
from hermes_cli.backup import restore_config_model_settings_all_profiles
@@ -370,9 +329,8 @@ def _check_and_apply_config_migration(
logger.debug("Sibling config auto-restore check failed: %s", exc)
-# {profile: snapshot_id} from this run's pre-update backup, consumed by the
-# post-update per-profile cron-jobs safety net (#66140). Module-level because
-# snapshot and restore run far apart in _cmd_update_impl.
+# {profile: snapshot_id} from this run's pre-update backup, consumed by the per-profile
+# safety nets. Module-level because snapshot and restore run far apart in _cmd_update_impl.
_LAST_SIBLING_SNAPSHOTS: dict = {}
diff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.py
index d8773aaa4c5..39faf4f1b68 100644
--- a/hermes_cli/update_cmd_deps.py
+++ b/hermes_cli/update_cmd_deps.py
@@ -1,9 +1,7 @@
-"""Dependency sync after ``hermes update``: venv health/ownership preflight, editable reinstall, lazy-feature refresh, npm/Desktop rebuilds, self-lock deferral.
+"""Post-``hermes update`` dependency sync: venv preflight, editable reinstall, lazy refresh, npm/Desktop rebuilds, self-lock deferral.
-Split out of ``hermes_cli/update_cmd.py``; every moved name is re-imported there, so
-``hermes_cli.update_cmd.<name>`` keeps resolving (and monkeypatching) as before.
-Origin-internal helpers are imported lazily inside each function (no import cycle;
-test patches on ``hermes_cli.update_cmd.<name>`` stay effective).
+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).
"""
import logging
@@ -21,8 +19,7 @@ from hermes_constants import venv_python_path
logger = logging.getLogger("hermes_cli.update_cmd")
-# Files that define the editable install. A pull that touches none of them
-# cannot have invalidated it.
+# Files defining the editable install; a pull touching none of them cannot invalidate it.
_INSTALL_DEFINING_FILES = (
"pyproject.toml",
"setup.py",
@@ -35,20 +32,11 @@ _INSTALL_DEFINING_FILES = (
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 .`` reinstalls unconditionally and rewrites the
- console-script shims every time. On Windows that rewrite is the only
- reason the running ``hermes.exe`` must be quarantined, and a lost
- quarantine race is the whole ``os error 32`` family — so skip the
- reinstall when it provably cannot change anything.
-
- Safe because Hermes pins its editable finder to a *static* module list
- (``[tool.setuptools] py-modules`` + ``packages.find.include``): only a
- new top-level module/package can stale it, and that needs a
- ``pyproject.toml`` diff (as do dependencies and ``[project.scripts]``).
- New submodules under an already-mapped package need no reinstall.
-
- Fails closed: an unresolvable pre-pull SHA (shallow checkout, ZIP swap)
- or a failed ``git diff`` returns False and the install runs as before.
+ ``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.
"""
if not pre_pull_sha:
return False
@@ -68,10 +56,8 @@ def _editable_install_is_current(git_cmd, cwd, pre_pull_sha: str | None) -> bool
return not result.stdout.strip()
-# Modules imported on every agent startup. Unlike _UPDATE_CRITICAL_FILES (which
-# is only parsed), these are actually *imported* so that cross-module breakage
-# is caught — a file can be syntactically perfect and still fail to import
-# because a name it pulls from a sibling module no longer exists.
+# Modules imported on every startup. Unlike _UPDATE_CRITICAL_FILES (only parsed) these are
+# *imported*, catching cross-module breakage (a name pulled from a sibling no longer exists).
_UPDATE_CRITICAL_MODULES = (
"hermes_cli.main",
"run_agent",
@@ -83,23 +69,14 @@ _UPDATE_CRITICAL_MODULES = (
def _critical_module_import_failures(
root, *, report_runtime_errors: bool = False
) -> dict[str, tuple[str, str]]:
- """Import each module in ``_UPDATE_CRITICAL_MODULES`` in a subprocess.
-
- ``_validate_critical_files_syntax`` only *parses*, so a partially-updated
- tree (new ``agent/``, old ``tools/``) parses fine yet dies at startup
- with ``ImportError: cannot import name ...``. That skew is reachable on
- the Windows ZIP-update path, whose copy loop replaces top-level entries
- one at a time in ``os.listdir`` order.
-
- Runs in a subprocess (~0.4s) so the half-updated tree's import-time side
- effects don't pollute the updater's ``sys.modules``. Uses the project
- venv's interpreter when present (like ``_venv_core_imports_healthy``):
- ``hermes update`` may be driven by a different Python than the install's.
-
- Returns every failing module in probe order. Generic import-time
- exceptions are tolerated by default (they can depend on local config);
- ``report_runtime_errors=True`` exposes them so a caller can compare two
- states of the same checkout without one failure masking another.
+ """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.
"""
from hermes_cli.update_cmd import _UPDATE_CRITICAL_MODULES, _m
from hermes_constants import FIRST_PARTY_MODULE_ROOTS
@@ -114,10 +91,8 @@ def _critical_module_import_failures(
" try:\n"
" importlib.import_module(name)\n"
" except ModuleNotFoundError as exc:\n"
- # A missing *third-party* module means dependencies aren't installed
- # yet, not a skewed checkout. Only our own packages count as breakage.
- # The root set is injected from hermes_constants so this can't drift
- # from the hint the user is shown (they disagreed once already).
+ # A missing *third-party* module means deps aren't installed, not a skewed checkout;
+ # only our own packages count. Roots come from hermes_constants so the user hint can't drift.
" missing = (getattr(exc, 'name', '') or '').split('.')[0]\n"
" if missing in %r or missing.startswith('hermes_') or %r:\n"
" failures.append((name, type(exc).__name__, str(exc)))\n"
@@ -222,10 +197,7 @@ def _npm_bin_exists(bin_dir: Path, name: str) -> bool:
def _web_build_toolchain_ready(*roots: Path) -> bool:
"""True when ``tsc`` and ``vite`` shims are reachable from any of *roots*.
-
- Callers must pass every root the build would search; checking only one
- reports a healthy tree as broken.
- """
+ Callers must pass every root the build would search, or a healthy tree reads as broken."""
bin_dirs = [
bin_dir
for bin_dir in (root / "node_modules" / ".bin" for root in roots)
@@ -238,12 +210,8 @@ def _web_build_toolchain_ready(*roots: Path) -> bool:
def _web_toolchain_roots(web_dir: Path) -> tuple[Path, ...]:
- """Roots whose ``node_modules/.bin`` can satisfy the web build.
-
- ``npm run build`` prepends ``node_modules/.bin`` for the package and each
- of its ancestors, so shims hoisted to the workspace root and shims nested
- under a package that owns its lockfile (#42973) are equally valid.
- """
+ """Roots whose ``node_modules/.bin`` can satisfy the web build: ``npm run build`` searches the
+ package and each ancestor, so hoisted and package-local shims are equally valid."""
return (web_dir, web_dir.parent)
@@ -271,12 +239,8 @@ def _upgrade_pip_before_lazy_refresh(
*,
env: dict[str, str] | None = None,
) -> None:
- """Upgrade pip before lazy-backend refreshes.
-
- Older pip (e.g. 24.0 on Python 3.11) can fail setuptools-backed source
- builds during lazy installs and leave a partially-written venv (#57828).
- Never raises.
- """
+ """Upgrade pip before lazy refreshes: older pip can fail setuptools source builds and
+ leave a partially-written venv. Never raises."""
from hermes_cli.update_cmd import _m
try:
_m()._run_package_only_install(
@@ -315,13 +279,8 @@ def _restore_active_tool_dependencies(
*,
env: dict[str, str] | None = None,
) -> None:
- """Restore allowlisted ``hermes tools`` dependencies into a rebuilt venv.
-
- The dependency names came from a pre-rebuild import probe and are resolved
- through a static package allowlist. Never raises: a failed optional tool
- must not block the core update, but the user must be told what stayed
- unavailable.
- """
+ """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
@@ -356,8 +315,7 @@ def _restore_active_tool_dependencies(
if probe.returncode == 0:
continue
except (subprocess.SubprocessError, OSError):
- # An indeterminate probe is safer to repair than to treat as
- # proof that a pre-rebuild dependency survived.
+ # Indeterminate probe: safer to repair than assume it survived.
pass
missing.append((name, install_args))
@@ -376,8 +334,7 @@ def _restore_active_tool_dependencies(
)
restored.append(name)
except Exception as exc:
- # Best-effort optional tooling: surface failures without aborting
- # the core update.
+ # Best-effort: surface failures without aborting the update.
failed.append((name, str(exc)))
if restored:
@@ -394,18 +351,12 @@ def _refresh_active_lazy_features(
env: dict[str, str] | None = None,
features: list[str] | None = None,
) -> bool:
- """Refresh lazy-installed backends after a code update.
-
- ``uv pip install -e .[all]`` never touches ``tools/lazy_deps.py`` backends,
- so a bumped :data:`LAZY_DEPS` pin (CVE, transitive fix) would otherwise
- leave already-activated backends stale forever. Reinstalls only the
- features the user previously activated; cold backends stay untouched.
+ """Refresh previously-activated lazy backends (cold ones untouched) after a code update.
- Returns True when the venv is safe to use (refresh succeeded, nothing
- active, or post-failure import repair succeeded); False when a failed
- lazy install left broken core imports that repair could not fix (#57828).
-
- Never raises. A failure here must not block the rest of the 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.
"""
from hermes_cli.update_cmd import _m
try:
@@ -436,8 +387,7 @@ def _refresh_active_lazy_features(
else:
results = lazy_deps.restore_features(active)
except Exception as exc:
- # refresh_active_features is documented as never-raise, but defend
- # the update flow against future regressions.
+ # refresh_active_features is never-raise by contract; defend anyway.
print(f" ⚠ Lazy refresh failed unexpectedly: {exc}")
results = {}
unexpected_failure = True
@@ -452,8 +402,7 @@ def _refresh_active_lazy_features(
if current:
print(f" ✓ {len(current)} already current")
if skipped:
- # Most common reason: security.allow_lazy_installs=false. Show one
- # line so the user knows why; not an error.
+ # Usually security.allow_lazy_installs=false; informational, not an error.
names = ", ".join(f for f, _ in skipped)
reason = skipped[0][1].split(": ", 1)[-1]
print(f" · {len(skipped)} skipped ({reason}): {names}")
@@ -463,7 +412,6 @@ def _refresh_active_lazy_features(
for feature, status in failed:
reason = status.split(": ", 1)[-1]
- # Clip noisy pip stderr to keep update output legible.
if len(reason) > 200:
reason = reason[:200] + "..."
print(f" ⚠ {feature} failed to refresh: {reason}")
@@ -472,9 +420,8 @@ def _refresh_active_lazy_features(
print(" ⚠ Lazy refresh failed; rerun `hermes update` once resolved.")
return False
- # Immediate import-based recovery — metadata-only verifiers miss the case
- # where DISTRIBUTION-INFO remains but import files were wiped (#57828).
- # Unavailable probes are indeterminate, not healthy — keep the lazy marker.
+ # Import-based recovery: metadata-only verifiers miss dist-info intact but import files
+ # wiped. Unavailable probes are indeterminate, not healthy — keep the lazy marker.
status = _m()._repair_venv_via_import_probes(install_cmd_prefix, env=env)
if status == "repaired":
print(
@@ -495,15 +442,11 @@ def _refresh_active_lazy_features(
def _refresh_active_memory_provider_dependencies() -> None:
- """Refresh pip dependencies for the configured external memory provider.
-
- Provider bridge packages are declared in each provider's ``plugin.yaml``
- (plus mode extras like Hindsight's ``hindsight-all``), not in Hermes'
- extras or ``LAZY_DEPS``, so the core reinstall can strip or downgrade
- them (#53272, #70636). Re-run the ACTIVE provider's install after the
- core install and lazy refresh so its writes to shared packages land last.
+ """Refresh pip deps for the configured external memory provider.
- Never raises. A failure here must not block the rest of the update.
+ 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.
"""
try:
from hermes_cli.config import load_config
@@ -521,7 +464,7 @@ def _refresh_active_memory_provider_dependencies() -> None:
return
provider = str(memory_cfg.get("provider") or "").strip()
- # "default" / empty is the built-in file-backed store — no pip deps.
+ # "default"/empty is the built-in file store — no pip deps.
if not provider or provider in {"default", "builtin", "none"}:
return
@@ -550,15 +493,9 @@ def _install_psutil_android_compat(
*,
env: dict[str, str] | None = None,
) -> None:
- """Install psutil on Android by patching upstream platform detection.
-
- psutil's setup gates Linux sources behind ``sys.platform.startswith('linux')``;
- Termux reports ``'android'``, so setup aborts although the Linux source path
- compiles fine. Only the extracted build tree for this attempt is patched.
-
- Stopgap: remove (together with the standalone installer's use of the same
- helper) once https://github.com/giampaolo/psutil/pull/2762 ships.
- """
+ """Install psutil on Android by patching its platform detection: setup gates Linux sources on
+ ``sys.platform.startswith('linux')`` but Termux reports ``'android'`` though the Linux path
+ compiles fine. Only this attempt's build tree is patched. Stopgap until psutil PR 2762 ships."""
from hermes_cli.update_cmd import _m
import tempfile
import urllib.request
@@ -577,12 +514,8 @@ def _install_psutil_android_compat(
def _ensure_uv_for_termux(pip_cmd: list[str]) -> str | None:
- """Best-effort uv bootstrap on Termux for faster update installs.
-
- The official uv installer may not work on Termux (glibc vs bionic). Prefer
- a uv already on PATH (``pkg install uv``); otherwise fall back to a
- wheel-only ``pip install uv`` so the Rust crate is never source-built.
- """
+ """Best-effort uv bootstrap on Termux (official installer may fail: glibc vs bionic). Prefer a
+ PATH uv; else wheel-only ``pip install uv`` so the Rust crate is never source-built."""
from hermes_cli.update_cmd import _m
from hermes_cli.managed_uv import resolve_uv
@@ -591,9 +524,8 @@ def _ensure_uv_for_termux(pip_cmd: list[str]) -> str | None:
return existing
if not _m()._is_termux_env():
return None
- # A Termux-packaged uv lands on PATH but not in the managed bin dir, so
- # resolve_uv() misses it. Use it before pip, which has no Android wheel and
- # would otherwise build uv from source on a low-memory device.
+ # Termux-packaged uv is on PATH but not the managed bin dir, so resolve_uv() misses it;
+ # prefer it over pip, which has no Android wheel and would source-build on a small device.
system_uv = shutil.which("uv")
if system_uv:
return system_uv
@@ -614,17 +546,11 @@ 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 is not a sufficient key: a dev can edit a package.json
- (root or workspace) without running npm, and `hermes update` is exactly
- the step expected to sync node_modules (`npm install` fallback in
- _run_npm_install_deterministic).
-
- Workspaces come from the root package.json's `workspaces` globs so a new
- workspace can never escape the key. Every workspace manifest counts —
- desktop included, though the install names only ui-tui and web — because
- the single lockfile spans the whole workspace graph. Falls back to root
- manifests only if package.json is unreadable (never skips more than main
- would have installed).
+ 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.
"""
from hermes_cli.update_cmd import _m
root_pkg = _m().PROJECT_ROOT / "package.json"
@@ -646,10 +572,7 @@ def _npm_manifest_paths() -> tuple[Path, ...]:
def _npm_manifests_digest() -> str | None:
- """Combined sha256 over the lockfile + all workspace package.json files.
-
- Returns None when the lockfile is missing (never skip then).
- """
+ """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
@@ -668,12 +591,10 @@ def _npm_lockfile_changed(hermes_root: Path) -> bool:
current = _npm_manifests_digest()
if current is None:
return True
- # Also check that node_modules exists; a matching hash with missing
- # node_modules means the cache was recorded by another checkout.
+ # Matching hash but no node_modules: cache was recorded by another checkout.
if not (_m().PROJECT_ROOT / "node_modules").is_dir():
return True
- # A matching hash must NOT skip the reinstall when the web build toolchain
- # never landed, or every later update rebuilds against a half-installed tree.
+ # Never skip when the web toolchain never landed, or later updates build on a half-installed tree.
web_dir = _m().PROJECT_ROOT / "web"
if (web_dir / "package.json").is_file() and not _web_build_toolchain_ready(
*_web_toolchain_roots(web_dir)
@@ -712,14 +633,12 @@ def _repair_node_deps_on_current_checkout(
completion_message: str = "✓ Already up to date!",
had_desktop_app_before_update: bool = False,
) -> bool:
- """Repair Node deps on the ``commit_count == 0`` path (#77211).
-
- A current checkout does not imply healthy Node deps: a failed npm install
- (EBADENGINE, network timeout, interrupt) says "re-run hermes update", but
- the early return never reached the Node refresh. ``_update_node_dependencies``
- self-gates on the lockfile hash, recorded only after a SUCCESSFUL install
- (and re-tripped when node_modules or the web toolchain is missing), so this
- is a cheap no-op on healthy installs and a real repair after a failed one.
+ """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.
"""
from hermes_cli.update_cmd import (
_check_and_apply_config_migration,
@@ -735,24 +654,20 @@ def _repair_node_deps_on_current_checkout(
"⚠ Checkout is current, but Node.js dependencies could not be repaired."
)
return False
- # Pair the refresh with the web build like every other
- # _update_node_dependencies call site; it staleness-checks internally,
- # so this is a no-op when nothing changed.
+ # Pair with the web build like every other call site; it staleness-checks internally.
_m()._build_web_ui(_m().PROJECT_ROOT / "web")
_check_and_apply_config_migration(
assume_yes=assume_yes,
gateway_mode=gateway_mode,
pre_update_snapshot_id=pre_update_snapshot_id,
)
- # A current checkout can still owe a Desktop rebuild (#97343) — e.g. the
- # Windows hand-off child never reaches the commits-pulled rebuild — leaving
- # a stale app behind a successful-looking update. Self-gates on the build stamp.
+ # A current checkout can still owe a Desktop rebuild (e.g. the Windows hand-off child
+ # never reaches the commits-pulled rebuild). Self-gates on the build stamp.
if not _rebuild_desktop_after_update(
_m().PROJECT_ROOT / "apps" / "desktop",
had_desktop_app_before_update=had_desktop_app_before_update,
):
- # _rebuild_desktop_after_update already printed the retry hint; withhold
- # success rather than claiming the update finished (#88251).
+ # Retry hint already printed; withhold success rather than claim completion.
print_completion(
"⚠ Update partially complete — the desktop app was not rebuilt "
"and is still on the previous build."
@@ -762,21 +677,16 @@ def _repair_node_deps_on_current_checkout(
def _update_node_dependencies() -> list[str]:
- """Refresh Node deps for the ui-tui and web workspaces.
-
- Returns the list of labels whose npm install failed (empty on success),
- so the caller can treat a Node refresh failure as a partial update rather
- than silently reporting ``Update complete!`` (#30271).
- """
+ """Refresh Node deps for ui-tui and web. Returns labels whose npm install failed (empty on
+ success) so the caller reports a partial update instead of ``Update complete!``."""
from hermes_cli.update_cmd import _m
if not (_m().PROJECT_ROOT / "package.json").exists():
return []
npm = _m()._resolve_node_runtime_npm()
if not npm:
- # If the only npm reachable inside this WSL shell is the Windows one,
- # flag it loudly: silently skipping leaves ui-tui deps stale while the
- # rest of the update proceeds, and running it would corrupt the tree.
+ # Only a Windows npm reachable from WSL: flag loudly — skipping silently leaves
+ # deps stale, running it would corrupt the tree.
from hermes_constants import is_wsl
path_npm = shutil.which("npm")
@@ -796,13 +706,11 @@ def _update_node_dependencies() -> list[str]:
from hermes_constants import get_default_hermes_root
- # node_modules is shared by every profile on this checkout, so keep one
- # per-checkout cache under the shared root instead of one per profile.
+ # node_modules is shared by every profile on this checkout: one per-checkout cache.
shared_hermes_root = get_default_hermes_root()
- # Best-effort npx cache warm for agent-browser (#43564), before the
- # lockfile-unchanged early return (the common case). Can block ~11s on a
- # cold cache — print first so it doesn't look like a hang.
+ # Best-effort npx cache warm before the lockfile-unchanged early return. Can block
+ # ~11s on a cold cache — print first so it doesn't look like a hang.
print("→ Warming npx cache for agent-browser...")
try:
from tools.browser_tool import warm_agent_browser_npx_cache
@@ -814,12 +722,9 @@ def _update_node_dependencies() -> list[str]:
logger.info("npm lockfile unchanged, skipping npm install")
return []
- # Root package.json has no dependencies of its own (#43564: agent-browser
- # resolves via `npx` at runtime, @streamdown/math moved to apps/desktop),
- # so a workspace-scoped install prunes nothing root-only. apps/desktop is
- # deliberately never named: its Electron devDependency has a ~200MB
- # postinstall download, so desktop deps install on demand
- # (see _desktop_build_needed).
+ # Root package.json has no deps of its own, so a workspace-scoped install prunes nothing
+ # root-only. apps/desktop is deliberately never named: its Electron devDependency has a
+ # ~200MB postinstall, so desktop deps install on demand (see _desktop_build_needed).
print("→ Updating Node.js dependencies...")
def _partial_update_failure(*labels: str) -> list[str]:
@@ -832,10 +737,8 @@ def _update_node_dependencies() -> list[str]:
install_args = [
"--no-fund", "--no-audit", "--prefer-offline", "--progress=false",
"--workspace", "ui-tui", "--workspace", "web",
- # Root's own devDependencies (the shared ESLint flat config every
- # workspace imports) would otherwise be pruned by this scoped install
- # and have nowhere else to live. apps/desktop is still excluded since
- # it is never named above.
+ # Root devDependencies (shared ESLint config) would otherwise be pruned by the
+ # scoped install; apps/desktop stays excluded since it is never named above.
"--include-workspace-root",
]
@@ -843,10 +746,8 @@ def _update_node_dependencies() -> list[str]:
nixos_env = with_hermes_node_path(_m()._nixos_build_env())
- # capture_output=False is deliberate (#18840): optional postinstall scripts
- # print download progress, and capturing it makes a long download look
- # hung. The npm-deprecation noise comes from the desktop build (captured
- # to update.log), not this step.
+ # capture_output=False is deliberate: postinstall scripts print download progress and
+ # capturing makes a long download look hung.
result = _m()._run_npm_install_deterministic(
npm,
_m().PROJECT_ROOT,
@@ -869,26 +770,18 @@ def _update_node_dependencies() -> list[str]:
def _venv_core_imports_healthy() -> tuple[bool, str]:
- """Probe the project venv for the core imports the backend needs to boot.
-
- Runs inside the venv interpreter (NOT this process — ``hermes update`` may
- run under a different Python). Catches a half-updated venv: checkout
- current but a dependency sync failed or was killed partway (e.g. Windows
- access-denied on a loaded .pyd). Without it, a current checkout prints
- "Already up to date!" and never re-syncs, so the install stays broken.
+ """Probe the venv (in ITS interpreter — updater may run under another Python) for core imports.
- Returns ``(healthy, detail)``. Never raises; unknown states report
- healthy so a probe failure can't force needless reinstalls.
+ 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.
"""
from hermes_cli.update_cmd import _m
venv_dir = _m().PROJECT_ROOT / "venv"
venv_python = venv_python_path(venv_dir, windows=_m()._is_windows())
if not venv_python.exists():
- # No venv interpreter. Normal for a dev checkout (report healthy to
- # avoid forced reinstalls), but on a MANAGED install (bootstrap stamp
- # or `.update-incomplete` present) the venv IS the install — its
- # absence means a repair was interrupted after the old venv was moved
- # aside, and "Already up to date!" would be a lie.
+ # No venv: normal for a dev checkout (healthy), but on a MANAGED install (bootstrap
+ # stamp or `.update-incomplete`) the venv IS the install — absence means an interrupted repair.
managed_markers = (
_m().PROJECT_ROOT / ".hermes-bootstrap-complete",
_m()._update_marker_path(),
@@ -897,9 +790,8 @@ def _venv_core_imports_healthy() -> tuple[bool, str]:
return False, f"venv python missing ({venv_python})"
return True, ""
- # Core web/serve imports plus their newest transitive deps. Import (not
- # just metadata) — a package can have intact dist-info but a missing
- # module after an interrupted uninstall/install cycle.
+ # Import (not just metadata): dist-info can be intact with modules missing after an
+ # interrupted uninstall/install.
check = (
"import importlib\n"
"mods = ['fastapi', 'uvicorn', 'pydantic', 'openai', 'yaml']\n"
@@ -923,7 +815,7 @@ def _venv_core_imports_healthy() -> tuple[bool, str]:
missing = [line.strip() for line in (result.stdout or "").splitlines() if line.strip()]
if result.returncode != 0 and not missing:
- # Interpreter itself is broken (e.g. deleted stdlib) — that IS unhealthy.
+ # Interpreter itself is broken — that IS unhealthy.
detail = (result.stderr or "").strip().splitlines()
return False, detail[0] if detail else "venv python failed to run"
if missing:
@@ -931,23 +823,12 @@ def _venv_core_imports_healthy() -> tuple[bool, str]:
return True, ""
-# Native-extension modules that pin files inside the venv once imported. If
-# the updater itself has one loaded, Windows blocks REPLACE on the mapped
-# ``.pyd``/``.dll`` and the sync dies with ``os error 5`` between uninstall
-# and reinstall, stranding the venv half-updated (#83569). ``cryptography``
-# is the canonical case; PyYAML's ``_yaml`` is loaded by every CLI process.
-# Kept as defence-in-depth against future eager imports, but the guard must
-# be HONEST (#86735/#86780/#86781: a preflight firing on every run, before
-# the fetch, re-bricked the flow it protected). Two honesty gates:
-#
-# 1. Fire only when the sync would actually REWRITE the loaded distribution
-# (``_dependency_sync_would_rewrite``); a satisfied pin means uv/pip
-# never touch the mapped ``.pyd``.
-# 2. Run AFTER the code swap, right before the venv rewrite — so gate 1
-# compares against the NEW pyproject and a deferral leaves the user on
-# new code with only the dependency install pending for the next launch's
-# marker recovery.
-#
+# Native extensions that pin venv files once imported: if the updater holds one, Windows blocks
+# REPLACE on the mapped ``.pyd`` and the sync dies with ``os error 5`` mid-reinstall. PyYAML's
+# ``_yaml`` is loaded by every CLI process, so the guard must be HONEST (an always-firing
+# preflight bricked the flow it protected): (1) fire only when the sync would actually
+# REWRITE the dist (``_dependency_sync_would_rewrite``); (2) run AFTER the code swap, right
+# before the venv rewrite, so a deferral leaves new code with only the install pending.
# Keys are ``sys.modules`` prefixes; values are ``(display name, PyPI dist)``.
_SELF_LOCKING_NATIVE_MODULES: dict[str, tuple[str, str]] = {
"cryptography.hazmat.bindings._rust": ("cryptography (_rust.pyd)", "cryptography"),
@@ -956,17 +837,10 @@ _SELF_LOCKING_NATIVE_MODULES: dict[str, tuple[str, str]] = {
def _dependency_sync_would_rewrite(dist_name: str) -> bool | None:
- """Whether ``uv pip install -e .[all]`` would replace *dist_name*'s files.
-
- Compares the installed version against every applicable requirement in
- the on-disk ``pyproject.toml`` (base deps plus all extras). ``False`` —
- every pin satisfied, a mapped extension is NOT at risk; ``True`` — some
- pin unsatisfied or dist missing; ``None`` — undeterminable.
-
- Never raises. Callers treat ``None`` as fail-OPEN (no deferral): PyYAML
- is loaded by every process, so deferring on uncertainty would recreate
- the #86735 always-firing loop.
- """
+ """Whether the ``.[all]`` install would replace *dist_name*'s files, judged against every
+ applicable pin in on-disk ``pyproject.toml`` (base + extras). False: all pins satisfied;
+ True: pin unsatisfied or dist missing; None: undeterminable. Never raises. Callers treat
+ None as fail-OPEN — PyYAML is in every process, so deferring on uncertainty always fires."""
from hermes_cli.update_cmd import _m
try:
from importlib import metadata as _ilmd
@@ -1005,24 +879,16 @@ def _dependency_sync_would_rewrite(dist_name: str) -> bool | None:
return True
if saw_pin:
return False
- # Not pinned anywhere in pyproject: the resolver may still move it
- # as a transitive — we cannot cheaply predict that, so stay honest
- # about the uncertainty.
+ # Not pinned in pyproject: the resolver may still move it as a transitive — unknown.
return None
except Exception:
return None
def _detect_self_loaded_native_modules() -> list[str]:
- """Native venv extensions loaded into THIS process that the sync would rewrite.
-
- Returns display names (empty off Windows — POSIX lets a running process
- keep using an unlinked inode, so self-locking is a Windows-only hazard).
- A loaded module whose installed version already satisfies the on-disk
- pyproject pins is NOT reported: the dependency sync will not touch its
- files, so there is no swap at risk (#86735 — the always-firing variant
- of this preflight bricked every Windows update). Never raises.
- """
+ """Display names of native venv extensions loaded into THIS process that the sync would rewrite.
+ Empty off Windows (POSIX keeps an unlinked inode usable). Modules whose installed version
+ already satisfies the pins are NOT reported — no swap at risk. Never raises."""
from hermes_cli.update_cmd import _m
if not _m()._is_windows():
return []
@@ -1030,12 +896,9 @@ def _detect_self_loaded_native_modules() -> list[str]:
for prefix, (display, dist) in _SELF_LOCKING_NATIVE_MODULES.items():
if prefix not in sys.modules:
continue
- # Defer ONLY on a CONFIRMED pending rewrite; "unknown" must fail OPEN,
- # since PyYAML is loaded in every CLI process and treating unknown as
- # at-risk recreated the always-firing loop (#86735). A missed deferral
- # only yields the pre-existing mid-sync os error 5, which marker
- # recovery already handles — far less harmful than an update that
- # can never run.
+ # Defer ONLY on a CONFIRMED rewrite; unknown fails OPEN (PyYAML is in every process, so
+ # unknown-as-at-risk always fires). A missed deferral only yields the mid-sync os error 5
+ # that marker recovery already handles — far less harmful than an update that never runs.
if _m()._dependency_sync_would_rewrite(dist) is not True:
continue
found.append(display)
@@ -1043,18 +906,11 @@ def _detect_self_loaded_native_modules() -> list[str]:
def _abort_dependency_sync_if_self_locked(gateway_resume=None) -> None:
- """Defer the venv rewrite when THIS process holds something it must replace.
-
- Runs after the code swap, right before the venv rewrite, so a deferral
- leaves the user on NEW code with only the dependency install pending.
- No-op when nothing at-risk is held. Two hazards with different recoveries:
-
- - A mapped native extension (``.pyd``): exit 2 and let the next launch's
- marker recovery finish the install before importing anything heavy.
- - The ``hermes.exe`` shim we were launched from (#88838, #89599): every
- future launch is also the shim, so the marker would defer forever.
- Hand the install to a child under the venv interpreter and exit.
- """
+ """Defer the venv rewrite when THIS process holds something it must replace (runs after the
+ code swap, so a deferral leaves NEW code with only the install pending). Two hazards:
+ a mapped ``.pyd`` -> exit 2, next launch's marker recovery finishes; the ``hermes.exe`` shim
+ we run from -> every launch is the shim so the marker would defer forever: hand the
+ install to a child under the venv interpreter and exit 0."""
from hermes_cli.update_cmd import _m
locked = _m()._detect_self_loaded_native_modules()
if locked:
@@ -1070,14 +926,9 @@ def _abort_dependency_sync_if_self_locked(gateway_resume=None) -> None:
def _defer_update_for_self_lock(loaded: list[str]) -> None:
- """Bail out before the dependency sync when the updater holds a lock.
-
- The install cannot win this race from inside the locked process — even
- killing threads would not unmap the image — so defer it: drop the
- update-incomplete marker (next launch's fresh process completes the
- install before importing anything heavy), explain, and exit 2 like the
- other preflight refusals.
- """
+ """Bail out before the sync when the updater holds a lock: the install can't win from inside
+ the locked process (killing threads won't unmap the image), so drop the update-incomplete
+ marker (next fresh launch completes it), explain, and let the caller exit 2."""
from hermes_cli.update_cmd import _m
print("✗ This updater process has already loaded native venv modules that")
print(" the dependency sync must replace:")
@@ -1103,18 +954,12 @@ def _desktop_app_present(desktop_dir: Path) -> bool:
def _rebuild_desktop_after_update(
desktop_dir: Path, *, had_desktop_app_before_update: bool
) -> bool:
- """Rebuild an installed Desktop app when its source or artifact changed.
-
- Returns ``False`` only when a rebuild was attempted and failed, so the
- caller can withhold ``✓ Update complete!`` and (in gateway mode) write
- a failing ``.update_exit_code`` (#88251). Every other outcome — nothing
- to rebuild, up to date, build succeeded, Desktop never installed —
- returns ``True``.
- """
+ """Rebuild an installed Desktop app when its source or artifact changed. Returns ``False``
+ only when a rebuild was attempted and failed (caller withholds ``✓ Update complete!`` and
+ writes a failing ``.update_exit_code`` in gateway mode); every other outcome is ``True``."""
from hermes_cli.update_cmd import _m
- # The release tree is ignored by git and can disappear during an update.
- # Its pre-update presence is enough to restore it; do not make people who
- # have never used Desktop pay for an Electron build.
+ # The release tree is git-ignored and can vanish mid-update; pre-update presence suffices.
+ # Never make people who never used Desktop pay for an Electron build.
has_desktop_app = had_desktop_app_before_update or _desktop_app_present(desktop_dir)
if not (
(desktop_dir / "package.json").exists()
@@ -1124,11 +969,9 @@ def _rebuild_desktop_after_update(
return True
print("→ Checking if desktop app needs rebuilding...")
- # Consult the content-hash stamp IN-PROCESS first: the spawned
- # `hermes desktop --build-only` re-imports the whole CLI stack (~1-3 s)
- # just to reach the same _m()._desktop_build_needed check. The update path
- # never passes --source, so mirror source_mode=False. Any pre-check error
- # falls through to the subprocess.
+ # Check the content-hash stamp IN-PROCESS first (the subprocess spends ~1-3 s importing the
+ # CLI to reach the same check). Update never passes --source, so source_mode=False.
+ # Any pre-check error falls through to the subprocess.
skip_desktop_build = False
try:
skip_desktop_build = not _m()._desktop_build_needed(
@@ -1141,14 +984,9 @@ def _rebuild_desktop_after_update(
return True
desktop_build_cmd = [sys.executable, "-m", "hermes_cli.main", "desktop", "--build-only"]
- # Capture the (very loud) Electron/vite build output into update.log. On
- # a nonzero exit, retry once (covers a still-settling rebuild window), then
- # surface the captured tail so the failure is debuggable.
- #
- # Put the Hermes-managed Node on PATH: inside the desktop updater chain
- # (Desktop → hermes-setup → hermes update) shell PATH customizations are
- # lost, so a bare-PATH child fails with `node: not found` before cmd_gui
- # can self-heal.
+ # Capture the loud build output into update.log; retry once on failure (still-settling
+ # rebuild window), then surface the tail. Put Hermes-managed Node on PATH: the desktop
+ # updater chain loses shell PATH customizations, so a bare-PATH child hits `node: not found`.
from hermes_constants import with_hermes_node_path
build_env = with_hermes_node_path()
@@ -1173,11 +1011,8 @@ def _rebuild_desktop_after_update(
def _path_uid(path) -> Optional[int]:
- """Owner uid of ``path`` via ``os.stat`` — ``None`` when unreadable.
-
- Separate seam so tests can simulate root-owned files without chown
- (which needs root). Never raises.
- """
+ """Owner uid of ``path`` (``None`` when unreadable). Separate seam so tests can simulate
+ root-owned files without chown. Never raises."""
try:
return os.stat(path, follow_symlinks=False).st_uid
except OSError:
@@ -1185,22 +1020,15 @@ 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 (#83529).
-
- A venv ever touched by ``sudo pip`` / ``sudo hermes`` contains root-owned
- files (classically ``*.dist-info/INSTALLER``); a later normal ``hermes
- update`` then dies mid-mutation inside ``uv pip install -e .`` with
- ``venv/bin/hermes`` already deleted — the CLI is bricked. Same philosophy
- as the contended-venv gate (#87331): never mutate a venv we cannot safely mutate.
-
- Deliberately BOUNDED (no full recursion): the venv root, direct entries of
- ``venv/bin``, top-level entries of the first ``lib/python*/site-packages``,
- and direct children of each ``*.dist-info`` there; ~2000 stat calls max,
- at most ``limit`` paths returned. POSIX-only: ``[]`` on Windows and as
- root. Swallows every per-entry ``OSError`` and returns ``[]`` on any
- structural surprise — must NEVER raise or add noticeable latency.
-
- Returns ``(path_str, uid)`` tuples, at most ``limit`` long.
+ """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.
"""
from hermes_cli.update_cmd import _path_uid
try:
@@ -1255,20 +1083,14 @@ def _venv_foreign_owned_paths(venv_root, limit: int = 5) -> list:
return foreign[:limit]
except Exception:
- # Preflight is advisory: any structural surprise means "no verdict",
- # never a crashed or blocked update.
+ # Advisory preflight: structural surprise = "no verdict", never a blocked update.
return []
def _refuse_update_if_venv_foreign_owned(project_root) -> None:
- """Refuse-before-mutate ownership gate for the dependency install (#83529).
-
- Runs after the code pull and immediately before the first venv mutation:
- foreign-owned venv files would make ``uv pip install -e .`` die
- mid-mutation and brick the install, so refuse up front with the exact
- recovery command while the venv is intact. No subprocess calls here —
- update tests mock ``subprocess.run`` with sequenced side effects.
- """
+ """Refuse-before-mutate ownership gate, run after the pull and before the first venv mutation:
+ foreign-owned files would brick the install mid-mutation, so refuse with the recovery command
+ while the venv is intact. No subprocess calls — tests mock ``subprocess.run`` with sequenced effects."""
foreign = _venv_foreign_owned_paths(Path(project_root) / "venv")
if not foreign:
return
@@ -1293,13 +1115,9 @@ def _sync_python_dependencies_after_pull(
active_tool_dependencies,
_windows_gateway_resume,
):
- """Reinstall Python dependencies for the freshly pulled checkout.
-
- Order matters: ownership preflight -> self-lock deferral -> core-install
- marker -> ``.[all]`` (uv or pip) -> bytecode sweep -> lazy-feature and
- tool-dependency refresh (own marker) -> memory-provider bridge deps ->
- critical-import probe (warn only; stale-bytecode self-heals next launch).
- """
+ """Reinstall Python deps for the pulled checkout. Order matters: ownership preflight ->
+ self-lock deferral -> core marker -> ``.[all]`` -> bytecode sweep -> lazy/tool refresh (own
+ marker) -> memory-provider deps -> critical-import probe (warn only; stale bytecode self-heals)."""
from hermes_cli.update_cmd import (
_m,
_sweep_bytecode_after_update,
@@ -1308,18 +1126,11 @@ def _sync_python_dependencies_after_pull(
_write_update_incomplete_marker,
)
_refuse_update_if_venv_foreign_owned(_m().PROJECT_ROOT)
- #
- # Self-lock deferral (relocated preflight — #86735): if THIS process
- # holds a native extension the sync must rewrite, defer NOW — after
- # the code swap, so only the dependency install is pending and the
- # next fresh launch completes it via the marker.
+ # Self-lock deferral: if THIS process holds a native extension the sync must rewrite, defer
+ # NOW (after the code swap) so only the install is pending for the next launch's marker.
_m()._abort_dependency_sync_if_self_locked(_windows_gateway_resume)
- #
- # Drop the core-install breadcrumb BEFORE touching the venv. If the
- # install is killed mid-flight (Ctrl-C, terminal close, WSL OOM), the
- # marker survives and the next ``hermes`` launch finishes the install
- # via ``_recover_from_interrupted_install``. Cleared after the core
- # ``.[all]`` install completes — lazy refresh uses a separate marker.
+ # Drop the core-install breadcrumb BEFORE touching the venv so a killed install is finished
+ # by the next launch (``_recover_from_interrupted_install``). Lazy refresh uses its own marker.
_write_update_incomplete_marker()
deps_current = _editable_install_is_current(
git_cmd, _m().PROJECT_ROOT, pre_pull_sha
@@ -1330,7 +1141,7 @@ def _sync_python_dependencies_after_pull(
print("→ Updating Python dependencies...")
from hermes_cli.managed_uv import ensure_uv, update_managed_uv
- # Keep managed uv current — runs `uv self update` if we already have one.
+ # `uv self update` if we already have a managed uv.
update_managed_uv()
uv_bin = ensure_uv()
@@ -1341,9 +1152,7 @@ def _sync_python_dependencies_after_pull(
install_group = "all"
if uv_bin:
- # Use official managed_python_env() isolation so third-party
- # UV_PYTHON_INSTALL_DIR (e.g. WorkBuddy) cannot hijack uv; then
- # point VIRTUAL_ENV at this install's venv.
+ # managed_python_env() isolation so a third-party UV_PYTHON_INSTALL_DIR can't hijack uv.
from hermes_cli.managed_uv import managed_python_env
uv_env = managed_python_env()
@@ -1377,36 +1186,27 @@ def _sync_python_dependencies_after_pull(
lazy_env = uv_env if uv_bin else None
if deps_current:
- # The verification normally runs inside the install we just
- # skipped. Run it here so a wrong skip self-heals into a real
- # install (both verifiers reinstall what they find missing)
- # instead of leaving a venv nobody checked.
+ # Verification normally runs inside the skipped install; run it here so a wrong skip
+ # self-heals (both verifiers reinstall what they find missing).
_m()._verify_core_dependencies_installed(
install_prefix, env=lazy_env, group=install_group
)
_m()._verify_console_scripts_installed(install_prefix, env=lazy_env)
- # Core ``.[all]`` install finished. Clear the generic core breadcrumb
- # before the lazy-refresh phase — that phase uses its own marker so a
- # later lazy failure cannot be "healed" by clearing the core marker
- # based on a narrow 7-package import probe (#58004 review).
+ # Clear the core breadcrumb before lazy refresh, which uses its own marker so a lazy
+ # failure can't be "healed" by a narrow core import probe.
_m()._clear_update_incomplete_marker()
- # The update process is still the old Python interpreter process. Run
- # one final cache/module refresh immediately before lazy backend
- # refresh, which imports newly-pulled modules that may depend on fresh
- # symbols in hermes_constants or lazy_deps. The dependency install
- # above may also have regenerated bytecode from build-cache copies —
- # this second sweep catches those stragglers (#60242, #65240).
+ # Still the old interpreter process: refresh caches/modules before lazy refresh imports
+ # newly-pulled modules. The install may have regenerated bytecode from build-cache
+ # copies — this second sweep catches those stragglers.
_sweep_bytecode_after_update(branch)
_m()._reload_updated_runtime_modules()
- # Upgrade pip before lazy refreshes — stale pip can fail source builds
- # and leave partially-written packages (#57828).
+ # Stale pip can fail source builds and leave partially-written packages.
_write_lazy_refresh_incomplete_marker()
_m()._upgrade_pip_before_lazy_refresh(install_prefix, env=lazy_env)
- # Lazy refresh can corrupt the venv when a backend install fails.
# Clear the lazy marker only when refresh/repair is confirmed healthy.
lazy_ok = _m()._refresh_active_lazy_features(
install_prefix,
@@ -1427,15 +1227,11 @@ def _sync_python_dependencies_after_pull(
env=lazy_env,
)
- # Heal the active memory provider's bridge packages last — the core
- # reinstall + lazy refresh above may have stripped or downgraded
- # plugin.yaml-declared deps that aren't in extras (#53272, #70636).
+ # Heal memory-provider bridge packages last — the steps above may have stripped them.
_m()._refresh_active_memory_provider_dependencies()
- # All transient-ImportError sources have run, so a module that still
- # won't import is real breakage. Warn only — never roll back: `cannot
- # import name X` is also the stale-bytecode signature (#6207, #60242),
- # which _sweep_stale_bytecode_if_checkout_changed() self-heals next launch.
+ # Remaining import failures are real breakage. Warn only — never roll back: `cannot import
+ # name X` is also the stale-bytecode signature, which self-heals next launch.
import_ok, failing_module, import_error = _validate_critical_modules_import(
_m().PROJECT_ROOT
)
diff --git a/hermes_cli/update_cmd_git.py b/hermes_cli/update_cmd_git.py
index 474a25d351c..b15dd3a2fb8 100644
--- a/hermes_cli/update_cmd_git.py
+++ b/hermes_cli/update_cmd_git.py
@@ -1,9 +1,8 @@
"""Git plumbing for ``hermes update``: fork/upstream sync, trampoline-git detection, lockfile/EOL churn cleanup, orphan rescue refs, parked-branch assessment, fetch-failure classification.
-Split out of ``hermes_cli/update_cmd.py``; every moved name is re-imported there, so
-``hermes_cli.update_cmd.<name>`` keeps resolving (and monkeypatching) as before.
-Origin-internal helpers are imported lazily inside each function (no import cycle;
-test patches on ``hermes_cli.update_cmd.<name>`` stay effective).
+Split out of ``update_cmd.py``, which re-imports every name so ``hermes_cli.update_cmd.<name>``
+still resolves/monkeypatches. Origin helpers are imported lazily per function (no cycle;
+test patches on ``update_cmd`` stay effective).
"""
import logging
@@ -30,20 +29,12 @@ def _prune_orphan_rescue_refs(
keep=_ORPHAN_RESCUE_REFS_TO_KEEP,
max_age_days=_ORPHAN_RESCUE_REF_MAX_AGE_DAYS,
) -> None:
- """Expire old orphan rescue refs so backups stay bounded.
-
- Each orphan-history divergence (#87694) parks the pre-reset HEAD under
- ``refs/hermes-update-backups/orphan-<branch>-<ts>-<sha>``. A rescue ref
- pins its objects against ``git gc`` — in the incident shape a full
- working-tree snapshot, potentially multi-GB — so a repeatedly corrupted
- install would grow ``.git`` without bound.
-
- Two limits, both enforced on every orphan incident: keep only the
- ``keep`` most-recent refs, and drop any older than ``max_age_days`` per
- the ``YYYYMMDD-HHMMSS`` stamp in the ref name (unparseable names are left
- alone). Names sort chronologically, so ``for-each-ref`` order is creation
- order. Disk is reclaimed on the next ``git gc``. Best-effort: never
- blocks the update.
+ """Expire old orphan rescue refs (``refs/hermes-update-backups/orphan-<branch>-<ts>-<sha>``).
+
+ Each ref pins a possibly multi-GB snapshot against ``git gc``, so a repeatedly corrupted
+ install would grow ``.git`` unbounded. Keep the ``keep`` newest AND drop any older than
+ ``max_age_days`` by the ``YYYYMMDD-HHMMSS`` stamp (unparseable names left alone); names
+ sort chronologically so ``for-each-ref`` order is creation order. Best-effort, never blocks.
"""
from hermes_cli.update_cmd import _git_run
try:
@@ -57,8 +48,6 @@ def _prune_orphan_rescue_refs(
return
refs = [line.strip() for line in list_result.stdout.splitlines() if line.strip()]
stale = set(refs[:-keep] if keep > 0 else refs)
- # Age expiry: ref names embed a UTC YYYYMMDD-HHMMSS timestamp right
- # after the branch segment; anything older than max_age_days goes.
if max_age_days > 0:
from datetime import timedelta, timezone
@@ -81,11 +70,9 @@ def _prune_orphan_rescue_refs(
def _branch_head_label(git_cmd=None, cwd=None) -> str | None:
- """``"<branch> @ <short-sha>"`` for the checkout, or None when unknown.
+ """``"<branch> @ <short-sha>"`` for the checkout, or None when unknown. Never raises.
- Appended to update summary lines so branch drift is visible (2026-08-17
- incident: a checkout parked on a stale feature branch got "✓ Update
- complete!" with nothing saying WHERE it sat). Never raises.
+ Appended to summary lines so a checkout parked on a stale branch is visible.
"""
from hermes_cli.update_cmd import _m
try:
@@ -122,27 +109,14 @@ def _branch_head_suffix(git_cmd=None, cwd=None) -> str:
def _assess_parked_branch_switch(
git_cmd: list[str], cwd: Path, current_branch: str, target_branch: str
) -> tuple[bool, str]:
- """Decide whether it is safe to auto-switch a parked feature branch back
- to the update target.
-
- Live incident (2026-08-17): the checkout sat on a stale feature branch;
- ``hermes update`` autostashed, ran post-update steps and printed
- "✓ Code updated!" while the running code stayed days behind main.
-
- - (True, "") — tree + index clean AND every parked commit is already in
- ``origin/<target_branch>`` (``git cherry`` reports no ``+`` lines).
- - (True, "unmerged:<count>") — tree clean but the branch has commits not
- in the target. Switching is safe (``git checkout`` never discards
- committed work) but the caller must print a LOUD notice naming the
- branch and count. Non-interactive callers (desktop button, gateway
- /update, cron) rely on this: they can't resolve a skip, so a clean
- checkout must always reach the target.
- - (False, <reason>) — dirty tree, git errors, or the
- ``updates.auto_switch_parked_branch: false`` opt-out; caller must NOT
- touch the branch. A dirty tree is the genuinely unsafe case: uncommitted
- work riding an autostash across branches is how the incident started.
-
- Block reasons: "disabled", "dirty", "unverifiable".
+ """Decide whether a parked feature branch may be auto-switched back to the update target.
+
+ - (True, "") — tree clean and every parked commit is in ``origin/<target>`` (no ``git cherry +``).
+ - (True, "unmerged:<n>") — tree clean but commits not in target; switching is safe (checkout
+ keeps committed work) but caller must print a LOUD notice. Non-interactive callers
+ (desktop, gateway /update, cron) can't resolve a skip, so a clean checkout must reach target.
+ - (False, "disabled"|"dirty"|"unverifiable") — caller must NOT touch the branch. Dirty is
+ the genuinely unsafe case: uncommitted work riding an autostash across branches.
"""
from hermes_cli.update_cmd import _git_run
try:
@@ -154,8 +128,7 @@ def _assess_parked_branch_switch(
):
return False, "disabled"
except Exception as exc:
- # A config read failure must not disable the guard's safety checks —
- # fall through to them with the default (auto-switch allowed).
+ # Config read failure must not disable the safety checks; fall through with default.
logger.debug("Could not read updates.auto_switch_parked_branch: %s", exc)
status = _git_run(git_cmd, ["status", "--porcelain"], cwd)
@@ -171,9 +144,7 @@ def _assess_parked_branch_switch(
line for line in cherry.stdout.splitlines() if line.startswith("+")
]
if unmerged:
- # Clean tree: switching is safe (checkout keeps the commits on the
- # branch). The reason string tells the caller to print the loud
- # "branch kept with N unmerged commit(s)" notice.
+ # Safe (checkout keeps commits); reason tells caller to print the loud notice.
return True, f"unmerged:{len(unmerged)}"
return True, ""
@@ -185,8 +156,7 @@ def _print_parked_branch_skip_warning(
target_branch: str,
reason: str,
) -> None:
- """LOUD block explaining why the code update was skipped on a parked
- branch, with the behind-count and the exact commands to resolve."""
+ """LOUD block: why the update was skipped on a parked branch, behind-count, fix commands."""
from hermes_cli.update_cmd import _git_run
behind = None
try:
@@ -230,12 +200,10 @@ def _print_parked_branch_skip_warning(
def _print_parked_branch_kept_notice(
current_branch: str, target_branch: str, unmerged_count: str
) -> None:
- """LOUD notice printed when a clean parked branch with unmerged commits
- is auto-switched back to the update target.
+ """LOUD notice when a clean parked branch with unmerged commits is auto-switched.
- Non-interactive callers can't resolve a skip, so a clean checkout always
- proceeds — but the unmerged work must be impossible to miss. The commits
- stay on the branch (``git checkout`` never discards committed work).
+ Non-interactive callers can't resolve a skip, so we proceed — but the unmerged work
+ (still safe on its branch) must be impossible to miss.
"""
bar = "=" * 68
print()
@@ -284,7 +252,6 @@ def _is_fork(origin_url: Optional[str]) -> bool:
"""Check if the origin remote points to a fork (not the official repo)."""
if not origin_url:
return False
- # Normalize URL for comparison (strip trailing .git if present)
normalized = origin_url.rstrip("/")
if normalized.endswith(".git"):
normalized = normalized[:-4]
@@ -347,10 +314,7 @@ def _mark_skip_upstream_prompt():
def _sync_fork_with_upstream(git_cmd: list[str], cwd: Path) -> bool:
- """Attempt to push updated main to origin (sync fork).
-
- Returns True if push succeeded, False otherwise.
- """
+ """Push updated main to origin (sync fork); True on success."""
from hermes_cli.update_cmd import _git_run
try:
result = _git_run(git_cmd, ["push", "origin", "main", "--force-with-lease"], cwd, network=True)
@@ -366,15 +330,11 @@ def _sync_with_upstream_if_needed(
assume_yes: bool = False,
input_fn=None,
) -> bool:
- """Check if fork is behind upstream and fast-forward if safe.
+ """Offer to add ``upstream``, compare origin/main vs upstream/main, ff-pull when strictly
+ behind, then push origin.
- Offers to add the ``upstream`` remote, compares origin/main with
- upstream/main, pulls when strictly behind, then tries to push origin.
-
- Returns True only when origin/main was actually verified against
- upstream/main; False when the check never happened (prompt declined,
- remote add/fetch/compare failed) so the caller never reports "up to date"
- on an origin-only comparison (#97052).
+ Returns True only when origin/main was actually verified against upstream/main; False when
+ the check never happened, so the caller never reports "up to date" on an origin-only compare.
"""
from hermes_cli.update_cmd import (
_add_upstream_remote,
@@ -398,8 +358,7 @@ def _sync_with_upstream_if_needed(
if assume_yes or (
input_fn is None and not (sys.stdin.isatty() and sys.stdout.isatty())
):
- # --yes means "don't block", not "mutate my git remotes". Skip
- # without persisting the decline so interactive runs still get asked.
+ # --yes means "don't block", not "mutate my remotes"; don't persist the decline.
print(" Skipping upstream setup (non-interactive run).")
print(
" Add it later with: git remote add upstream https://github.com/NousResearch/hermes-agent.git"
@@ -440,8 +399,7 @@ def _sync_with_upstream_if_needed(
_mark_skip_upstream_prompt()
return False
- # Fetch only upstream/main: a bare fetch drags in thousands of
- # auto-generated branches.
+ # Only upstream/main: a bare fetch drags in thousands of auto-generated branches.
print()
print("→ Fetching upstream...")
try:
@@ -456,7 +414,6 @@ def _sync_with_upstream_if_needed(
print(" ✗ Failed to fetch upstream. Skipping upstream sync.")
return False
- # Compare origin/main with upstream/main
origin_ahead = _count_commits_between(git_cmd, cwd, "upstream/main", "origin/main")
upstream_ahead = _count_commits_between(
git_cmd, cwd, "origin/main", "upstream/main"
@@ -466,7 +423,6 @@ def _sync_with_upstream_if_needed(
print(" ✗ Could not compare branches. Skipping upstream sync.")
return False
- # If origin/main has commits not on upstream, don't trample
if origin_ahead > 0:
print()
print(f"ℹ Your fork has {origin_ahead} commit(s) not on upstream.")
@@ -479,7 +435,6 @@ def _sync_with_upstream_if_needed(
print(" ✓ Fork is up to date with upstream")
return True
- # origin/main is strictly behind upstream/main (can fast-forward)
print()
print(f"→ Fork is {upstream_ahead} commit(s) behind upstream")
print("→ Pulling from upstream...")
@@ -511,13 +466,10 @@ def _sync_with_upstream_if_needed(
def _classify_fetch_failure(stderr: str) -> str:
- """Map git-fetch stderr to a one-line, user-facing diagnosis.
+ """Map git-fetch stderr to a one-line diagnosis (caller also prints the raw first line).
- Order matters: curl reports HTTP failures as ``unable to access '<url>':
- The requested URL returned error: 429``, so the rate-limit/outage checks
- must run BEFORE the generic "unable to access" network check. The caller
- always prints the first raw stderr line too — this adds guidance, it
- never replaces the wire error.
+ Order matters: curl reports HTTP errors as ``unable to access '<url>': ... error: 429``,
+ so rate-limit/outage checks must run BEFORE the generic "unable to access" check.
"""
def _has_http_code(*codes: str) -> bool:
@@ -539,9 +491,8 @@ def _classify_fetch_failure(stderr: str) -> str:
if "Could not resolve host" in stderr or "unable to access" in stderr:
return "✗ Network error — cannot reach the remote repository."
if "could not read Username" in stderr or "terminal prompts disabled" in stderr:
- # Anonymous fetch of a public repo got HTTP 401. GitHub does this
- # during outages (and for renamed/private repos) — it is not a
- # credentials problem on the user's side.
+ # Anonymous fetch got HTTP 401: GitHub does this during outages (and for
+ # renamed/private repos) — not a user credentials problem.
return (
"✗ GitHub rejected the anonymous fetch (asked for a login) — this"
" usually means a GitHub outage; try again in a few minutes"
@@ -562,13 +513,11 @@ def _print_fetch_failure(stderr: str) -> None:
def _git_is_trampoline(git_cmd: list) -> bool:
- """Whether *git_cmd* resolves to a Git-for-Windows trampoline launcher.
+ """Whether *git_cmd* is a broken Git-for-Windows trampoline shim.
- Git for Windows ships ~46KB shims (``bin\\git.exe``, ``cmd\\git.exe``) that
- re-exec ``mingw64\\libexec\\git-core\\git.exe``. When the shim cannot find
- git-core, every git call dies with the launcher's guard message — a broken
- PATH entry, not a network/filesystem problem (#87876). Never raises;
- unknown states report False so a probe failure can't block an update.
+ The ~46KB ``bin\\git.exe``/``cmd\\git.exe`` shims re-exec git-core; when they can't find
+ it every call dies with the launcher's guard message (a PATH problem, not network).
+ Never raises; unknown states report False so a probe failure can't block an update.
"""
try:
result = subprocess.run(
@@ -584,14 +533,8 @@ def _git_is_trampoline(git_cmd: list) -> bool:
def _portable_git_candidates() -> list:
- """PortableGit candidate paths: shared root first, then profile home.
-
- The Hermes-managed PortableGit tree lives under the SHARED root
- (``<root>/git/...``), not the profile-scoped HERMES_HOME
- (``<root>/profiles/<name>``), so a profile-scoped ``hermes update`` must
- look there (monerostar review, #87876). The profile-home candidate is
- kept as a fallback for custom layouts that place it there.
- """
+ """PortableGit candidates: shared root first (where the managed tree actually lives,
+ not the profile-scoped HERMES_HOME), then profile home as a fallback for custom layouts."""
from hermes_cli.update_cmd import get_default_hermes_root, get_hermes_home
candidates = []
try:
@@ -605,15 +548,9 @@ def _portable_git_candidates() -> list:
def _locate_real_git() -> Optional[Path]:
- """Find a real Git-for-Windows binary that is not a broken trampoline.
-
- The ~46KB ``bin\\git.exe`` / ``cmd\\git.exe`` shims fail to re-exec
- git-core while ``mingw64\\libexec\\git-core\\git.exe`` (≈4.4MB) works
- directly (#87876). Check standard Git for Windows locations plus the
- Hermes-managed PortableGit; accept the first candidate that runs without
- the trampoline guard. None when nothing suits — callers keep the broken
- command and let the fetch-failure ZIP fallback handle it.
- """
+ """Find a real Git-for-Windows ``git-core/git.exe`` (standard locations + managed PortableGit)
+ that runs without the trampoline guard. None when nothing suits — callers keep the broken
+ command and let the fetch-failure ZIP fallback handle it."""
candidates = [
Path(r"C:\Program Files\Git\mingw64\libexec\git-core\git.exe"),
Path(r"C:\Program Files (x86)\Git\mingw64\libexec\git-core\git.exe"),
@@ -638,14 +575,9 @@ def _locate_real_git() -> Optional[Path]:
def _ensure_non_trampoline_git(git_cmd: list) -> list:
- """Swap a broken Git-for-Windows trampoline for a real git binary.
-
- Runs right after the git command is built. If ``git`` is a broken
- trampoline, rebuild the command around the real binary so fetch/pull/
- checkout keep working instead of degrading to the ZIP fallback; if none is
- found, leave the command untouched (the fetch-failure handler falls back to
- ZIP on Windows). No-op off Windows and when git is healthy.
- """
+ """Swap a broken Git-for-Windows trampoline for a real git binary so fetch/pull/checkout
+ keep working; if none is found leave the command untouched (fetch-failure handler falls
+ back to ZIP). No-op off Windows and when git is healthy."""
from hermes_cli.update_cmd import _locate_real_git
if sys.platform != "win32":
return git_cmd
@@ -666,13 +598,9 @@ def _ensure_non_trampoline_git(git_cmd: list) -> list:
def _discard_lockfile_churn(git_cmd, repo_root):
- """Restore tracked ``package-lock.json`` files that npm dirtied locally.
-
- npm rewrites lockfiles non-deterministically at install/build time. On a
- managed install those diffs are never intentional, so we discard them so
- ``hermes update`` sees a clean tree instead of autostashing every run.
- Best-effort; only ever touches files named ``package-lock.json``.
- """
+ """Restore ``package-lock.json`` files npm rewrote non-deterministically, so the update
+ sees a clean tree instead of autostashing every run. Only touches lockfiles whose
+ package.json is NOT also dirty. Best-effort."""
from hermes_cli.update_cmd import _git_run
try:
diff = _git_run(git_cmd, ["diff", "--name-only"], repo_root)
@@ -694,29 +622,21 @@ def _discard_lockfile_churn(git_cmd, repo_root):
_git_run(git_cmd, ["checkout", "--", *dirty], repo_root)
print(f"→ Discarded npm lockfile churn ({len(dirty)} file(s))")
except Exception:
- # Never let lockfile cleanup block an update.
pass
def _normalize_managed_eol(git_cmd, repo_root):
"""Take a managed checkout off ``core.autocrlf=true`` without leaving it dirty.
- Git for Windows ships ``core.autocrlf=true`` system-wide, which turns this
- repo's LF files CRLF in the working tree and breaks ``git checkout`` on
- update ("Your local changes would be overwritten"); ``install.ps1`` pins
- ``core.autocrlf=false`` on the managed clone (#67730). Older checkouts never
- got the pin and the bootstrap installer reuses its build-pinned
- ``install.ps1`` forever, so ``hermes update`` is the only path that can fix them.
-
- The pin and the cleanup are one operation: under ``autocrlf=true`` a CRLF
- tree reads clean, so pinning alone would expose every text file as
- modified and hand the update a whole-tree autostash. The pin is written
- only after the tree is verified clean under it; a checkout we cannot fully
- normalize is left as it was. Best-effort: never blocks an update.
+ Git for Windows sets ``autocrlf=true`` system-wide, turning LF files CRLF and breaking
+ ``git checkout`` on update; install.ps1 pins ``false`` but older checkouts never got it
+ and only ``hermes update`` can fix them. Pin and cleanup are one operation: under
+ ``autocrlf=true`` a CRLF tree reads clean, so pinning alone would expose every file as
+ modified (whole-tree autostash). Pin only after the tree verifies clean under it; a
+ checkout we can't fully normalize is left as-is. Best-effort.
"""
from hermes_cli.update_cmd import _git_run
- # -c, not config: evaluate the tree as it WOULD look pinned, without
- # persisting anything we might not be able to follow through on.
+ # -c, not config: evaluate the tree as it WOULD look pinned, persisting nothing.
probe = git_cmd + ["-c", "core.autocrlf=false"]
def _dirty(*extra):
@@ -731,11 +651,8 @@ def _normalize_managed_eol(git_cmd, repo_root):
return {p for p in out.stdout.split("\0") if p}
def _real_dirty():
- # Files with a *content* change once CRLF differences are ignored.
- # ``diff --name-only --ignore-cr-at-eol`` still LISTS CR-only files
- # (names come from blob/stat differences before the CR filter), so use
- # ``--numstat``, which honors the filter: a CR-only file produces no
- # record. Parse the paths out of numstat.
+ # Files with a *content* change ignoring CRLF. ``--name-only --ignore-cr-at-eol``
+ # still LISTS CR-only files; ``--numstat`` honors the filter (no record for them).
out = subprocess.run(
probe + ["-c", "core.quotepath=false",
"diff", "--numstat", "--ignore-cr-at-eol"],
@@ -749,8 +666,7 @@ def _normalize_managed_eol(git_cmd, repo_root):
for line in out.stdout.splitlines():
if not line.strip():
continue
- # Format: "<added>\t<deleted>\t<path>". Rename detection is off in
- # plain diff, so there is exactly one path field per record.
+ # "<added>\t<deleted>\t<path>"; rename detection off, so exactly one path.
parts = line.split("\t", 2)
if len(parts) == 3 and parts[2]:
paths.add(parts[2])
@@ -764,8 +680,7 @@ def _normalize_managed_eol(git_cmd, repo_root):
try:
effective = _git_run(git_cmd, ["config", "--get", "core.autocrlf"], repo_root)
- # Only "true" rewrites LF to CRLF on checkout. Unset, false, and input
- # all leave the working tree alone, so there is nothing to repair.
+ # Only "true" rewrites LF->CRLF; unset/false/input leave the tree alone.
if effective.stdout.strip().lower() != "true":
return
@@ -773,8 +688,7 @@ def _normalize_managed_eol(git_cmd, repo_root):
if eol_only is None:
return
if eol_only:
- # Pathspec over stdin, not argv: a fully renormalized checkout is
- # thousands of paths, well past the Windows command-line limit.
+ # Pathspec via stdin: thousands of paths exceed the Windows argv limit.
subprocess.run(
probe
+ ["checkout", "--pathspec-from-file=-", "--pathspec-file-nul", "--"],
@@ -785,8 +699,7 @@ def _normalize_managed_eol(git_cmd, repo_root):
check=False,
)
if _eol_only():
- # Still dirty — persisting the pin here would only surface churn
- # we failed to clear. Leave the checkout as we found it.
+ # Still dirty: pinning would only surface churn we failed to clear.
return
print(f"→ Normalized line-ending churn ({len(eol_only)} file(s))")
@@ -797,5 +710,4 @@ def _normalize_managed_eol(git_cmd, repo_root):
check=False,
)
except Exception:
- # Never let line-ending cleanup block an update.
pass
diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.py
index 21468d3fe25..1687178851f 100644
--- a/hermes_cli/update_cmd_maint.py
+++ b/hermes_cli/update_cmd_maint.py
@@ -1,9 +1,8 @@
"""Post-update maintenance for ``hermes update``: pre-update backup snapshot, state-db verify/restore, curator/FTS notices, FHS path guard, completion summary, stale-module purge.
-Split out of ``hermes_cli/update_cmd.py``; every moved name is re-imported there, so
-``hermes_cli.update_cmd.<name>`` keeps resolving (and monkeypatching) as before.
-Origin-internal helpers are imported lazily inside each function (no import cycle;
-test patches on ``hermes_cli.update_cmd.<name>`` stay effective).
+Split out of ``update_cmd.py``, which re-imports every name so ``hermes_cli.update_cmd.<name>``
+still resolves/monkeypatches. Origin helpers are imported lazily per function (no cycle;
+test patches on ``update_cmd`` stay effective).
"""
import logging
@@ -27,10 +26,8 @@ _UPDATE_RUNTIME_RELOAD_MODULES = (
)
-#: Package prefixes whose cached modules become stale the moment the checkout
-#: changes under this process. Purged (not reloaded) by
-#: ``_purge_stale_hermes_modules`` so any LATER import chain resolves against
-#: fresh on-disk source only.
+#: Package prefixes whose cached modules go stale when the checkout changes under this
+#: process; purged (not reloaded) so any LATER import chain resolves against fresh source.
_STALE_PURGE_PREFIXES = (
"hermes_cli",
"gateway",
@@ -40,10 +37,8 @@ _STALE_PURGE_PREFIXES = (
)
-#: Modules that must survive the purge: they are (or are referenced by) the
-#: code currently EXECUTING the update, so evicting them buys nothing — the
-#: running frames keep their module objects alive regardless — and reloading
-#: them mid-flight is the one genuinely unsafe move.
+#: Modules EXECUTING the update survive the purge: evicting them buys nothing (running frames
+#: keep them alive) and reloading them mid-flight is the one genuinely unsafe move.
_STALE_PURGE_PROTECTED = frozenset(
{
"hermes_cli",
@@ -59,24 +54,12 @@ _STALE_PURGE_PROTECTED = frozenset(
def _purge_stale_hermes_modules() -> None:
- """Evict every cached Hermes module after the checkout changed in-place.
-
- ``hermes update`` keeps running in the pre-pull Python process; the
- gateway-restart phase then does function-level imports of NEW source
- inside an OLD ``sys.modules`` world. As soon as new source references a
- symbol added to an already-cached module, the import dies (2026-08-20:
- fresh ``hermes_cli.gateway`` imported ``line_input`` from a stale cached
- ``cli_output`` → restart phase aborted, gateway kept serving old code).
-
- ``_UPDATE_RUNTIME_RELOAD_MODULES`` fixed this per-symptom; this is the
- class fix: drop EVERY cached module under the Hermes package prefixes so
- later lazy imports rebuild a self-consistent graph from the new checkout.
- Purging only removes the ``sys.modules`` entry — module objects held by
- running frames stay alive and functional. Only genuinely executing modules
- are exempt, because reload-in-place (not purge) is what can pull code out
- from under a running frame.
-
- Best-effort: never raises.
+ """Evict every cached Hermes module after the checkout changed in-place. Never raises.
+
+ The update runs in the pre-pull process; later phases lazily import NEW source into an OLD
+ ``sys.modules`` world and die when new code references a symbol missing from a cached
+ module. Purging (unlike reload) only drops the ``sys.modules`` entry — running frames keep
+ their module objects — so later imports rebuild a self-consistent graph from the new tree.
"""
from hermes_cli.update_cmd import _m
try:
@@ -91,8 +74,7 @@ def _purge_stale_hermes_modules() -> None:
continue
root = name.split(".", 1)[0]
if root not in _STALE_PURGE_PREFIXES:
- # Prefix-string match caught an unrelated package
- # (e.g. ``gateway_foo``) — leave it alone.
+ # startswith() also matches unrelated packages like ``gateway_foo``.
continue
if _m().sys.modules.pop(name, None) is not None:
purged.append(name)
@@ -105,12 +87,8 @@ def _purge_stale_hermes_modules() -> None:
def _reload_updated_runtime_modules() -> None:
- """Reload update-sensitive modules after the checkout changes in-place.
-
- ``hermes update`` runs in the pre-pull process, so cached modules can
- expose old symbols despite new source on disk. Refresh the small set used
- by lazy-backend refresh before that step imports newly-updated code paths.
- """
+ """Reload the modules used by lazy-backend refresh: the pre-pull process's cached modules
+ can expose old symbols despite new source on disk."""
from hermes_cli.update_cmd import _m
try:
import importlib
@@ -129,14 +107,9 @@ def _reload_updated_runtime_modules() -> None:
def _print_curator_first_run_notice() -> None:
- """Print a short heads-up about the skill curator after `hermes update`.
-
- Only fires when the curator is enabled AND has no recorded run yet, which
- is exactly the window where the gateway ticker used to fire Curator
- against a fresh skill library immediately after an update. We defer the
- first real pass by one ``interval_hours``; this notice tells the user how
- to preview or disable before then. Silent on steady state.
- """
+ """Curator heads-up after update. Fires only when enabled AND never run — the window where
+ the first pass (deferred one ``interval_hours``) is pending, so the user can preview or
+ disable it first. Silent on steady state."""
try:
from agent import curator
except Exception:
@@ -148,7 +121,6 @@ def _print_curator_first_run_notice() -> None:
except Exception:
return
if state.get("last_run_at"):
- # Curator has run before (real or already seeded) — no notice needed.
return
try:
hours = curator.get_interval_hours()
@@ -170,14 +142,9 @@ def _print_curator_first_run_notice() -> None:
def _print_fts_optimize_available_notice() -> None:
- """Advertise the opt-in v23 search-index optimization after `hermes update`.
-
- Only fires when the current profile's state.db is still on the legacy
- (pre-v23) inline FTS layout. Leads with the reclaimable-space figure and
- points at the exact command. Honors ``sessions.fts_optimize_notice``:
- ``advise`` (default) prints an advisory notice, ``require`` prints a
- firmer required-upgrade notice, ``off`` suppresses it. Silent for
- fresh/already-optimized installs.
+ """Advertise the opt-in v23 FTS optimization when state.db is still on the legacy layout.
+
+ ``sessions.fts_optimize_notice``: ``advise`` (default), ``require`` (firmer), ``off``.
"""
mode = "advise"
try:
@@ -205,21 +172,20 @@ def _print_fts_optimize_available_notice() -> None:
size_gb = db_path.stat().st_size / (1024 ** 3)
except OSError:
return
- # Skip the notice for trivially small DBs — the win isn't worth the nag.
+ # Small DBs: the win isn't worth the nag.
if size_gb < 0.5:
return
db = None
interrupted = False
try:
db = SessionDB(db_path=db_path, read_only=True)
- # read_only opens skip schema init, so probe the layout directly.
+ # read_only opens skip schema init; probe the layout directly.
row = db._conn.execute(
"SELECT sql FROM sqlite_master "
"WHERE type = 'table' AND name = 'messages_fts'"
).fetchone()
- # An interrupted `optimize-storage` run: the table is already the
- # v23 shape, but backfill markers / demoted trash tables remain.
- # Offer the command again — re-running resumes and finishes it.
+ # Interrupted optimize-storage: v23 table shape but backfill markers / trash
+ # tables remain. Re-running resumes it, so offer the command again.
interrupted = bool(
db._conn.execute(
"SELECT 1 FROM state_meta "
@@ -244,7 +210,6 @@ def _print_fts_optimize_available_notice() -> None:
pass
sql = (row[0] if row else "") or ""
if not sql or ("tool_name" in sql and not interrupted):
- # v23 layout already present (fresh/optimized) — nothing to offer.
return
if interrupted:
@@ -258,7 +223,6 @@ def _print_fts_optimize_available_notice() -> None:
print(" hermes sessions optimize-storage")
return
- # Concrete size framing — lead with the savings the user cares about.
est_reclaim = size_gb * 0.6
print()
if mode == "require":
@@ -284,14 +248,8 @@ def _print_fts_optimize_available_notice() -> None:
def _print_curator_recent_run_notice() -> None:
- """Print the most recent curator run summary, exactly once.
-
- The curator runs in the background, so users only notice consolidations
- by stumbling into a rename; ``hermes update`` is a high-attention surface
- to show the rename map. Show-once: stamps ``last_run_summary_shown_at``
- after printing. Silent when the curator never ran, the summary was already
- shown, or it has no rename info (no archives).
- """
+ """Print the latest background curator run summary (rename map) once, stamping
+ ``last_run_summary_shown_at``. Silent when never run, already shown, or no rename info."""
try:
from agent import curator
except Exception:
@@ -312,10 +270,8 @@ def _print_curator_recent_run_notice() -> None:
if not summary:
return
- # Only a multi-line summary (rename map appended) is worth showing; a
- # bare "auto: no changes; llm: no change" isn't.
+ # Only a multi-line summary (rename map) is worth showing; still stamp it shown.
if "\n" not in summary:
- # Still stamp it shown so we don't reconsider it on every update.
try:
state["last_run_summary_shown_at"] = last_run_at
curator.save_state(state)
@@ -333,7 +289,6 @@ def _print_curator_recent_run_notice() -> None:
"View anytime: hermes curator status)"
)
- # Stamp shown so we don't repeat on the next update.
try:
state["last_run_summary_shown_at"] = last_run_at
curator.save_state(state)
@@ -362,18 +317,10 @@ def _format_time_ago(iso_ts: str) -> str:
def _reload_process_scan_modules() -> None:
- """Force-reload the process-scan modules from disk after an update.
-
- ``_finish_dashboard_update_cleanup`` runs in the PRE-update process, but
- ``_scan_dashboard_processes`` lazily imports from ``_subprocess_compat``;
- a symbol the update added (``bounded_probe_run``, #87134) is missing from
- the cached OLD module and the cleanup crashes with ImportError after the
- code update already succeeded. Reload dependency-first so
- ``dashboard_procs`` binds against the fresh ``_subprocess_compat``.
-
- Called from the cleanup entry point (not only ``_reload_config_modules``)
- so EVERY caller — git path, Windows ZIP fallback, future ones — is covered.
- """
+ """Reload the process-scan modules, dependency-first, so ``dashboard_procs`` binds against a
+ fresh ``_subprocess_compat``: cleanup runs in the PRE-update process and a symbol the update
+ added would otherwise ImportError after the code update succeeded. Called from the cleanup
+ entry point so every caller (git path, ZIP fallback) is covered."""
import importlib
importlib.invalidate_caches()
@@ -386,8 +333,7 @@ def _reload_process_scan_modules() -> None:
try:
importlib.reload(mod)
except Exception as exc:
- # warning, not debug: a failed reload here surfaces seconds
- # later as an ImportError in the same process — leave a trail.
+ # warning, not debug: a failed reload surfaces as ImportError seconds later.
logger.warning(
"Could not reload %s for post-update cleanup: %s",
mod_name,
@@ -400,10 +346,8 @@ def _finish_dashboard_update_cleanup(
) -> None:
"""Refresh managed dashboards or stop stale manual ones after an update.
- *already_restarted_units* forwards the systemd unit names (no
- ``.service`` suffix) that the fleet-restart loop already restarted
- directly, so a Serve-only install's freshly restarted process isn't
- found and restarted a second time here (review on #83595).
+ *already_restarted_units*: systemd unit names (no ``.service``) the fleet-restart loop
+ already restarted, so a Serve-only install isn't restarted a second time here.
"""
from hermes_cli.update_cmd import _m, _reload_process_scan_modules
if node_failures:
@@ -412,8 +356,6 @@ def _finish_dashboard_update_cleanup(
print(" Node.js dependency refresh did not complete.")
return
- # The scan path lazy-imports symbols from _subprocess_compat; make sure
- # both modules reflect the freshly-updated source before touching them.
_reload_process_scan_modules()
stop_result = _m()._kill_stale_dashboard_processes(
@@ -432,10 +374,8 @@ def _finish_dashboard_update_cleanup(
def _print_update_completion(message: str) -> None:
- """Print an update outcome plus, when the dashboard launched this run with
- an action id, a terminal receipt line the Desktop can match after the
- dashboard restarts (#47359 / #58764). The outcome line carries the
- branch + HEAD short-sha so branch drift is visible (2026-08-17 incident)."""
+ """Print the outcome (with branch @ sha so drift is visible) plus, when launched by the
+ dashboard with an action id, a receipt line the Desktop matches after restart."""
from hermes_cli.update_cmd import _branch_head_suffix
print(f"{message}{_branch_head_suffix()}")
action_id = os.environ.get("HERMES_ACTION_ID", "")
@@ -444,12 +384,8 @@ def _print_update_completion(message: str) -> None:
def _read_project_version() -> str | None:
- """Read the ``version`` field from the checkout's pyproject.toml.
-
- On-disk file, not importlib.metadata: after a pull the installed
- metadata still describes the OLD version. Returns None on any failure —
- version reporting is cosmetic and must never break an update.
- """
+ """``version`` from the checkout's pyproject.toml (not importlib.metadata, which still
+ describes the OLD version after a pull). None on any failure — cosmetic, never breaks."""
from hermes_cli.update_cmd import _m
try:
import tomllib
@@ -462,12 +398,8 @@ def _read_project_version() -> str | None:
def _update_complete_message(pre_version: str | None) -> str:
- """Completion line with the version transition when it is known.
-
- Ported from PrimeIntellect-ai/prime-agent#630: show ``v0.19.4 → v0.20.0``
- after a self-update. Plain message when either side is unknown or the
- version did not change (several commits within one release).
- """
+ """Completion line with ``vA → vB`` when known; plain when either side is unknown or
+ the version did not change."""
post_version = _read_project_version()
if pre_version and post_version and pre_version != post_version:
return f"✓ Update complete! (v{pre_version} → v{post_version})"
@@ -500,10 +432,8 @@ def _print_verified_update_completion(message: str) -> bool:
return False
sqlite_runtime_ok, sqlite_info = _post_update_sqlite_runtime_status()
if sqlite_info is None:
- # Grace path: an unprobeable interpreter (no venv in a dev checkout,
- # probe subprocess unavailable) must not fail an otherwise-successful
- # update — only a POSITIVE vulnerable probe withholds success
- # (same contract as _venv_core_imports_healthy's unknown states).
+ # Grace path: an unprobeable interpreter (dev checkout, no probe subprocess) must not
+ # fail the update — only a POSITIVE vulnerable probe withholds success.
logger.debug("Post-update SQLite runtime probe unavailable; not blocking")
_print_update_completion(message)
return True
@@ -524,19 +454,13 @@ def _print_verified_update_completion(message: str) -> bool:
def _clear_stale_sqlite_sidecars(db_path: Path) -> None:
- """Delete the WAL / shared-memory / rollback-journal files next to *db_path*.
-
- Call immediately before overwriting a database with a snapshot image.
- Quick snapshots come from ``sqlite3.backup()`` (``backup._safe_copy_db``),
- so the image is checkpointed and owns no WAL — which is why
- ``backup._EXCLUDED_SUFFIXES`` ships no sidecars. Copying the image
- replaces only the main file, so a ``-wal``/``-shm`` left by the *old*
- database (crashed writer, undrained second process) is replayed over the
- fresh image on next open: it passes ``PRAGMA integrity_check`` while
- serving the old contents, and the first checkpoint makes that permanent.
-
- Safe here because the sidecars belong to a database the caller has already
- declared corrupt and is about to discard.
+ """Delete -wal/-shm/-journal next to *db_path*, immediately before overwriting it with a
+ snapshot image.
+
+ Snapshots are checkpointed ``sqlite3.backup()`` images with no WAL; copying replaces only
+ the main file, so a leftover WAL from the OLD database would be replayed over the fresh
+ image on next open (passes integrity_check while serving old contents). Safe because the
+ caller has already declared that database corrupt.
"""
for suffix in ("-wal", "-shm", "-journal"):
db_path.with_name(db_path.name + suffix).unlink(missing_ok=True)
@@ -548,13 +472,11 @@ def _print_update_summary(
desktop_build_ok: bool,
pre_update_version: str | None,
) -> bool:
- """Final update banner. A failed Desktop rebuild is non-fatal for the
- Python side, but must not print ``✓ Update complete!`` (#88251)."""
+ """Final banner. A failed Desktop rebuild is non-fatal but must not print ``✓ Update complete!``."""
from hermes_cli.update_cmd import _post_update_sqlite_runtime_status, _update_complete_message
sqlite_runtime_ok, sqlite_info = _post_update_sqlite_runtime_status()
if sqlite_info is None:
- # Grace path: an unprobeable interpreter must not fail the update —
- # only a POSITIVE vulnerable probe demotes success to partial.
+ # Grace path: only a POSITIVE vulnerable probe demotes success to partial.
sqlite_runtime_ok = True
print()
if node_failures or not desktop_build_ok or not sqlite_runtime_ok:
@@ -591,21 +513,13 @@ def _print_update_summary(
def _restore_state_db_from_snapshot(state_path: Path, snap_state: Path) -> bool:
- """Replace *state_path* with the snapshot image at *snap_state*.
+ """Replace *state_path* with the snapshot image; True when the result passes integrity.
- Shared by the ZIP and git-pull auto-restore paths. Stale sidecars are
- cleared before the copy so the corrupt database's WAL replay cannot
- silently overwrite the restored image (:func:`_clear_stale_sqlite_sidecars`).
-
- Refuses (``False``) while another process — or a live connection in THIS
- process — holds the database or its sidecars: copying over a live
- writer's inode desyncs its page cache/WAL index from the file bytes and
- its next checkpoint clobbers pages (#90950 page-1 clobber). ``None``
- (scan unavailable) proceeds: gateways are already drained, and refusing
- on "unknown" would disable auto-restore on every non-Linux host.
-
- Returns ``True`` when the restored file passes an integrity check. Raises
- ``OSError`` if the copy itself fails (callers already report it).
+ Stale sidecars are cleared first so the corrupt DB's WAL can't replay over the image.
+ Refuses (False) while another process — or a live connection in THIS process — holds the
+ DB: copying over a live writer's inode desyncs its page cache and its next checkpoint
+ clobbers pages. Holder scan ``None`` proceeds (gateways drained; refusing on unknown would
+ disable auto-restore on non-Linux). Raises OSError if the copy fails.
"""
from hermes_cli.backup import _foreign_db_holder_pids, verify_sqlite_integrity
from hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_access
@@ -618,12 +532,9 @@ def _restore_state_db_from_snapshot(state_path: Path, snap_state: Path) -> bool:
"then restore manually with /snapshot restore."
)
return False
- # The foreign-pid scan excludes THIS process, but an in-process SessionDB
- # handle is just as live: unlinking -wal/-shm and copy2-ing under it
- # leaves this process checkpointing through deleted-inode sidecars (the
- # #90950 split brain, reproduced live via `/proc/self/fd`).
- # ``offline_file_access`` fails CLOSED on any tracked connection and holds
- # the lifecycle lock across clear + copy so none can appear mid-swap.
+ # The foreign-pid scan excludes THIS process; an in-process SessionDB handle is just as
+ # live (it would checkpoint through deleted-inode sidecars). offline_file_access fails
+ # CLOSED on any tracked connection and holds the lock across clear + copy.
try:
with offline_file_access(state_path, what="restore a snapshot over"):
_clear_stale_sqlite_sidecars(state_path)
@@ -641,14 +552,8 @@ def _restore_state_db_from_snapshot(state_path: Path, snap_state: Path) -> bool:
def _verify_and_restore_one_state_db(home: Path, *, label: str) -> None:
- """Post-update integrity check + auto-restore for ONE home's state.db.
-
- Shared by the root-DB and sibling-profile guards (ZIP update path and
- git-pull path both route here). A corrupt live DB is restored from the
- most recent valid snapshot under that home's own state-snapshots dir.
- Never raises: a guard that crashes the update tail would be worse than
- the corruption it detects.
- """
+ """Integrity check + auto-restore for ONE home's state.db from its newest valid snapshot.
+ Never raises: a guard that crashes the update tail is worse than what it detects."""
try:
from hermes_cli.backup import _quick_snapshot_root, verify_sqlite_integrity
@@ -704,13 +609,8 @@ def _verify_and_restore_one_state_db(home: Path, *, label: str) -> None:
def _verify_and_restore_state_dbs_post_update() -> None:
- """Post-update integrity guard for the ROOT state.db AND every sibling
- profile's state.db (#97994).
-
- The pre-update snapshot already covers siblings (#66140), but the guard
- only verified the root DB — a corrupted profile DB was never detected or
- restored, its sessions silently gone while the root passed.
- """
+ """Integrity guard for the ROOT state.db AND every sibling profile's (the snapshot covers
+ siblings, so the guard must too or a corrupt profile DB goes undetected)."""
from hermes_cli.update_cmd import get_hermes_home
home = get_hermes_home()
_verify_and_restore_one_state_db(home, label="default home")
@@ -752,17 +652,9 @@ def _print_bundled_skills_sync_report() -> None:
def _ensure_fhs_path_guard() -> None:
- """Ensure /usr/local/bin is on PATH for RHEL-family root non-login shells.
-
- Mirrors the post-symlink probe in ``scripts/install.sh`` so existing FHS
- root installs on RHEL/CentOS/Rocky/Alma 8+ get repaired on ``hermes
- update``. In non-login interactive shells there (su, sudo -s, tmux panes)
- neither /etc/bashrc nor /root/.bash_profile adds /usr/local/bin, so
- ``hermes`` prints ``command not found`` despite the symlink.
-
- Silent no-op on non-Linux, non-root, non-FHS installs, and wherever
- ``bash -i -c 'command -v hermes'`` already resolves. Idempotent.
- """
+ """Ensure /usr/local/bin is on PATH for RHEL-family root non-login shells (su, sudo -s,
+ tmux), where neither /etc/bashrc nor .bash_profile adds it. Mirrors install.sh. Idempotent;
+ no-op on non-Linux/non-root/non-FHS or when ``bash -i -c 'command -v hermes'`` resolves."""
from hermes_cli.update_cmd import _m
if _m().sys.platform != "linux":
return
@@ -771,15 +663,13 @@ def _ensure_fhs_path_guard() -> None:
return
except AttributeError:
return
- # Only act when this is actually an FHS-layout install (command link at
- # /usr/local/bin/hermes, code at /usr/local/lib/hermes-agent).
+ # Only for FHS-layout installs (link at /usr/local/bin/hermes).
fhs_link = Path("/usr/local/bin/hermes")
if not fhs_link.is_symlink() and not fhs_link.exists():
return
- # Probe a fresh non-login interactive bash the way the user will use it.
- # ``bash -i -c`` sources ~/.bashrc but NOT ~/.bash_profile or /etc/profile,
- # which is the exact scenario where RHEL root loses /usr/local/bin.
+ # ``bash -i -c`` sources ~/.bashrc but NOT ~/.bash_profile or /etc/profile — the exact
+ # scenario where RHEL root loses /usr/local/bin.
home = os.environ.get("HOME") or "/root"
try:
probe = subprocess.run(
@@ -815,8 +705,7 @@ def _ensure_fhs_path_guard() -> None:
existing = cfg.read_text(errors="replace", encoding="utf-8")
except OSError:
continue
- # Idempotency: skip if any uncommented PATH= line already references
- # /usr/local/bin. Mirrors the grep pattern used by install.sh.
+ # Idempotency: any uncommented PATH line referencing /usr/local/bin (install.sh grep).
already_guarded = any(
"/usr/local/bin" in line
and "PATH" in line
@@ -838,25 +727,17 @@ def _ensure_fhs_path_guard() -> None:
def _ensure_acp_launcher() -> None:
- r"""Self-heal: install a ``hermes-acp`` launcher next to the ``hermes`` one.
-
- Mirrors the launcher block in ``scripts/install.sh``. ACP hosts (Zed,
- JetBrains, Buzz Desktop) resolve ``hermes-acp`` on the login-shell PATH,
- but the console script lives inside the venv, so they report Hermes as
- not installed. The shim just delegates to the sibling ``hermes`` launcher
- with the ``acp`` subcommand, which is correct for every install layout.
-
- No-op on Windows: install.ps1 stages launchers into ``$HermesHome\bin``
- and puts THAT on PATH — never ``venv\Scripts``, which would shadow the
- user's ``python`` (#83797); ``ensure_windows_bin_launchers`` re-stages
- them. Also no-op where ``hermes-acp`` already exists next to ``hermes``.
- Unwritable dirs (``/usr/local/bin`` as non-root) are skipped. Idempotent.
+ r"""Self-heal a ``hermes-acp`` launcher next to ``hermes`` (mirrors install.sh): ACP hosts
+ resolve it on the login-shell PATH but the console script lives in the venv. The shim
+ delegates to the sibling ``hermes acp``, correct for every layout.
+
+ No-op on Windows (install.ps1 stages launchers into ``$HermesHome\bin``, never
+ ``venv\Scripts`` which would shadow the user's python) and where it already exists.
+ Unwritable dirs are skipped. Idempotent.
"""
from hermes_cli.update_cmd import _m
if _m().sys.platform == "win32":
- # Windows launcher staging/repair lives in _install_repair
- # (ensure_windows_bin_launchers at process start,
- # migrate_windows_bin_path in this command's tail) — not here.
+ # Windows launcher repair lives in _install_repair, not here.
return
for bin_dir in (Path.home() / ".local" / "bin", Path("/usr/local/bin")):
hermes_cmd = bin_dir / "hermes"
@@ -864,9 +745,7 @@ def _ensure_acp_launcher() -> None:
try:
if not (hermes_cmd.is_file() or hermes_cmd.is_symlink()):
continue
- # Already present (console script, earlier shim, or symlink).
- # is_symlink() catches broken symlinks exists() misses; never
- # follow-and-overwrite (#21454).
+ # is_symlink() catches broken symlinks exists() misses; never follow-and-overwrite.
if acp_cmd.exists() or acp_cmd.is_symlink():
continue
shim = (
@@ -886,20 +765,15 @@ def _ensure_acp_launcher() -> None:
_PRE_UPDATE_SNAPSHOT_KEEP = 1
-# Per-file cap for the quick snapshot; larger files are skipped with a warning.
-# The snapshot protects small, hard-to-regenerate state (pairing JSONs, cron,
-# config, auth) — not a multi-GB state.db (a 24 GB one cost ~60s and 24 GB/update).
+# Per-file cap for the quick snapshot (larger files skipped with a warning): it protects
+# small hard-to-regenerate state, not a multi-GB state.db (24 GB cost ~60s + 24 GB/update).
_PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE = 1 << 30 # 1 GiB
def _resolve_pre_update_backup_mode(args) -> str:
- """Resolve the pre-update backup mode: ``"off"``, ``"quick"``, or ``"full"``.
-
- CLI flags win over config; ``--no-backup`` beats ``--backup``. Config
- accepts the mode strings plus legacy booleans: ``true`` → ``full``,
- ``false`` → ``off`` (an explicit opt-out also disables the quick
- snapshot). Missing key defaults to ``quick``.
- """
+ """Backup mode ``off``/``quick``/``full``. CLI flags win (``--no-backup`` beats ``--backup``);
+ config accepts mode strings plus legacy booleans (true→full, false→off, which also disables
+ the quick snapshot). Default ``quick``."""
if getattr(args, "no_backup", False):
return "off"
if getattr(args, "backup", False):
@@ -936,21 +810,11 @@ def _resolve_pre_update_backup_mode(args) -> str:
def _run_pre_update_backup(args) -> Optional[str]:
- """Run the pre-update safety backup and return the quick-snapshot id.
+ """Run the pre-update backup; return the quick-snapshot id (None when off/failed). Never raises.
- Gated on ``updates.pre_update_backup``:
-
- - ``off`` — nothing runs; explicit opt-out is honored fully.
- - ``quick`` (default) — snapshot of critical small files
- (``_QUICK_STATE_FILES``) under ``state-snapshots/``; files over 1 GiB
- are skipped so a bloated state.db can never stall the update (#15733,
- #34600).
- - ``full`` — quick snapshot PLUS a zip of HERMES_HOME under ``backups/``
- (restorable via ``hermes import``; exists because of the #48200 wipe).
-
- ``--backup`` forces ``full``; ``--no-backup`` forces ``off``. Never raises.
- Returns the quick-snapshot id (used by the post-update cron-jobs restore),
- or ``None`` when mode is ``off`` or the snapshot failed.
+ ``off`` — nothing. ``quick`` (default) — snapshot of critical small files under
+ ``state-snapshots/``, files over 1 GiB skipped so a bloated state.db can't stall the update.
+ ``full`` — quick snapshot PLUS a zip of HERMES_HOME under ``backups/`` (``hermes import``).
"""
from hermes_cli.update_cmd import _record_update_step
mode = _resolve_pre_update_backup_mode(args)
@@ -959,8 +823,7 @@ def _run_pre_update_backup(args) -> Optional[str]:
if getattr(args, "no_backup", False):
print("◆ Pre-update backup: skipped (--no-backup)")
print()
- # Config-level off is silent — the user opted out; don't spam them
- # on every update.
+ # Config-level off is silent: the user opted out.
return None
snapshot_id = None
@@ -971,9 +834,8 @@ def _run_pre_update_backup(args) -> Optional[str]:
verify_sqlite_integrity,
)
- # NOTE: this function later does `from hermes_constants import
- # get_hermes_home`, which makes the name function-local — the
- # module-level import is shadowed and unbound here. Alias explicitly.
+ # A later `from hermes_constants import get_hermes_home` in this function makes that
+ # name function-local (unbound here), so alias explicitly.
from hermes_cli.config import get_hermes_home as _get_home
snapshot_id = create_quick_snapshot(
@@ -982,10 +844,8 @@ def _run_pre_update_backup(args) -> Optional[str]:
max_file_size=_PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE,
)
- # Verify the live state.db is still intact after the snapshot: a
- # concurrent process (antivirus, force-killed gateway, Windows filter
- # driver) can corrupt it at any point, and a silent zeroing would
- # otherwise proceed to exit 0 — the #68474 symptom.
+ # Verify live state.db after the snapshot: a concurrent process (antivirus, killed
+ # gateway, Windows filter driver) can corrupt it and we'd otherwise exit 0 silently.
if snapshot_id:
_src_path = _get_home() / "state.db"
if _src_path.exists():
@@ -1000,7 +860,6 @@ def _run_pre_update_backup(args) -> Optional[str]:
print(
f" ⚠ state.db integrity check FAILED after snapshot: {_msg}"
)
- # Check if the snapshot itself is valid.
_snap_root = _quick_snapshot_root(_get_home())
_snap_state = _snap_root / snapshot_id / "state.db"
if _snap_state.exists():
@@ -1027,9 +886,8 @@ def _run_pre_update_backup(args) -> Optional[str]:
if snapshot_id:
print(f"◆ Pre-update snapshot: {snapshot_id}")
- # #66140: the code swap + fleet restart touch EVERY profile, so
- # every profile gets the same snapshot (same set, same 1GiB cap,
- # keep=1) under its own state-snapshots/. Best-effort per profile.
+ # The code swap + fleet restart touch EVERY profile, so each gets the same snapshot
+ # under its own state-snapshots/. Best-effort per profile.
try:
from hermes_cli.backup import create_pre_update_snapshots_all_profiles
@@ -1051,15 +909,13 @@ def _run_pre_update_backup(args) -> Optional[str]:
)
import hermes_cli.update_cmd_config as _cfg
- # The reader (_check_and_apply_config_migration) lives in
- # update_cmd_config; write ITS module global, not ours.
+ # The reader lives in update_cmd_config; write ITS module global, not ours.
_cfg._LAST_SIBLING_SNAPSHOTS = _sibling_snaps
except Exception as _sib_exc:
logger.debug(
"Sibling profile snapshots failed: %s", _sib_exc
)
except Exception as exc:
- # Never let a snapshot failure block an update.
logger.debug("Pre-update snapshot failed: %s", exc)
if mode != "full":
@@ -1105,12 +961,11 @@ def _run_pre_update_backup(args) -> Optional[str]:
except OSError:
size_bytes = 0
- # Human-readable size
from hermes_cli.sizefmt import format_bytes
size_str = format_bytes(size_bytes)
- # Render path using display_hermes_home so the user sees ~/.hermes/...
+ # display_hermes_home so the user sees ~/.hermes/...
try:
from hermes_constants import get_hermes_home, display_hermes_home
@@ -1130,9 +985,8 @@ def _run_pre_update_backup(args) -> Optional[str]:
def _sweep_bytecode_after_update(branch: str) -> None:
- """Clear stale ``__pycache__`` (prevents ImportError on gateway restart when new
- source references names absent from old bytecode), re-stamp the fingerprint
- and refresh the bootstrap cache scripts."""
+ """Clear stale ``__pycache__`` (else gateway restart ImportErrors on names absent from old
+ bytecode), re-stamp the fingerprint, refresh the bootstrap cache scripts."""
from hermes_cli.update_cmd import _m
removed = _m()._clear_bytecode_cache(_m().PROJECT_ROOT)
if removed:
@@ -1153,23 +1007,17 @@ def _run_post_update_maintenance(
desktop_build_ok,
pre_update_version,
) -> bool:
- """Post-pull housekeeping that runs once the code + deps are in place.
-
- state.db integrity restore, catalog/skills/profile syncs, config
- migration, the update summary (whose verdict is returned), and the
- best-effort notices/self-heals (FTS, curator, PATH, launchers, cua-driver).
- Every step is isolated so none can fail the update.
- """
+ """Post-pull housekeeping: state.db restore, catalog/skills/profile syncs, config migration,
+ the update summary (verdict returned), and best-effort notices/self-heals. Every step is
+ isolated so none can fail the update."""
from hermes_cli.update_cmd import (
_check_and_apply_config_migration,
_m,
_print_curator_first_run_notice,
_print_curator_recent_run_notice,
)
- # ── macOS TCC stale-grant notice (#86385) ──────────────────────
- # Desktop bundles are re-signed each update; grants made to a pre-#73681
- # binary stay stale (toggle ON, yet macOS re-prompts with no Allow
- # button). One line tells affected users how to re-grant once.
+ # macOS TCC: Desktop bundles are re-signed each update, so old grants can go stale
+ # (toggle ON, yet macOS re-prompts with no Allow button). Tell users how to re-grant.
if sys.platform == "darwin" and had_desktop_app_before_update:
print()
print(
@@ -1180,8 +1028,7 @@ def _run_post_update_maintenance(
"fully quit & relaunch once."
)
- # macOS TCC interpreter anchor (#95596): dylib-complete re-land.
- # Boot-gated — a failed probe leaves the venv untouched.
+ # macOS TCC interpreter anchor; boot-gated — a failed probe leaves the venv untouched.
try:
from hermes_cli.macos_tcc_anchor import ensure_tcc_anchor
@@ -1189,17 +1036,13 @@ def _run_post_update_maintenance(
except Exception:
logger.debug("macOS TCC anchor refresh skipped", exc_info=True)
- # ── Post-update state.db integrity guard (#68474, #97994) ─────────
- # Check state.db in the root home AND every profile; restore a corrupted
- # one from its own pre-update snapshot instead of silently losing sessions.
+ # state.db integrity guard for root home AND every profile; restore from own snapshot.
try:
_verify_and_restore_state_dbs_post_update()
except Exception as exc:
logger.debug("Post-update state.db integrity check failed: %s", exc)
- # Seed ~/.hermes/cache/model_catalog.json from the just-pulled
- # website/static/api/model-catalog.json instead of a (bot-gated,
- # flaky) network fetch. Non-fatal: the picker refreshes on next open.
+ # Seed the model-catalog cache from the checkout instead of a bot-gated, flaky fetch.
try:
from hermes_cli.model_catalog import seed_cache_from_checkout
@@ -1208,7 +1051,6 @@ def _run_post_update_maintenance(
except Exception as e:
logger.debug("Model catalog seed during update failed: %s", e)
- # Sync bundled skills (copies new, updates changed, respects user deletions)
try:
print()
print("→ Syncing bundled skills...")
@@ -1216,11 +1058,8 @@ def _run_post_update_maintenance(
except Exception as e:
logger.debug("Skills sync during update failed: %s", e)
- # Sync bundled skills to all profiles (including the active one).
- # seed_profile_skills() uses subprocess with an explicit HERMES_HOME so
- # it is not affected by sync_skills()'s module-level HERMES_HOME cache,
- # which means the active profile is reliably synced regardless of whether
- # the caller's HERMES_HOME env var points at the default or a named profile.
+ # All profiles incl. the active one: seed_profile_skills() subprocesses with an explicit
+ # HERMES_HOME, so sync_skills()'s module-level HERMES_HOME cache can't skew it.
try:
from hermes_cli.profiles import (
list_profiles,
@@ -1256,9 +1095,8 @@ def _run_post_update_maintenance(
except Exception:
pass # profiles module not available or no profiles
- # Backfill per-profile .env files for profiles created before the
- # .env-seeding fix (#44792). Copies the default install's .env so
- # those profiles keep the credentials they were effectively using.
+ # Backfill .env for profiles created before .env seeding (copy the default's) so they
+ # keep the credentials they were effectively using.
try:
from hermes_cli.profiles import backfill_profile_envs
@@ -1272,7 +1110,6 @@ def _run_post_update_maintenance(
except Exception:
pass # profiles module not available or no profiles
- # Sync Honcho host blocks to all profiles
try:
from plugins.memory.honcho.cli import sync_honcho_profiles_quiet
@@ -1282,7 +1119,6 @@ def _run_post_update_maintenance(
except Exception:
pass # honcho plugin not installed or not configured
- # Check for config migrations (#91360).
_check_and_apply_config_migration(
assume_yes=assume_yes,
gateway_mode=gateway_mode,
@@ -1295,51 +1131,34 @@ def _run_post_update_maintenance(
pre_update_version=pre_update_version,
)
- # v23 search-index notice: the compact layout is opt-in (existing
- # indexes are untouched), so surface the command and size win here,
- # only when a legacy index is present.
+ # v23 FTS layout is opt-in (existing indexes untouched); surface the command here.
try:
_print_fts_optimize_available_notice()
except Exception as e:
logger.debug("FTS optimize notice failed: %s", e)
- # Curator first-run heads-up. Only prints when curator is enabled AND
- # has never run — i.e. the window where the ticker would otherwise
- # have fired against a fresh skill library. Kept silent on steady
- # state so we don't nag.
try:
_print_curator_first_run_notice()
except Exception as e:
logger.debug("Curator first-run notice failed: %s", e)
- # Latest curator run notice (rename map `old-name → umbrella`),
- # self-stamped so it shows once per run.
try:
_print_curator_recent_run_notice()
except Exception as e:
logger.debug("Curator recent-run notice failed: %s", e)
- # Repair RHEL-family root installs where /usr/local/bin isn't on PATH
- # for non-login interactive shells. No-op on every other platform.
try:
_ensure_fhs_path_guard()
except Exception as e:
logger.debug("FHS PATH guard check failed: %s", e)
- # Self-heal the hermes-acp launcher for installs that predate it, so
- # ACP hosts (Zed, JetBrains, Buzz) can resolve Hermes on PATH without
- # a reinstall. No-op on Windows (the launcher migration below owns
- # that) and when already present.
try:
_ensure_acp_launcher()
except Exception as e:
logger.debug("hermes-acp launcher self-heal failed: %s", e)
- # Migrate/repair Windows launchers into the managed bin dir. In-checkout
- # launchers (hermes-agent\bin) were swept by the pre-update autostash
- # (--include-untracked) and with --keep-stash never restored, so
- # `hermes` stopped resolving. Updates never run install.ps1, so this is
- # how existing installs reach the new layout. No-op on POSIX/source checkouts.
+ # Windows launchers into the managed bin dir: in-checkout launchers were swept by the
+ # autostash (--include-untracked) and updates never run install.ps1. No-op on POSIX.
try:
from hermes_cli._install_repair import migrate_windows_bin_path
@@ -1347,9 +1166,8 @@ def _run_post_update_maintenance(
except Exception as e:
logger.debug("Windows bin launcher migration failed: %s", e)
- # Refresh cua-driver (Computer Use) — no-op unless already on PATH.
- # Tied to ``hermes update`` for a predictable cadence without a
- # per-launch GitHub API call.
+ # cua-driver refresh, no-op unless on PATH; tied to update for a predictable cadence
+ # without a per-launch GitHub API call.
try:
refresh_cua_driver = True
try:
@@ -1372,12 +1190,9 @@ def _run_post_update_maintenance(
print()
print("→ Refreshing cua-driver (Computer Use)...")
- # require_confirmed_update: run the slow silent installer only
- # when check-update positively reports a newer release; an
- # indeterminate check keeps the current version (`hermes update`
- # must stay fast; `computer-use install --upgrade` is the force
- # path). Windows defers even confirmed updates there because the
- # installer may need console/UAC consent.
+ # require_confirmed_update: install only when check-update positively reports a
+ # newer release (update must stay fast; `computer-use install --upgrade` forces).
+ # Windows defers even confirmed updates (installer may need console/UAC consent).
install_cua_driver(
upgrade=True,
require_confirmed_update=True,
diff --git a/hermes_cli/update_cmd_stash.py b/hermes_cli/update_cmd_stash.py
index a3150f55559..867992c8d86 100644
--- a/hermes_cli/update_cmd_stash.py
+++ b/hermes_cli/update_cmd_stash.py
@@ -1,9 +1,7 @@
-"""Autostash handling for ``hermes update``: stash local changes before the pull, restore/park/discard them afterwards, warn about orphaned autostashes.
+"""Autostash handling for ``hermes update``: stash before the pull, restore/park/discard afterwards, warn about orphans.
-Split out of ``hermes_cli/update_cmd.py``; every moved name is re-imported there, so
-``hermes_cli.update_cmd.<name>`` keeps resolving (and monkeypatching) as before.
-Origin-internal helpers are imported lazily inside each function (no import cycle;
-test patches on ``hermes_cli.update_cmd.<name>`` stay effective).
+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; test patches on the origin stay effective).
"""
import logging
@@ -22,10 +20,8 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[st
if not status.stdout.strip():
return None
- # If the index has unmerged entries (e.g. from an interrupted merge/rebase),
- # git stash will fail with "needs merge / could not write index". Clear the
- # conflict state with `git reset` so the stash can proceed. Working-tree
- # changes are preserved; only the index conflict markers are dropped.
+ # Unmerged index entries (interrupted merge/rebase) make `git stash` fail with
+ # "needs merge"; `git reset` drops only the index conflict state, not the tree.
unmerged = _git_run(git_cmd, ["ls-files", "--unmerged"], cwd)
if unmerged.stdout.strip():
print("→ Clearing unmerged index entries from a previous conflict...")
@@ -49,10 +45,8 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[st
if push.returncode != 0:
if stash_created:
- # stash push exits non-zero when it saved everything but couldn't
- # delete some swept untracked files (e.g. a root-owned dir:
- # "failed to remove ...: Permission denied"). The entry is
- # complete, so not a failure — leave the files and continue.
+ # Non-zero but entry created: push saved everything yet couldn't delete
+ # some untracked files (e.g. root-owned dir). Not a failure — continue.
if push.stderr.strip():
print(push.stderr.strip())
print(
@@ -63,18 +57,15 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[st
" They were still saved to the stash and were left in "
"place — the update will continue."
)
- # A partially-failed stash push also aborts its working-tree
- # cleanup for TRACKED modifications — they are saved in the stash
- # but still dirty the tree, which would break the checkout/pull
- # that follows. Safe to reset: everything is in the stash entry.
+ # A partially-failed push also skips cleanup of TRACKED modifications;
+ # they'd break the following pull. Safe to reset: all is in the stash.
subprocess.run(
git_cmd + ["reset", "--hard", "HEAD"],
cwd=cwd,
capture_output=True,
)
else:
- # No stash entry was created: the changes were NOT saved. This
- # is a real failure — bail out before the update touches HEAD.
+ # No entry created: changes NOT saved — bail before touching HEAD.
print("✗ Could not stash local changes — update aborted.")
if push.stderr.strip():
print(f" {push.stderr.strip().splitlines()[0]}")
@@ -101,29 +92,21 @@ def _resolve_stash_selector(
return None
-#: Producer/consumer contract for update autostash names: the stash subject is
-#: this prefix + a UTC YYYYMMDD-HHMMSS stamp (see _stash_local_changes_if_needed
-#: and _warn_orphaned_update_autostashes).
+#: Autostash subject contract: this prefix + UTC YYYYMMDD-HHMMSS stamp
+#: (producer _stash_local_changes_if_needed, consumer _warn_orphaned_update_autostashes).
_AUTOSTASH_NAME_PREFIX = "hermes-update-autostash-"
-#: Age past which a leftover ``hermes-update-autostash-*`` entry is called out
-#: at update time. Entries younger than this are normal (a parked stash from
-#: the desktop updater's --keep-stash run minutes ago); older ones are almost
-#: always forgotten (#63717 problem 6: an orphan persisted 9+ days unnoticed).
+#: Age past which a leftover autostash is called out. Younger entries are normal
+#: (recent --keep-stash park); older ones are almost always forgotten.
_AUTOSTASH_WARN_AGE_DAYS = 7
def _warn_orphaned_update_autostashes(git_cmd: list[str], cwd: Path) -> int:
- """Surface leftover update autostashes older than the warn threshold.
+ """Print a notice for update autostashes older than the warn threshold; return the count (0 on any git failure).
- Autostashes legitimately outlive a run (``--keep-stash`` parks them; a
- failed restore preserves them), but nothing re-surfaces them — they sit
- invisibly for weeks (#63717 problem 6). Prints a notice with recovery/
- cleanup guidance. Deliberately NOT a GC: a stash entry can be the only
- copy of the user's uncommitted work, so Hermes never drops one.
-
- Best-effort — any git failure returns 0. Returns the stale-entry count.
+ Autostashes legitimately outlive a run (--keep-stash, failed restore) but nothing re-surfaces them.
+ Deliberately NOT a GC: a stash may be the only copy of the user's work, so Hermes never drops one.
"""
from hermes_cli.update_cmd import _git_run
from datetime import timedelta, timezone
@@ -148,9 +131,7 @@ def _warn_orphaned_update_autostashes(git_cmd: list[str], cwd: Path) -> int:
tzinfo=timezone.utc
)
except ValueError:
- # Unparseable name — age unknown; leave it alone rather than
- # guess (same posture as _prune_orphan_rescue_refs).
- continue
+ continue # age unknown — leave it alone rather than guess
if stash_time < cutoff:
stale.append((selector, stamp))
if not stale:
@@ -188,18 +169,11 @@ def _print_stash_cleanup_guidance(
def _stash_apply_failed_only_on_existing_untracked(stderr: str) -> bool:
- """True when a ``git stash apply`` failure is ONLY about untracked files
- that already exist in the working tree.
-
- This is the tail end of the permission-denied autostash class: ``git stash
- push --include-untracked`` swept undeletable files (e.g. a root-owned
- ``packaging/`` directory) into the stash but could not remove them from
- disk. On restore, git applies all tracked changes, then refuses to
- overwrite those still-present files (``already exists, no checkout`` /
- ``could not restore untracked files from stash``) and exits non-zero even
- though nothing was lost. Any other error line (e.g. ``would be
- overwritten by merge`` / ``Aborting``) means the tracked apply itself
- failed and this returns False.
+ """True when a ``git stash apply`` failure is ONLY about untracked files that already exist in the tree.
+
+ Tail of the permission-denied class: push swept undeletable files into the stash but couldn't remove them;
+ apply restores tracked changes, then refuses to overwrite those files and exits non-zero though nothing was lost.
+ Any other error line (e.g. ``would be overwritten by merge``) means the tracked apply failed -> False.
"""
lines = [ln.strip() for ln in (stderr or "").splitlines() if ln.strip()]
if not lines:
@@ -218,12 +192,9 @@ def _stash_apply_failed_only_on_existing_untracked(stderr: str) -> bool:
def _park_stashed_changes(stash_ref: str) -> None:
- """Leave a pre-update autostash parked instead of re-applying it.
+ """Leave a pre-update autostash parked (``--keep-stash``, the desktop updater's mode).
- Used by ``hermes update --keep-stash`` (the desktop updater's mode): the
- stash made the update possible on a dirty tree, but local source edits
- must never be silently re-applied onto the updated code. Nothing is
- lost — the entry stays in ``git stash`` with printed recovery guidance.
+ Local source edits must never be silently re-applied onto updated code; the entry stays in ``git stash``.
"""
print()
print("ℹ️ Local changes were stashed before updating and were NOT re-applied (--keep-stash).")
@@ -256,11 +227,7 @@ def _git_untracked_paths(git_cmd: list[str], cwd: Path) -> set[str] | None:
def _restored_python_paths(
git_cmd: list[str], cwd: Path
) -> tuple[str, ...] | None:
- """Return restored ``.py`` paths changed from ``HEAD``.
-
- This deliberately validates Python source only; non-Python entry scripts
- remain outside the executable import-health check.
- """
+ """Restored ``.py`` paths changed from ``HEAD``; deliberately Python-only (entry scripts stay outside the health check)."""
from hermes_cli.update_cmd import _git_untracked_paths
try:
changed = subprocess.run(
@@ -384,9 +351,7 @@ def _restore_stashed_changes(
try:
response = input().strip().lower()
except (EOFError, UnicodeDecodeError):
- # A closed stdin or terminal-encoding error must not crash the
- # update mid-restore; fall through to the skip-restore path.
- response = "n"
+ response = "n" # closed stdin/encoding error must not crash mid-restore
accepted = response in {"y", "yes"} or (not remote_prompt and response == "")
if not accepted:
print("Skipped restoring local changes.")
@@ -405,16 +370,15 @@ def _restore_stashed_changes(
print("→ Restoring local changes...")
restore = _git_run(git_cmd, ["stash", "apply", stash_ref], cwd)
- # Check for unmerged (conflicted) files — can happen even when returncode is 0
+ # Conflicts can exist even when returncode is 0
unmerged = _git_run(git_cmd, ["diff", "--name-only", "--diff-filter=U"], cwd)
has_conflicts = bool(unmerged.stdout.strip())
if restore.returncode != 0 and not has_conflicts and (
_stash_apply_failed_only_on_existing_untracked(restore.stderr)
):
- # Tracked changes applied cleanly; the only "failure" is untracked files
- # git couldn't delete at stash time and now refuses to overwrite. Their
- # content is untouched — treat as restored.
+ # Tracked changes applied; only undeletable-at-stash-time untracked files
+ # were refused. Their content is untouched — treat as restored.
print(
" ⚠ Some stashed untracked files already exist in the working "
"tree and were kept as-is."
@@ -435,8 +399,7 @@ def _restore_stashed_changes(
print("\nYour stashed changes are preserved — nothing is lost.")
print(f" Stash ref: {stash_ref}")
- # Always reset: conflict markers in source make hermes unrunnable
- # (SyntaxError on import). The user's changes remain in the stash.
+ # Always reset: conflict markers make hermes unrunnable; changes stay in the stash.
subprocess.run(
git_cmd + ["reset", "--hard", "HEAD"],
cwd=cwd,
@@ -444,8 +407,7 @@ def _restore_stashed_changes(
)
print("Working tree reset to clean state.")
print(f"Restore your changes later with: git stash apply {stash_ref}")
- # Don't exit: the code update succeeded; let cmd_update continue with
- # pip install, skill sync, and gateway restart.
+ # Don't exit: code update succeeded; cmd_update continues (deps, skills, gateway).
return False
restored_python = _restored_python_paths(git_cmd, cwd)
@@ -527,13 +489,9 @@ def _discard_stashed_changes(
cwd: Path,
stash_ref: str,
) -> bool:
- """Drop a pre-update stash without applying it.
-
- Only for NON-interactive updates with
- ``updates.non_interactive_local_changes: discard``. Unlike ``git reset
- --hard`` + ``git clean -fd``, this touches only what was stashed — ignored
- paths (node_modules, venv, build outputs) are never affected.
+ """Drop a pre-update stash without applying (non-interactive ``updates.non_interactive_local_changes: discard``).
+ Unlike reset --hard + clean -fd this touches only what was stashed; ignored paths are never affected.
Returns True if dropped, False on git failure (stash left in place).
"""
from hermes_cli.update_cmd import _git_run
diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.py
index 43748ad248a..029036225ad 100644
--- a/hermes_cli/update_cmd_windows.py
+++ b/hermes_cli/update_cmd_windows.py
@@ -1,9 +1,7 @@
-"""Windows gateway lifecycle for ``hermes update``: pause/resume/cold-start the gateway service, sweep venv-holding python processes, reap orphaned Desktop backends.
+"""Windows gateway lifecycle for ``hermes update``: pause/resume/cold-start the service, sweep venv holders, reap orphaned backends.
-Split out of ``hermes_cli/update_cmd.py``; every moved name is re-imported there, so
-``hermes_cli.update_cmd.<name>`` keeps resolving (and monkeypatching) as before.
-Origin-internal helpers are imported lazily inside each function (no import cycle;
-test patches on ``hermes_cli.update_cmd.<name>`` stay effective).
+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; test patches on the origin stay effective).
"""
import logging
@@ -75,15 +73,11 @@ def _wait_for_windows_update_gateway_exit(
def _self_and_non_gateway_ancestor_pids(psutil) -> set[int]:
- """PIDs a venv-holder scan must never nominate: this process and its ancestry.
-
- #87594: do NOT blanket-exclude ancestors. When ``/update`` runs from a
- messaging platform the updater is a CHILD of the gateway; hiding it means
- the pause machinery never sees the one process it exists to stop and the
- update dead-ends on ``venv-blocked``. Keep a GATEWAY ancestor visible (the
- pause path stops it gracefully; a detached child survives on Windows) and
- exclude every other ancestor — an updater must never nominate its own
- interactive ancestry as a blocker.
+ """PIDs a venv-holder scan must never nominate: this process and its non-gateway ancestry.
+
+ Do NOT blanket-exclude ancestors: under ``/update`` the updater is a CHILD of the gateway, and hiding it
+ dead-ends the update on ``venv-blocked``. Keep GATEWAY ancestors visible (the pause path stops them
+ gracefully; a detached child survives on Windows); never nominate interactive ancestry as a blocker.
"""
try:
from gateway.status import looks_like_gateway_command_line as _is_gw
@@ -107,18 +101,11 @@ def _self_and_non_gateway_ancestor_pids(psutil) -> set[int]:
def _detect_venv_python_processes(
*, exclude_pids: set[int] | None = None
) -> list[tuple[int, str, str]]:
- """Find live processes running from the project venv's interpreter.
-
- The hermes.exe shim guard misses the biggest Windows lock-holder class:
- the Desktop backend (``python.exe -m hermes_cli.main serve``) and anything
- running off ``venv\\Scripts\\python(w).exe``. They keep native ``.pyd``
- files mapped, so a mid-update dependency sync dies with access-denied and
- strands the venv half-updated.
-
- Killing them is pointless (the Desktop app respawns its backend), so the
- caller should refuse and ask the user to close the app. Returns
- ``(pid, name, cmdline)`` tuples; empty off-Windows / without psutil / no
- matches. This process and its ancestors are excluded. Never raises.
+ """Live processes running from the project venv's interpreter as ``(pid, name, cmdline)``; never raises.
+
+ The hermes.exe shim guard misses the Desktop backend and anything off ``venv\\Scripts\\python(w).exe``;
+ they keep ``.pyd`` files mapped so a mid-update dependency sync dies half-way. Killing is pointless (Desktop
+ respawns its backend) so callers should refuse. Empty off-Windows / without psutil; self+ancestors excluded.
"""
from hermes_cli.update_cmd import _m
if not _m()._is_windows():
@@ -143,10 +130,8 @@ def _detect_venv_python_processes(
matches: list[tuple[int, str, str]] = []
try:
- # On Windows cmdline/cwd are expensive per-process queries; with 500+
- # processes prefetching them can exceed the Desktop preflight watchdog.
- # Collect cheap identity fields first, fetch cmdline/cwd lazily for
- # plausible Python/uv/Hermes candidates.
+ # cmdline/cwd are expensive per-process on Windows (500+ procs can blow the
+ # Desktop preflight watchdog): fetch them lazily for plausible candidates only.
proc_iter = psutil.process_iter(["pid", "exe", "name"])
except Exception:
return []
@@ -163,8 +148,7 @@ def _detect_venv_python_processes(
exe_norm = str(Path(exe).resolve()).lower()
except (OSError, ValueError):
exe_norm = str(exe).lower()
- # Primary match: the executable itself lives under this venv
- # (venv\Scripts\python(w).exe — the desktop backend / gateway case).
+ # Primary match: exe lives under this venv (desktop backend / gateway case).
is_holder = exe_norm.startswith(venv_prefix)
name = str(info.get("name") or Path(exe).name)
name_low = name.lower()
@@ -180,10 +164,8 @@ def _detect_venv_python_processes(
except Exception:
cmdline_raw = ""
cmdline_low = cmdline_raw.lower()
- # Fallback: uv/base-interpreter trampolines run a python whose exe is
- # OUTSIDE the venv yet still holds its .pyd files. Match on the cmdline
- # instead: this venv's path, or `-m hermes_cli.main` tied to this
- # install (root in the cmdline or as cwd).
+ # Fallback: uv/base-interpreter trampolines have an exe OUTSIDE the venv yet hold
+ # its .pyd files — match cmdline (venv path, or `-m hermes_cli.main` + root/cwd).
if not is_holder and venv_prefix in cmdline_low:
is_holder = True
if not is_holder and "hermes_cli.main" in cmdline_low:
@@ -196,10 +178,8 @@ def _detect_venv_python_processes(
if not is_holder:
continue
name = info.get("name") or Path(exe).name
- # Return the FULL cmdline: callers parse it (the Desktop preflight's
- # pausable-gateway exemption looks for `gateway run`). Truncating here
- # once cut long interpreter paths before the argv, so autostarted
- # gateways were misreported as blockers. Truncate only at display time.
+ # FULL cmdline: callers parse it (pausable-gateway exemption looks for `gateway run`);
+ # truncating here misreported autostarted gateways as blockers. Truncate at display time.
matches.append((int(pid), str(name), cmdline_raw))
return matches
@@ -219,15 +199,11 @@ _holder_value_flags_cache: frozenset | None = None
def _holder_value_flags() -> frozenset:
- """Top-level CLI flags that consume a value — derived from the REAL parser.
-
- Introspects ``build_top_level_parser()`` (every option with nargs != 0) so
- the holder classifier can't drift from argparse (#91869: a handwritten
- subset misparsed ``--reasoning high serve`` as subcommand ``high``). The
- pre-argparse profile selectors (``--profile``/``-p``, ``--config``) are
- added explicitly since they're stripped before argparse sees argv. Falls
- back to a static snapshot when the parser can't be imported (the updater
- must classify holders even on a broken tree). Cached per process.
+ """Top-level CLI flags that consume a value, introspected from the REAL parser (nargs != 0); cached per process.
+
+ Derived so the holder classifier can't drift from argparse (a handwritten subset misparsed ``--reasoning high
+ serve``). Pre-argparse profile selectors are added explicitly (stripped before argparse sees argv). Falls back
+ to a static snapshot when the parser can't import — the updater must classify holders even on a broken tree.
"""
global _holder_value_flags_cache
if _holder_value_flags_cache is not None:
@@ -247,13 +223,10 @@ def _holder_value_flags() -> frozenset:
def _hermes_holder_subcommand(cmdline: str) -> str | None:
- """The actual Hermes SUBCOMMAND a venv-holder argv runs, or None.
+ """The actual Hermes SUBCOMMAND a venv-holder argv runs, or None (callers must NOT guess a label).
- Token-based, never substring (#90778: ``kanban --preserve-cache`` contains
- \"serve\" and got labeled as the Desktop backend). Finds the
- ``hermes_cli.main`` / ``hermes(.exe)`` entry token, then returns the first
- following token that isn't a flag or a flag's value (profile selectors
- skipped). None when undeterminable — callers must NOT guess a label.
+ Token-based, never substring (``kanban --preserve-cache`` contains "serve"): find the ``hermes_cli.main`` /
+ ``hermes(.exe)`` entry token, return the first following token that isn't a flag or a flag's value.
"""
try:
import shlex
@@ -293,11 +266,8 @@ def _hermes_holder_subcommand(cmdline: str) -> str | None:
def _format_venv_python_holders_message(matches: list[tuple[int, str, str]]) -> str:
"""Explain which venv processes block the update and how to clear them.
- Holder labels come from the parsed SUBCOMMAND, never substring matching
- (#90778): a standalone ``hermes dashboard`` must not be labeled as the
- Desktop backend (advice to close an app that isn't running), and flags
- like ``--preserve-cache`` must not match \"serve\". Unknown argv gets no
- hint rather than a wrong one.
+ Labels come from the parsed SUBCOMMAND, never substring: a standalone ``hermes dashboard`` must not be
+ called the Desktop backend, ``--preserve-cache`` must not match "serve". Unknown argv gets no hint.
"""
lines = [
"✗ Other Hermes processes are running from this install's venv:",
@@ -329,19 +299,11 @@ def _format_venv_python_holders_message(matches: list[tuple[int, str, str]]) ->
def _venv_launcher_ancestors(pids: list[int]) -> list[int]:
- """Return venv-interpreter ancestors of *pids* that hold the install open.
-
- On Windows a gateway started through the venv shim is a two-process chain:
- ``venv\\Scripts\\python.exe`` (the launcher, which keeps venv ``.pyd``
- files mapped) spawns the real interpreter from uv's managed CPython. The
- PID file is written by the *child*, so ``find_gateway_pids()`` / the pause
- set only see the uv-side worker, while ``_detect_venv_python_processes()``
- (venv path prefix) sees the *launcher*. The sets are disjoint, so a paused
- gateway still tripped the venv-holder guard and aborted the update.
-
- Walk one hop up from each mapped gateway PID and keep only ancestors under
- the project venv; unrelated ancestors (the Scheduled Task's ``cmd.exe``,
- an operator's shell) are ignored to bound the blast radius. Never raises.
+ """Venv-interpreter parents of *pids* that hold the install open; never raises.
+
+ A shim-started gateway is a chain: ``venv\\Scripts\\python.exe`` launcher (keeps ``.pyd`` mapped) -> uv
+ CPython worker (writes the PID file). The pause set sees the worker, the venv scan sees the launcher, so a
+ paused gateway still tripped the guard. One hop up only, venv-prefixed only (bounds blast radius).
"""
from hermes_cli.update_cmd import _m
if not _m()._is_windows() or not pids:
@@ -382,22 +344,11 @@ def _venv_launcher_ancestors(pids: list[int]) -> list[int]:
def _leftover_pausable_gateway_pids(
matches: list[tuple[int, str, str]],
) -> list[int] | None:
- """PIDs from *matches* when every remaining venv holder is a pausable gateway.
-
- ``_pause_windows_gateways_for_update()`` stops the gateways its discovery
- finds, but the venv-holder guard sees the process table as it is *now*: a
- gateway respawned by its supervisor inside the pause→guard window, or one
- started through an unmapped spawn path, still holds venv ``.pyd`` files and
- would dead-end the update on exactly the process the pause exists to stop.
-
- Holders are classified with the same matcher the Desktop preflight uses
- (``_is_pausable_gateway``) so exemption and tolerance cannot drift apart.
- The scan keeps only a 120-char cmdline prefix, so live argv is re-read via
- psutil when possible, falling back to the prefix.
-
- Returns ``None`` when any holder is not a pausable gateway (operator REPL,
- stray script, Desktop backend) — nothing downstream can pause it, so the
- guard must keep refusing.
+ """PIDs from *matches* when EVERY remaining venv holder is a pausable gateway, else ``None`` (keep refusing).
+
+ A gateway respawned inside the pause->guard window (or via an unmapped spawn path) still holds ``.pyd`` files.
+ Uses the Desktop preflight's ``_is_pausable_gateway`` so exemption and tolerance cannot drift; live argv is
+ re-read via psutil when possible since the scan may hold only a cmdline prefix.
"""
from hermes_cli._scan_venv_blockers import _is_pausable_gateway
@@ -423,15 +374,11 @@ def _leftover_pausable_gateway_pids(
def _refuse_gateway_ancestor_tree_kill(
pids: list[int], *, gateway_mode: bool
) -> bool:
- """Refuse a plain Windows update that would kill its own process tree.
-
- A chat agent can run plain ``hermes update`` via its terminal tool, making
- the updater a child of the gateway; leftover-holder recovery uses
- ``taskkill /T /F``, so force-stopping that gateway kills the updater before
- it mutates the checkout (#98814). ``/update`` (``--gateway`` hand-off) is
- exempt: it detaches the updater with file-based progress/result delivery.
- Otherwise refuse only when a nominated gateway is positively an ancestor of
- this process; if ancestry cannot be established, keep existing recovery.
+ """Refuse a plain Windows update that would tree-kill its own ancestry.
+
+ A chat agent running plain ``hermes update`` is a child of the gateway; ``taskkill /T /F`` on it kills the
+ updater first. ``/update`` (``--gateway``) is exempt (detached, file-based delivery). Refuse only when a
+ nominated gateway is positively an ancestor; unknown ancestry keeps existing recovery.
"""
if gateway_mode or not pids:
return False
@@ -468,16 +415,11 @@ def _refuse_gateway_ancestor_tree_kill(
def _ledger_manual_serve_holders(
matches: list[tuple[int, str, str]],
) -> list[dict]:
- """Ledger entries for venv holders that are MANUAL serve/dashboard backends.
-
- Positive identity only (#63206): the process self-registered in the spawn
- ledger with purpose serve/dashboard, its (pid, create_time) still matches
- a live process, and its recorded spawner is NOT alive (a Desktop-owned
- backend keeps its live Electron spawner and must keep the refusal — the
- app would respawn what we kill; a PowerShell-launched serve has no live
- Hermes spawner). Returns the full ledger entries so the relauncher can
- rebuild the launch command from structured host/port/profile instead of
- parsing argv.
+ """Full ledger entries for venv holders that are MANUAL serve/dashboard backends.
+
+ Positive identity only: self-registered purpose serve/dashboard, live (pid, create_time), recorded spawner
+ NOT alive (a Desktop-owned backend keeps its live Electron spawner and must keep the refusal — the app would
+ respawn what we kill). Full entries let the relauncher rebuild from host/port/profile, not argv.
"""
try:
from hermes_cli.process_identity import ledger_entries, spawner_is_dead
@@ -498,12 +440,8 @@ def _ledger_manual_serve_holders(
def _serve_relaunch_commands(entries: list[dict]) -> list[list[str]]:
- """Rebuild launch commands for stopped serves from structured identity.
-
- Uses the ledger's host/port/profile fields — never argv parsing (a
- joined argv string cannot round-trip Windows paths with spaces). Entries
- without a recorded port are skipped; the caller prints the manual hint
- for those.
+ """Rebuild launch commands for stopped serves from ledger host/port/profile — never argv parsing
+ (joined argv cannot round-trip Windows paths with spaces). Entries without a port are skipped.
"""
from hermes_cli.update_cmd import _m
commands: list[list[str]] = []
@@ -540,9 +478,7 @@ def _serve_relaunch_commands(entries: list[dict]) -> list[list[str]]:
def _relaunch_stopped_serves(token: dict) -> None:
"""Idempotent atexit relaunch of manual serves stopped by the venv guard.
- Mirrors the gateway resume token contract: `pending` flips False on the
- first invocation so the explicit call and the atexit registration cannot
- double-spawn (#63206).
+ `pending` flips False on first invocation so explicit call + atexit registration cannot double-spawn.
"""
from hermes_cli.update_cmd import _m, _record_update_step
if not token.get("pending"):
@@ -572,34 +508,15 @@ def _relaunch_stopped_serves(token: dict) -> None:
def _orphaned_desktop_backend_pids(
matches: list[tuple[int, str, str]],
) -> list[tuple[int, int]] | None:
- """PIDs from *matches* when every remaining holder is an ORPHANED backend.
-
- The venv-holder guard refuses on the Desktop app's ``serve`` backend by
- design: while the Desktop is open, killing it is futile (the app respawns
- it within seconds). But in the GUI-updater hand-off the Desktop has
- *already exited* — by contract it tree-kills its backends before spawning
- hermes-setup, and the update-in-progress marker parks any relaunched
- Desktop (#50238). A ``serve`` backend still holding the venv then is a
- straggler whose supervisor is gone (SIGTERM raced its spawn, or a crashed
- window); refusing on it dead-ends the update with "Hermes is still
- running" while the user sees zero open windows.
-
- A holder qualifies only when BOTH hold:
-
- - its cmdline is a Hermes backend (``hermes_cli.main`` + ``serve`` /
- ``dashboard``), and
- - its supervising parent is demonstrably gone: the parent PID no longer
- exists, or was reused (parent created *after* the child).
-
- Tree-aware: the scanner may also return an orphan's managed-runtime child
- (the ``.hermes-runtime`` interpreter), which has a live parent and is not
- a ``serve`` cmdline. Holders inside an accepted orphan root's tree are
- folded into that root; only roots are returned (``taskkill /T`` reaps
- descendants).
-
- Any other live-parent backend, non-backend holder outside an orphan tree,
- or unprovable case disqualifies the whole set → ``None`` (keep refusing).
- Also ``None`` when psutil is unavailable. Never raises.
+ """``(pid, start_time)`` roots from *matches* when every remaining holder is an ORPHANED backend, else ``None``.
+
+ Killing a Desktop-owned ``serve`` is futile (the app respawns it), but after the Desktop exited (GUI hand-off
+ contract: it tree-kills backends, the marker parks relaunch) a straggler whose supervisor is gone would
+ dead-end the update with "Hermes is still running" and zero open windows.
+ Qualifies only if cmdline is a Hermes backend (``hermes_cli.main`` + serve/dashboard) AND the parent is
+ demonstrably gone (PID missing or reused: parent created *after* child). Tree-aware: holders inside an
+ accepted root's tree fold into it; only roots are returned (``taskkill /T`` reaps descendants). Any other
+ live-parent backend, unjustified non-backend, unprovable case, or no psutil -> ``None``. Never raises.
"""
try:
import psutil # type: ignore
@@ -619,9 +536,7 @@ def _orphaned_desktop_backend_pids(
try:
argv = " ".join(psutil.Process(int(pid)).cmdline()) or cmdline
except psutil.NoSuchProcess:
- # Holder exited between scan and classification — nothing to
- # reap, nothing blocking. Skip it.
- continue
+ continue # exited between scan and classification — nothing to reap
except Exception:
pass
low = argv.lower()
@@ -630,15 +545,11 @@ def _orphaned_desktop_backend_pids(
continue
try:
proc = psutil.Process(int(pid))
- # Fingerprint from the SAME psutil handle, quantized to centiseconds
- # like gateway.status.get_process_start_time on Windows, so it
- # round-trips through pid_is_hermes at kill time (/proc/<pid>/stat
- # would read the HOST table in different units).
+ # Fingerprint from the SAME psutil handle, centisecond-quantized like
+ # gateway.status.get_process_start_time so pid_is_hermes round-trips at kill time.
process_start_time = int(round(proc.create_time() * 100))
except psutil.NoSuchProcess:
- # The candidate itself exited during classification; there is
- # nothing left to reap and no identity to pass to taskkill.
- continue
+ continue # exited during classification — nothing to reap
except Exception:
return None
@@ -646,12 +557,10 @@ def _orphaned_desktop_backend_pids(
ppid = proc.ppid()
parent = psutil.Process(ppid) if ppid else None
if parent is not None and parent.is_running():
- # PID-reuse check: a "parent" created after its child is a
- # recycled PID, not the real (dead) supervisor.
+ # PID-reuse check: a "parent" created after its child is a recycled PID.
if parent.create_time() <= proc.create_time():
- # Live parent — not a root, but possibly an orphan root's
- # descendant (the venv python.exe trampoline re-execs the
- # uv interpreter with the SAME argv). Defer to pass 2.
+ # Live parent: not a root, maybe an orphan root's descendant (the venv
+ # trampoline re-execs uv python with the SAME argv). Defer to pass 2.
remaining.append((int(pid), low))
continue
except psutil.NoSuchProcess:
@@ -660,9 +569,8 @@ def _orphaned_desktop_backend_pids(
return None
roots.append((int(pid), process_start_time))
- # Pass 2: every non-backend holder must be a descendant of an accepted
- # orphan root — then it dies with the root's tree reap. Anything else
- # (operator REPL, stray script) keeps the refusal.
+ # Pass 2: every non-backend holder must descend from an accepted orphan root
+ # (dies with the tree reap); anything else keeps the refusal.
root_set = {pid for pid, _start_time in roots}
for pid, _low in remaining:
if not root_set:
@@ -681,21 +589,11 @@ def _orphaned_desktop_backend_pids(
def _ledger_reapable_backend_pids(
matches: list[tuple[int, str, str]],
) -> list[int]:
- """PIDs positively identified by the spawn ledger as orphaned backends.
-
- The strongest rung: look each venv holder up in the machine spawn ledger
- (``hermes_cli.process_identity``) instead of inferring lineage from PPIDs
- or cmdline shape. A holder qualifies when ALL of:
-
- - its ``(pid, create_time)`` matches a live ledger entry (PID reuse
- cannot forge this pair);
- - the entry's purpose is a reapable backend kind (serve/dashboard/
- gateway — never interactive processes);
- - the entry's recorded SPAWNER is provably dead (``spawner_is_dead``).
+ """PIDs the spawn ledger positively identifies as orphaned backends; never raises.
- Safe in ANY update context — the process itself declared its supervisor
- and that supervisor is gone. Holders not in the ledger fall through to
- later rungs and never disqualify identified ones. Never raises.
+ Strongest rung (no PPID/cmdline inference): qualifies when ``(pid, create_time)`` matches a live ledger entry
+ (PID reuse can't forge it), purpose is a REAPABLE kind (never interactive), and the recorded SPAWNER is
+ provably dead. Safe in ANY context. Unlisted holders fall to later rungs and never disqualify identified ones.
"""
try:
from hermes_cli.process_identity import (
@@ -723,30 +621,13 @@ def _ledger_reapable_backend_pids(
def _handoff_reapable_backend_pids(
matches: list[tuple[int, str, str]],
) -> list[int] | None:
- """PIDs of Hermes ``serve``/``dashboard`` backends safe to reap during a
- GUI-updater hand-off, INCLUDING ones with a still-live parent.
-
- Complements ``_orphaned_desktop_backend_pids``, which returns ``None``
- (keep refusing) the moment ANY holder has a live parent. That produced a
- field incident: a Windows Desktop hand-off (``update --yes --gateway
- --force``) left a swarm of per-profile ``serve`` backends holding
- ``cryptography\\_rust.pyd``, several with a lingering parent (tearing-down
- Electron, or the launcher→worker chain mid-exit), so the orphan check
- disqualified the WHOLE set and the update hung for 12 minutes.
-
- The hand-off is the safe signal: with the update-incomplete marker claimed
- AND a ``--gateway`` run AND no live Desktop shim (``hermes.exe``), nothing
- legitimate supervises or respawns a ``serve`` backend from this venv (the
- Desktop tree-kills its backends and parks relaunch behind the marker,
- #50238). Any ``serve`` backend still holding the venv is a leak, live
- parent or not, and tree-reaping it is correct rather than a race.
-
- Guards: only Hermes backends (``hermes_cli.main`` + ``serve``/``dashboard``)
- qualify — a non-backend holder disqualifies the whole set → ``None``; the
- CALLER must have confirmed the hand-off gate above (outside it the stricter
- orphan-only path stands); psutil unavailable → ``None``. Returns backend
- root PIDs to tree-reap, or ``None`` to leave the decision to the caller's
- other rungs. Never raises.
+ """Backend PIDs safe to tree-reap during a GUI-updater hand-off, INCLUDING ones with a live parent; never raises.
+
+ ``_orphaned_desktop_backend_pids`` bails on ANY live parent (mid-teardown Electron, launcher->worker chain),
+ which hung a hand-off for 12 minutes. With the update-incomplete marker + ``--gateway`` + no live
+ ``hermes.exe`` shim, nothing legitimate supervises or respawns a ``serve`` from this venv, so survivors are
+ leaks. Only Hermes backends qualify — any non-backend holder, or no psutil -> ``None``. The CALLER must
+ have confirmed the hand-off gate; outside it the stricter orphan-only path stands.
"""
try:
import psutil # type: ignore
@@ -764,14 +645,11 @@ def _handoff_reapable_backend_pids(
try:
argv = " ".join(psutil.Process(int(pid)).cmdline()) or cmdline
except psutil.NoSuchProcess:
- # Exited between scan and classification — nothing to reap.
- continue
+ continue # exited — nothing to reap
except Exception:
pass
if not _is_backend(argv.lower()):
- # A non-backend holder during a hand-off is unexpected; refuse the
- # whole set rather than reap something we cannot justify.
- return None
+ return None # unexpected non-backend holder: refuse the whole set
roots.append(int(pid))
return roots or None
@@ -780,12 +658,9 @@ def _handoff_reapable_backend_pids(
def _stop_process_trees(
pids: list[int] | list[tuple[int, int]],
) -> None:
- """Force-stop each PID with its full child tree (Windows).
+ """Force-stop each PID with its full child tree (Windows); best effort, never raises.
- ``taskkill /T /F`` mirrors the Desktop's ``forceKillProcessTree`` and
- install.ps1's venv sweep: stopping only the parent can leave a managed
- ``.hermes-runtime`` interpreter child alive and holding the install open
- (#70026). Best effort; never raises.
+ ``taskkill /T /F``: stopping only the parent can leave a ``.hermes-runtime`` child holding the install open.
"""
from gateway.status import get_process_start_time
from hermes_cli._subprocess_compat import pid_is_hermes, windows_hide_flags
@@ -825,14 +700,11 @@ def _stop_process_trees(
def _looks_like_desktop_control_plane(cmdline: str) -> bool:
- """True for this-install ``hermes serve`` / ``hermes dashboard`` argv.
-
- That is the Desktop control plane, not the messaging gateway (serve and
- dashboard host no platform adapters, #92091); do not feed this into
- ``looks_like_gateway_command_line``. Token-based via the parser-derived
- subcommand classifier — never substring (#90778/#91869: ``kanban
- --preserve-cache`` contains "serve", ``-m dashboard chat`` contains
- " dashboard"). An undeterminable subcommand is NOT a control plane.
+ """True for this-install ``hermes serve`` / ``hermes dashboard`` argv (Desktop control plane).
+
+ Not the messaging gateway — don't feed into ``looks_like_gateway_command_line``. Token-based via the
+ parser-derived classifier, never substring (``kanban --preserve-cache``, ``-m dashboard chat``).
+ Undeterminable subcommand is NOT a control plane.
"""
if "hermes_cli.main" not in (cmdline or "").lower():
return False
@@ -840,16 +712,10 @@ def _looks_like_desktop_control_plane(cmdline: str) -> bool:
def _desktop_owns_gateway_lifecycle() -> bool:
- """True when Desktop currently supervises this install's control plane.
-
- The updater must not steal gateway start in that case: Desktop owns
- start/stop via ``/api/gateway/*``. This is *not* proof messaging is
- already served — a live serve process is the control plane, and the
- gateway is a detached sibling (#76129 / #92091).
+ """True when Desktop currently supervises this install's control plane (updater must not steal gateway start).
- Prefer the spawn ledger (owned identity). Fall back to the install-scoped
- venv-holder scan already used by the lock guard; an orphaned control-plane
- process (supervisor gone) does not count.
+ Not proof messaging is served: serve is the control plane, the gateway a detached sibling. Prefer the spawn
+ ledger; fall back to the venv-holder scan. An orphaned control plane (supervisor gone) does not count.
"""
from hermes_cli.update_cmd import _m
try:
@@ -878,9 +744,7 @@ def _desktop_owns_gateway_lifecycle() -> bool:
if not _looks_like_desktop_control_plane(cmdline):
continue
if psutil is None:
- # Cannot prove orphanhood; a live this-install control plane is
- # enough to refuse stealing gateway start.
- return True
+ return True # cannot prove orphanhood; a live control plane suffices
try:
proc = psutil.Process(int(pid))
parent = proc.parent()
@@ -971,12 +835,9 @@ def _stop_windows_gateway_service(
try:
current = float(psutil.Process(pid).create_time())
except (psutil.NoSuchProcess, psutil.ZombieProcess):
- # A vanished process is clear.
return False
except Exception:
- # AccessDenied or any unknown probe failure stays fail-closed
- # because the venv may still be locked.
- return True
+ return True # AccessDenied/unknown: fail closed, venv may still be locked
return abs(current - create_time) <= 0.001
alive = [
@@ -996,8 +857,7 @@ def _stop_windows_gateway_service(
return
_time.sleep(0.2)
if service.status() == "stopped":
- # Return only if the original processes are gone too; a lingering
- # matching-identity process means venv mutation is unsafe — fail closed.
+ # Lingering matching-identity processes make venv mutation unsafe — fail closed.
alive_after_stop = [
pid
for pid, create_time in expected_processes
@@ -1009,7 +869,6 @@ def _stop_windows_gateway_service(
f"{alive_after_stop}"
)
return
- # Timeout with the original descendants still alive — fail closed; venv mutation is unsafe.
raise RuntimeError(
f"Windows service {name} did not stop within {timeout:.0f}s; venv mutation unsafe."
)
@@ -1063,10 +922,8 @@ def _restore_windows_gateway_service(name: str, *, timeout: float = 60.0) -> Non
def _pause_windows_gateways_for_update() -> dict | None:
"""Stop running Windows gateways before mutating the checkout or venv.
- Windows scheduled/startup gateways run through pythonw.exe, so the generic
- hermes.exe concurrent-instance guard does not see them. They still import
- from the checkout and can keep files locked while ``git`` or ``uv`` updates
- the install. Stop only PIDs that the gateway discovery code identifies.
+ Scheduled/startup gateways run via pythonw.exe, invisible to the hermes.exe instance guard, yet keep files
+ locked during ``git``/``uv``. Stop only PIDs the gateway discovery code identifies.
"""
from hermes_cli.update_cmd import (
_desktop_owns_gateway_lifecycle,
@@ -1124,17 +981,11 @@ def _pause_windows_gateways_for_update() -> dict | None:
f"Could not discover Windows gateway PIDs before update: {exc}"
) from exc
if not running_pids:
- # No gateway is running, but an installed autostart entry (Scheduled
- # Task / Startup-folder login item) is an explicit "I want a gateway"
- # signal. A gateway that died between updates (e.g. its spawning
- # terminal closed) would otherwise stay down until next login, since
- # the resume path only relaunches gateways that were running. Cold-start
- # one after the update; gateway-less users get nothing forced on them.
- #
- # Exception: Desktop owns this install's gateway lifecycle (live
- # supervised serve/dashboard); a vestigial autostart entry is not the
- # owner, and spawning ``gateway run`` beside Desktop races ports/state
- # (#76129). The skip is ownership, not liveness (#92091).
+ # No gateway running, but an installed autostart entry is an explicit "I want a
+ # gateway" signal; a gateway that died between updates would otherwise stay down
+ # until next login (resume only relaunches what was running). Cold-start after update.
+ # Exception: Desktop owns the lifecycle — spawning ``gateway run`` beside it races
+ # ports/state. The skip is ownership, not liveness.
try:
if _desktop_owns_gateway_lifecycle():
logger.debug(
@@ -1177,11 +1028,8 @@ def _pause_windows_gateways_for_update() -> dict | None:
profiles[str(proc.profile)] = int(pid)
mapped_pids.append(int(pid))
_write_update_planned_stop_marker(Path(proc.path), int(pid))
- # Socket-first pause (#92091 step 2): ask the gateway to drain and exit
- # itself. A positive ACK means it runs its own graceful restart path
- # (same drain as SIGUSR1/service restarts) and releases venv handles on
- # exit. No answer (older gateway, no socket) → the marker poll /
- # force-kill ladder below behaves exactly as before.
+ # Socket-first pause: ask the gateway to drain and exit itself (ACK = its own
+ # graceful path). No answer (older gateway) -> marker poll / force-kill ladder below.
try:
from gateway.control_socket import pause_gateway_for_update
@@ -1193,15 +1041,9 @@ def _pause_windows_gateways_for_update() -> dict | None:
"Socket pause unavailable for gateway %s: %s", pid, exc
)
- # Resolve each mapped worker's venv-side launcher BEFORE draining: a
- # gracefully drained worker is gone when the wait returns, and a dead
- # pid's parent cannot be recovered (psutil raises NoSuchProcess). The
- # snapshot is stopped after the drain alongside the survivors.
- #
- # The drain targets the PID-file writer (uv-side worker); its parent is
- # usually the venv ``python.exe`` launcher, which keeps venv ``.pyd``
- # files mapped and is what ``_detect_venv_python_processes()`` reports.
- # Left alive, it trips the venv-holder guard though the gateway is stopped.
+ # Resolve venv-side launchers BEFORE draining: a dead worker's parent cannot be
+ # recovered (NoSuchProcess). The launcher keeps ``.pyd`` mapped and would trip the
+ # venv-holder guard after the gateway stopped; it is killed with the survivors.
launcher_pids = _m()._venv_launcher_ancestors(mapped_pids)
print("→ Stopping Windows gateway process(es) before updating Hermes...")
@@ -1210,9 +1052,8 @@ def _pause_windows_gateways_for_update() -> dict | None:
except Exception:
drain_timeout = 10.0
if socket_acks:
- # A socket-paused gateway drains its ACTIVE TURN before exiting; honor
- # the budget it declared (plus teardown grace) so a mid-turn gateway
- # isn't force-killed by a too-short wait.
+ # A socket-paused gateway drains its ACTIVE TURN first; honor its declared
+ # budget (+ teardown grace) so it isn't force-killed mid-turn.
try:
declared = max(
float(a.get("drain_timeout") or 0.0) for a in socket_acks
@@ -1234,10 +1075,8 @@ def _pause_windows_gateways_for_update() -> dict | None:
if pid not in profile_processes and pid not in service_gateway_pids
]
- # Snapshot each unmapped gateway's argv *before* force-killing it so
- # ``_resume_windows_gateways_after_update`` can replay it. Unmapped = no
- # profile→PID-file mapping (e.g. a Scheduled Task running ``pythonw.exe -m
- # hermes_cli.main gateway run``); without this they were never restarted (#50090).
+ # Snapshot unmapped gateways' argv *before* force-killing so resume can replay it.
+ # Unmapped = no profile->PID-file mapping (e.g. Scheduled Task ``pythonw.exe -m ...``).
unmapped: list[dict] = []
for pid in unmapped_pids:
argv = None
@@ -1247,9 +1086,8 @@ def _pause_windows_gateways_for_update() -> dict | None:
logger.debug("Could not capture argv for unmapped gateway %s: %s", pid, exc)
unmapped.append({"pid": int(pid), "argv": argv})
- # Stop drain survivors, unmapped gateways, and the pre-drain launcher
- # snapshot. ``terminate_pid(force=True)`` is a tree kill; a launcher that
- # already exited with its worker raises ProcessLookupError and is skipped.
+ # Tree-kill survivors, unmapped gateways, and pre-drain launchers; a launcher
+ # already gone with its worker raises ProcessLookupError and is skipped.
force_killed = []
for pid in sorted(set(survivors).union(unmapped_pids).union(launcher_pids)):
try:
@@ -1274,8 +1112,7 @@ def _pause_windows_gateways_for_update() -> dict | None:
f" → Stopped {len(unmapped_pids)} gateway process(es) without profile mapping"
)
if respawnable < len(unmapped_pids):
- # Some had no recoverable command line (psutil missing, access
- # denied, already gone): those still need a manual restart.
+ # No recoverable cmdline (psutil missing, access denied, gone): manual restart.
print(" Restart manually after update: hermes gateway run")
token = {
@@ -1285,9 +1122,8 @@ def _pause_windows_gateways_for_update() -> dict | None:
"unmapped": unmapped,
}
- # Stop SCM-supervised gateways only after every fallible step for ordinary
- # gateways is done; from here on any error restores attempted services and
- # already-paused ordinary gateways before aborting.
+ # Stop SCM services only after every fallible ordinary-gateway step; from here any
+ # error restores attempted services and already-paused gateways before aborting.
paused_services = []
current_service_name = None
try:
@@ -1347,22 +1183,11 @@ def _pause_windows_gateways_for_update() -> dict | None:
def _cold_start_windows_gateway_after_update() -> bool:
- """Start a fresh detached gateway after update when one is installed but down.
-
- Called from ``_resume_windows_gateways_after_update`` for the
- ``cold_start_if_installed`` case: no gateway was running at update start,
- but an autostart entry is installed. Unlike the relaunch paths (watch an
- old PID, respawn on exit) this is a direct spawn via the same
- hidden-console + breakaway path as ``hermes gateway start``
- (``gateway_windows._spawn_detached``).
-
- Best-effort and idempotent: re-checks that nothing is running first so a
- concurrent start (e.g. the autostart entry firing) can't duplicate.
-
- A successful ``Popen`` only proves the process was created, not that it
- survived (a job object denying breakaway kills it before it logs, #84185),
- so the success line is gated on the same post-spawn liveness poll every
- other ``_spawn_detached`` caller uses (``_report_gateway_start``).
+ """Direct-spawn a detached gateway after update for the ``cold_start_if_installed`` case (installed but down).
+
+ Uses ``gateway_windows._spawn_detached`` (same hidden-console + breakaway path as ``hermes gateway start``).
+ Idempotent: re-checks nothing is running so a concurrent autostart can't duplicate. A successful Popen
+ doesn't prove survival (a job object denying breakaway kills it), so success is gated on the liveness poll.
"""
from hermes_cli.update_cmd import _desktop_owns_gateway_lifecycle, _m
if not _m()._is_windows():
@@ -1375,9 +1200,7 @@ def _cold_start_windows_gateway_after_update() -> bool:
f"Could not load Windows gateway cold-start helpers: {exc}"
) from exc
- # Re-check liveness right before spawning — between pause and resume the
- # autostart entry may have already brought a gateway up, or a leftover
- # process may have re-registered. Don't double-start.
+ # Re-check liveness right before spawning: autostart may have brought one up. Don't double-start.
try:
if list(find_gateway_pids(all_profiles=True)):
return True
@@ -1415,9 +1238,8 @@ def _cold_start_windows_gateway_after_update() -> bool:
"✓ Gateway started via cold-start after update "
f"(PID: {', '.join(map(str, ready_pids))})"
)
- # Persist the PIDs this ✓ vouched for so a death AFTER the updater exits
- # (parent Job Object teardown, #91675) is reported by the next CLI
- # invocation instead of staying silent. Best-effort.
+ # Persist vouched PIDs so a death AFTER updater exit (Job Object teardown) is
+ # reported by the next CLI invocation. Best-effort.
try:
gateway_windows._write_start_attestation(
ready_pids, "cold-start after update"
@@ -1428,17 +1250,11 @@ def _cold_start_windows_gateway_after_update() -> bool:
def _refresh_windows_gateway_launchers() -> None:
- """Regenerate installed Windows gateway launcher scripts after update.
-
- The Scheduled Task / Startup-folder launchers (``gateway.cmd`` +
- ``gateway.vbs``) are written once at install time, so installs predating
- the hidden-console rework (aa2ae36c3f) kept launching via ``pythonw.exe``:
- conhost flashes (#54220/#56747) and, since #70344, a startup death with
- ``RuntimeError: sys.stderr is None`` (#71671).
+ """Regenerate installed Windows gateway launcher scripts after update; best-effort, never fails the update.
- The task's /TR points at a stable script path, so rewriting in place
- retargets it without schtasks (no UAC). ``_write_task_script`` is
- idempotent — a no-op for modern installs. Best-effort: never fails the update.
+ Launchers are written once at install, so old installs kept launching via ``pythonw.exe`` (conhost flashes,
+ ``sys.stderr is None`` death). The task's /TR points at a stable path, so rewriting in place retargets it
+ without schtasks/UAC. ``_write_task_script`` is idempotent.
"""
from hermes_cli.update_cmd import _m
if not _m()._is_windows():
@@ -1455,33 +1271,13 @@ def _refresh_windows_gateway_launchers() -> None:
def _refresh_bootstrap_cache_scripts(branch: str = "main") -> None:
- """Sync the installer's bootstrap-cache scripts from the fresh checkout.
-
- The Desktop GUI updater (``hermes-setup.exe``) runs
- ``$HERMES_HOME/bootstrap-cache/install-<ref>.ps1`` (or ``.sh``) for its
- repair/bootstrap stages. Installers built before the #67193 cache-refresh
- fix NEVER re-download a cached branch-ref script, so a stale
- ``install-main.ps1`` runs months-old code forever (the 2026-08-09
- incident: a cached script lacked the #81327 process-tree sweep and died on
- ``Access denied``). The binary has no self-update path.
-
- Overwriting the cached script for *branch* with the freshly pulled
- ``scripts/install.ps1`` / ``scripts/install.sh`` on every update turns
- that unconditional reuse into a feature. Post-#67193 installers
- re-download anyway, so for them this is a harmless pre-seed.
-
- Scope guards, mirroring ``install_script.rs``:
-
- - Only the cache key for the update-target *branch* is rewritten
- (``sanitize_ref``: non ``[A-Za-z0-9._-]`` chars become ``_``, so
- ``bb/gui`` → ``install-bb_gui.ps1``); sibling refs cache other
- branches' scripts and must not be clobbered.
- - Commit-SHA pins are immutable and never touched. ``is_valid_commit()``
- accepts **7–40** hex chars, so abbreviated pins count too; the sanitized
- *branch* must also not itself look like a pin (defense in depth).
-
- The .ps1 copy gets a UTF-8 BOM to match the installer's cache format
- (#67193). Best-effort: a failed refresh must never fail the update.
+ """Overwrite ``$HERMES_HOME/bootstrap-cache/install-<ref>.{ps1,sh}`` for *branch* from the fresh checkout.
+
+ Old ``hermes-setup.exe`` builds NEVER re-download a cached branch-ref script (and have no self-update), so a
+ stale one runs months-old code forever; refreshing turns that reuse into a feature (newer installers
+ re-download anyway). Guards mirror ``install_script.rs``: only the sanitized *branch* key is rewritten
+ (sibling refs untouched); commit-SHA pins (7-40 hex, incl. abbreviated) are immutable and skipped.
+ The .ps1 copy gets a UTF-8 BOM to match the cache format. Best-effort: never fails the update.
"""
from hermes_cli.update_cmd import _m
try:
@@ -1492,8 +1288,7 @@ def _refresh_bootstrap_cache_scripts(branch: str = "main") -> None:
return
# Mirror install_script.rs::sanitize_ref().
safe_ref = _re.sub(r"[^A-Za-z0-9._-]", "_", str(branch or "main"))
- # Mirror install_script.rs::is_valid_commit(): 7-40 hex chars is an
- # immutable commit pin — abbreviated SHAs included. Never rewrite.
+ # Mirror install_script.rs::is_valid_commit(): immutable commit pin, never rewrite.
if _re.fullmatch(r"[0-9a-fA-F]{7,40}", safe_ref):
return
refreshed = []
@@ -1506,8 +1301,7 @@ def _refresh_bootstrap_cache_scripts(branch: str = "main") -> None:
continue # this ref was never bootstrap-cached — nothing to heal
data = src.read_bytes()
if kind == "ps1" and not data.startswith(b"\xef\xbb\xbf"):
- # Match the installer's cache format: PowerShell needs the
- # UTF-8 BOM or localized/em-dash text mis-decodes (#67193).
+ # PowerShell needs the BOM or localized/em-dash text mis-decodes.
data = b"\xef\xbb\xbf" + data
if cached.read_bytes() == data:
continue # already current
@@ -1533,9 +1327,8 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:
token["resume_needed"] = False
return
- # Regenerate the persisted launcher scripts before respawning anything,
- # so a legacy pythonw-era Scheduled Task / Startup entry comes back on
- # current hidden-console design at the next login too.
+ # Regenerate launcher scripts before respawning so a legacy pythonw-era
+ # autostart entry comes back on the current design at next login too.
_m()._refresh_windows_gateway_launchers()
services = list(token.get("services") or [])
@@ -1611,17 +1404,12 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:
)
failed_profiles[str(profile)] = int(old_pid)
- # Surface the outcome on the token (#91277 plan-vs-execution
- # reconciliation): the git-update fleet reconciliation cross-checks every
- # planned runtime against relaunched_profiles etc., which this Windows
- # pause/resume never fed, so a correctly relaunched gateway was reported
- # "unaccounted" (loud warning + exit 1). The caller merges this into the
- # shared list. A profile whose relaunch failed is deliberately left off so
- # it still surfaces as unaccounted (Windows has no watcher to recover it).
+ # Feed the plan-vs-execution reconciliation (else a relaunched gateway is reported
+ # "unaccounted", exit 1). Failed relaunches are deliberately left off so they
+ # still surface (Windows has no watcher to recover them).
token["relaunched_profiles"] = relaunched
- # Respawn unmapped gateways (no profile→PID-file mapping, e.g. a Scheduled
- # Task) by replaying the argv we snapshotted before force-killing them.
+ # Respawn unmapped gateways by replaying the argv snapshotted before the kill.
unmapped_relaunched = 0
failed_unmapped = []
for entry in unmapped:
@@ -1648,13 +1436,9 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:
if failed_profiles or failed_unmapped:
raise RuntimeError("Could not restart every paused Windows gateway")
- # A truthy launch result only proves the detached watcher was created, not
- # that the respawned gateway survived: a parent Job Object denying
- # CREATE_BREAKAWAY_FROM_JOB kills it on updater teardown before it logs
- # anything, yet "✓ Restarting" was printed (#48820). Verify a stable
- # gateway exists with the same provisional-hit + confirmation-window poll
- # every other spawn path uses (#91675); all_profiles=True because the
- # resume covers the fleet.
+ # A truthy launch only proves the watcher was created; a parent Job Object denying
+ # CREATE_BREAKAWAY_FROM_JOB can kill the gateway on updater teardown. Verify with
+ # the same liveness poll every spawn path uses; all_profiles=True covers the fleet.
if relaunched or unmapped_relaunched:
try:
from hermes_cli import gateway_windows
@@ -1681,9 +1465,8 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:
raise RuntimeError(
"Windows gateway relaunch after update was not verified alive"
)
- # Persist the PIDs this ✓ vouches for so a death AFTER the updater
- # exits (parent Job Object teardown, #91675) is reported by the next
- # CLI invocation instead of staying silent. Best-effort.
+ # Persist vouched PIDs so a death AFTER updater exit is reported by the
+ # next CLI invocation. Best-effort.
try:
gateway_windows._write_start_attestation(
ready_pids, "post-update relaunch"
@@ -1705,12 +1488,8 @@ def _resume_windows_gateways_after_update(token: dict | None) -> None:
def _resume_windows_gateways_and_merge_outcome(outcome, _windows_gateway_resume, gateway_mode: bool):
- """Resume the gateways paused for a Windows update and fold that outcome into ``outcome``.
-
- Feeds the pause/resume token's relaunched/restarted/pending lists into
- the same bookkeeping the systemd/launchd phase populates so the
- plan-vs-execution reconciliation never reports a healthy Windows gateway
- as unaccounted. Best-effort: must never itself abort the update.
+ """Resume gateways paused for a Windows update and fold the token into ``outcome``'s systemd/launchd-style
+ bookkeeping so reconciliation never reports a healthy gateway as unaccounted. Must never abort the update.
"""
from hermes_cli.update_cmd import _m, _write_gateway_update_exit_code
try:
@@ -1726,11 +1505,7 @@ def _resume_windows_gateways_and_merge_outcome(outcome, _windows_gateway_resume,
_write_gateway_update_exit_code(False)
if isinstance(_windows_gateway_resume, dict):
- # Fold the Windows pause/resume outcome into the same bookkeeping
- # the systemd/launchd phase fills, so the #91277 reconciliation
- # doesn't flag a healthy Windows gateway as "unaccounted". Genuinely
- # failed relaunches are left out of the token so they still surface.
- # Best-effort: must never abort the update.
+ # Failed relaunches are absent from the token so they still surface. Best-effort.
try:
for _win_profile in _windows_gateway_resume.get("relaunched_profiles") or []:
if _win_profile not in outcome.relaunched_profiles:
@@ -1778,13 +1553,11 @@ def _resume_windows_gateways_and_merge_outcome(outcome, _windows_gateway_resume,
def _clear_windows_venv_holders_or_exit(args, gateway_mode: bool, _windows_gateway_resume):
- """Windows: stop every venv-python holder we can positively identify, else exit 2.
+ """Windows: stop every venv-python holder we can positively identify, else resume paused gateways and exit 2.
- Rungs, in order: leftover pausable gateways -> ledger-identified orphaned
- backends -> orphaned Desktop backends -> ledger-identified manual serve
- (relaunched at exit on the same bind) -> GUI-updater hand-off leaks.
- Anything still holding the venv afterwards is refused (the sync would
- corrupt against a locked .pyd) and the paused gateways are resumed.
+ Rungs in order: leftover pausable gateways -> ledger orphaned backends -> orphaned Desktop backends ->
+ ledger manual serve (relaunched at exit on the same bind) -> GUI hand-off leaks. Remaining holders are
+ refused (the sync would corrupt against a locked .pyd).
"""
from hermes_cli.update_cmd import _m, _record_update_step, _refuse_gateway_ancestor_tree_kill
_venv_holders = _m()._detect_venv_python_processes()
@@ -1798,9 +1571,8 @@ def _clear_windows_venv_holders_or_exit(args, gateway_mode: bool, _windows_gatew
_windows_gateway_resume
)
sys.exit(2)
- # Remaining holders are gateways the pause machinery owns
- # (supervisor respawn in the pause→guard window, or an unmapped
- # spawn path). Stop and re-check; the post-update resume brings them back.
+ # Gateways the pause machinery owns (respawned in the pause->guard window or
+ # unmapped spawn path): stop and re-check; post-update resume brings them back.
from gateway.status import get_process_start_time, terminate_pid
print(
@@ -1822,11 +1594,8 @@ def _clear_windows_venv_holders_or_exit(args, gateway_mode: bool, _windows_gatew
_time.sleep(1.0)
_venv_holders = _m()._detect_venv_python_processes()
if _venv_holders:
- # Positive-identity rung (runs FIRST, any update context): holders
- # the spawn ledger proves are orphaned Hermes backends — the
- # process self-registered (pid, create_time, purpose, spawner) at
- # startup and its recorded spawner is provably dead. No PPID
- # archaeology, no hand-off contract required.
+ # Positive-identity rung (any context): spawn ledger proves the holder is an
+ # orphaned backend (self-registered, spawner provably dead). No PPID archaeology.
_ledger_backends = _m()._ledger_reapable_backend_pids(_venv_holders)
if _ledger_backends:
print(
@@ -1839,11 +1608,8 @@ def _clear_windows_venv_holders_or_exit(args, gateway_mode: bool, _windows_gatew
if _venv_holders:
_orphan_backends = _m()._orphaned_desktop_backend_pids(_venv_holders)
if _orphan_backends:
- # Remaining holders are Desktop `serve` backends whose app is
- # GONE (Electron lost the SIGTERM race on teardown). Nothing
- # respawns an orphan, so reap the tree and re-check. Backends
- # with a live Desktop never reach here (returns None) — the app
- # would just respawn what we kill, so that path keeps refusing.
+ # Desktop `serve` backends whose app is GONE: nothing respawns an orphan, so
+ # reap the tree. Live-Desktop backends return None and keep the refusal.
print(
f" ⚠ {len(_orphan_backends)} orphaned Desktop backend "
"process(es) still hold the venv; stopping their trees"
@@ -1852,11 +1618,9 @@ def _clear_windows_venv_holders_or_exit(args, gateway_mode: bool, _windows_gatew
_time.sleep(1.0)
_venv_holders = _m()._detect_venv_python_processes()
if _venv_holders:
- # Manual serve/dashboard rung (#63206): a `hermes serve --host <ip>`
- # powering a REMOTE Desktop used to dead-end the update with exit 2.
- # Ledger identity only (spawner not alive; Desktop-owned backends
- # keep the refusal). Stop them and register an idempotent atexit
- # relaunch on the SAME host/port/profile — success or failure.
+ # Manual serve/dashboard rung (e.g. `hermes serve --host <ip>` for a REMOTE Desktop):
+ # ledger identity only (spawner dead; Desktop-owned keep the refusal). Stop and
+ # register an idempotent atexit relaunch on the SAME host/port/profile — success or failure.
_serve_entries = _m()._ledger_manual_serve_holders(_venv_holders)
if _serve_entries:
print(
@@ -1884,20 +1648,15 @@ def _clear_windows_venv_holders_or_exit(args, gateway_mode: bool, _windows_gatew
_time.sleep(1.0)
_venv_holders = _m()._detect_venv_python_processes()
if _venv_holders:
- # Final rung: a GUI-updater hand-off (`update --gateway --force` with
- # the update-incomplete marker) means the Desktop is contractually
- # gone and nothing legitimate respawns a `serve` backend. The
- # orphan-only reap bails on ANY live parent (mid-teardown Electron,
- # launcher→worker chain), which hung updates; in hand-off context
- # surviving backends are leaks regardless — reap by cmdline.
+ # Final rung: in a GUI hand-off (`--gateway` + update-incomplete marker) the Desktop
+ # is contractually gone; surviving `serve` backends are leaks even with a live
+ # parent (which made the orphan-only rung bail and hang) — reap by cmdline.
_handoff = False
try:
_handoff = bool(getattr(args, "gateway", False)) and _m()._update_marker_path().exists()
except Exception:
_handoff = False
- # Fail closed: if we cannot positively verify the shim state
- # (scripts dir unresolvable, detection raised), assume a live
- # shim exists and keep refusing rather than reap.
+ # Fail closed: unverifiable shim state is treated as a live shim (keep refusing).
_no_live_shim = False
try:
_scripts_dir = _m()._venv_scripts_dir()
diff --git a/tests/hermes_cli/test_update_fetch_failure_classifier.py b/tests/hermes_cli/test_update_fetch_failure_classifier.py
index dfc6e1bcb5f..883ac3639ba 100644
--- a/tests/hermes_cli/test_update_fetch_failure_classifier.py
+++ b/tests/hermes_cli/test_update_fetch_failure_classifier.py
@@ -105,7 +105,10 @@ def test_update_network_git_calls_never_prompt_for_credentials():
# configured so a private-fork origin still authenticates.
assert "GIT_CONFIG_COUNT" not in kw["env"] or kw["env"]["GIT_CONFIG_COUNT"] == os.environ.get("GIT_CONFIG_COUNT")
- src = inspect.getsource(update_cmd)
+ from hermes_cli import update_cmd_git
+
+ # Network git calls live in the origin (``_git_run``) and the split git module.
+ src = inspect.getsource(update_cmd) + inspect.getsource(update_cmd_git)
# Every subprocess.run(...) whose argv is a fetch/pull must spread the kwargs.
calls = []
for m in re.finditer(r"subprocess\.run\(", src):
diff --git a/tests/hermes_cli/test_update_modified_notice.py b/tests/hermes_cli/test_update_modified_notice.py
index ec5453260ac..1dfd2272d46 100644
--- a/tests/hermes_cli/test_update_modified_notice.py
+++ b/tests/hermes_cli/test_update_modified_notice.py
@@ -19,6 +19,8 @@ from pathlib import Path
import hermes_cli.main as main_mod
import hermes_cli.update_cmd as update_mod
+import hermes_cli.update_cmd_maint as update_maint_mod
+import hermes_cli.update_cmd_zip as update_zip_mod
_COUNT_RE = re.compile(r"user-modified \(kept\)")
@@ -26,11 +28,11 @@ _HINT_RE = re.compile(r"hermes skills list-modified")
def _source_lines() -> list[str]:
- # The update pipeline was extracted to hermes_cli/update_cmd.py
- # (main.py decomposition); scan both homes of the notice.
+ # The update pipeline was extracted to hermes_cli/update_cmd.py and then
+ # split into update_cmd_*.py; scan every home of the notice.
return [
line
- for mod in (main_mod, update_mod)
+ for mod in (main_mod, update_mod, update_maint_mod, update_zip_mod)
for line in Path(mod.__file__).read_text(encoding="utf-8").splitlines()
]
diff --git a/tests/test_managed_runtime_resolution.py b/tests/test_managed_runtime_resolution.py
index e3943e351ac..4aa8158980c 100644
--- a/tests/test_managed_runtime_resolution.py
+++ b/tests/test_managed_runtime_resolution.py
@@ -64,11 +64,11 @@ _ALLOWED: dict[tuple[str, str], str] = {
"can only run what is on that subshell's PATH, which local.py populates "
"with the managed dirs — so PATH is the correct question to ask here."
),
- ("hermes_cli/update_cmd.py", "uv"): (
+ ("hermes_cli/update_cmd_deps.py", "uv"): (
"Termux fallback: a pkg-installed uv lands on PATH but not in the "
"managed bin dir, and it is checked only after resolve_uv() misses."
),
- ("hermes_cli/update_cmd.py", "npm"): (
+ ("hermes_cli/update_cmd_deps.py", "npm"): (
"WSL diagnostic: deliberately inspects what PATH resolves so it can "
"warn that the only reachable npm is the Windows one."
),