Skip to content

The agent that grows with you

fix(update): freeze shipped updater imports across full history

ethernet16e99423d97b
diff --git a/gateway/status.py b/gateway/status.py
index 3d62d7cfa91..05f7a8932bb 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -46,6 +46,11 @@ _gateway_running_pid_cache: dict[tuple[str, bool, bool], tuple[float, tuple, Opt
logger = logging.getLogger(__name__)
+def profile_flag_value(command: str) -> Optional[str]:
+ # Shim to suppress old updater work until relaunch. Do not select a profile.
+ return None
+
+
class StormInfo(NamedTuple):
"""Respawn-storm check result: start count, window, and backoff to sleep."""
diff --git a/hermes_cli/_subprocess_compat.py b/hermes_cli/_subprocess_compat.py
index 4e238738a40..2a3130c913d 100644
--- a/hermes_cli/_subprocess_compat.py
+++ b/hermes_cli/_subprocess_compat.py
@@ -13,7 +13,7 @@ import re
import shutil
import subprocess
import sys
-from typing import Mapping, Sequence
+from typing import Mapping, NoReturn, Sequence
__all__ = [
"IS_WINDOWS",
@@ -50,6 +50,13 @@ _DIFF_RENDERING_SUBCOMMANDS = frozenset({"diff", "show", "log", "blame"})
_GIT_VALUE_OPTS = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"}
+def run(cmd, **kwargs) -> NoReturn:
+ # Shim to suppress old updater work until relaunch. Do not start its installer.
+ from hermes_cli._old_updater import stop_for_relaunch
+
+ stop_for_relaunch()
+
+
def harden_git_argv(args: Sequence[str]) -> list[str]:
"""Copy of subcommand-first git *args* (no leading ``"git"``) with :data:`NO_DRIVER_DIFF_FLAGS`
inserted right after a diff-rendering subcommand; other subcommands are returned unchanged.
diff --git a/hermes_cli/build_info.py b/hermes_cli/build_info.py
new file mode 100644
index 00000000000..978f3944e68
--- /dev/null
+++ b/hermes_cli/build_info.py
@@ -0,0 +1,6 @@
+"""Shims to suppress old updater work until relaunch. Live identity uses version_info."""
+
+
+def get_code_identity(refresh: bool = False) -> dict:
+ # Shim to suppress old updater work until relaunch, not certify the new checkout.
+ return {"sha": None, "short_sha": None, "version": None, "source": "unknown"}
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index d93cd72687d..71a6ddae7e4 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -713,6 +713,35 @@ from hermes_cli.main_provider_setup import (
_prompt_provider_choice,
_remove_custom_provider,
)
+# Frozen external updater API: old in-memory siblings still import these names
+# after a checkout swap. Keep their inert shims separate from live launch helpers.
+from hermes_cli.old_updater_main import (
+ ShimQuarantineError,
+ _BYTECODE_FINGERPRINT_FILE,
+ _desktop_stamp_path,
+ _detect_broken_lazy_refresh_imports,
+ _expected_windows_pe_machines,
+ _hermes_exe_shims,
+ _insert_python_pin,
+ _interpreter_scripts_dir,
+ _load_installable_optional_extras,
+ _parse_pe_machine,
+ _quarantine_running_hermes_exe,
+ _repair_broken_lazy_refresh_imports,
+ _resolve_install_target_python,
+ _restore_quarantined_exes,
+ _run_install_with_heartbeat,
+ _run_package_only_install,
+ _run_quarantined_install,
+ _run_with_idle_timeout,
+ _self,
+ _verify_console_scripts_installed,
+ _verify_core_dependencies_installed,
+ _web_ui_build_needed,
+ _windows_native_machine,
+ _windows_shim_in_process_chain,
+ _write_web_ui_build_stamp,
+)
from hermes_cli.main_install_repair import _cleanup_quarantined_exes
from hermes_cli.main_install_repair import ( # frozen updater surface: update_cmd*.py resolve these via _m()
_UPDATE_REEXEC_ENV,
diff --git a/hermes_cli/managed_uv.py b/hermes_cli/managed_uv.py
index c8225d175ee..0ec6dd0de8b 100644
--- a/hermes_cli/managed_uv.py
+++ b/hermes_cli/managed_uv.py
@@ -11,6 +11,11 @@ from typing import NoReturn
from hermes_cli._old_updater import stop_for_relaunch
+def _reload_hermes_constants() -> None:
+ # Shim to suppress old updater work until relaunch. Never re-execute live globals.
+ return None
+
+
def ensure_uv(*args, **kwargs) -> NoReturn:
# Shim to stop the old updater doing work until relaunch. Older releases
# expect a tuple, newer ones a path. Exit before either can consume it.
diff --git a/hermes_cli/old_updater_main.py b/hermes_cli/old_updater_main.py
new file mode 100644
index 00000000000..56a6e6ca782
--- /dev/null
+++ b/hermes_cli/old_updater_main.py
@@ -0,0 +1,159 @@
+"""Frozen main.py imports for updater code still running after a checkout swap.
+
+These are not the live helpers in main_desktop, main_install_repair or
+main_web_build. Returning from an old installer can trigger a retry or report
+success, so those call paths stop for relaunch instead.
+"""
+
+from pathlib import Path
+from typing import NoReturn
+
+from hermes_cli._old_updater import stop_for_relaunch
+
+
+# Shim to stop the old updater doing work until relaunch. Retain the filename
+# as data only, without recording a fingerprint or replacing the live recorder.
+_BYTECODE_FINGERPRINT_FILE = ".bytecode-fingerprint"
+
+
+class ShimQuarantineError(RuntimeError):
+ # Shim to stop the old updater doing work until relaunch. Preserve the
+ # historical exception payload without performing or claiming quarantine.
+ def __init__(self, failed_shims: list[str]):
+ self.failed_shims = list(failed_shims)
+ super().__init__("could not quarantine live shim(s): " + ", ".join(self.failed_shims))
+
+
+def _desktop_stamp_path() -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not select a build stamp.
+ stop_for_relaunch()
+
+
+def _detect_broken_lazy_refresh_imports(
+ install_cmd_prefix: list[str], *, env: dict[str, str] | None = None,
+) -> None:
+ # Shim to stop the old updater doing work until relaunch: unknown, not healthy [].
+ return None
+
+
+def _expected_windows_pe_machines() -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not approve a binary.
+ stop_for_relaunch()
+
+
+def _hermes_exe_shims(scripts_dir: Path) -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not select files to rename.
+ stop_for_relaunch()
+
+
+def _insert_python_pin(args: list[str]) -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not prepare an install.
+ stop_for_relaunch()
+
+
+def _interpreter_scripts_dir() -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not target live launchers.
+ stop_for_relaunch()
+
+
+def _load_installable_optional_extras(group: str = "all") -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not select dependency retries.
+ stop_for_relaunch()
+
+
+def _parse_pe_machine(path: Path) -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not trigger a binary fallback.
+ stop_for_relaunch()
+
+
+def _quarantine_running_hermes_exe(
+ scripts_dir: Path, *, max_attempts: int = 4, failed_out: list[str] | None = None,
+) -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not rename live executables.
+ stop_for_relaunch()
+
+
+def _repair_broken_lazy_refresh_imports(
+ install_cmd_prefix: list[str], packages: list[str], *, env: dict[str, str] | None = None,
+) -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not repair or claim health.
+ stop_for_relaunch()
+
+
+def _resolve_install_target_python(
+ install_cmd_prefix: list[str], env: dict[str, str] | None,
+) -> None:
+ # Shim to stop the old updater doing work until relaunch: no interpreter to probe.
+ return None
+
+
+def _restore_quarantined_exes(moved: list[tuple[Path, Path]]) -> None:
+ # Shim to stop the old updater doing work until relaunch, including finally-block renames.
+ return None
+
+
+def _run_install_with_heartbeat(
+ cmd: list[str], *, env: dict[str, str] | None = None, heartbeat_interval_seconds: int = 30,
+) -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not run pip/uv or report success.
+ stop_for_relaunch()
+
+
+def _run_package_only_install(cmd: list[str], *, env: dict[str, str] | None = None) -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not run a package-only retry.
+ stop_for_relaunch()
+
+
+def _run_quarantined_install(
+ cmd: list[str], *, env: dict[str, str] | None = None, scripts_dir: Path | None = None,
+ strict_quarantine: bool = False,
+) -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not install or enable fallback.
+ stop_for_relaunch()
+
+
+def _run_with_idle_timeout(
+ cmd: list[str], cwd: Path, *, idle_timeout_seconds: int = 180, indent: str = " ",
+ env: dict[str, str] | None = None,
+) -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not build or synthesize success.
+ stop_for_relaunch()
+
+
+def _self() -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not expose live process scans.
+ stop_for_relaunch()
+
+
+def _verify_console_scripts_installed(
+ install_cmd_prefix: list[str], *, env: dict[str, str] | None = None,
+) -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not reinstall entry points.
+ stop_for_relaunch()
+
+
+def _verify_core_dependencies_installed(
+ install_cmd_prefix: list[str], *, env: dict[str, str] | None = None, group: str = "all",
+) -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not reinstall missing packages.
+ stop_for_relaunch()
+
+
+def _web_ui_build_needed(web_dir: Path) -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not claim an unbuilt UI is current.
+ stop_for_relaunch()
+
+
+def _windows_native_machine() -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not approve a fallback architecture.
+ stop_for_relaunch()
+
+
+def _windows_shim_in_process_chain() -> NoReturn:
+ # Shim to stop the old updater doing work until relaunch, not spawn an install handoff.
+ stop_for_relaunch()
+
+
+def _write_web_ui_build_stamp(project_root: Path, web_dir: Path) -> None:
+ # Shim to stop the old updater doing work until relaunch. Never write a success marker.
+ return None
diff --git a/hermes_cli/tools_config.py b/hermes_cli/tools_config.py
index 048d2ab13ba..a10dd1fc084 100644
--- a/hermes_cli/tools_config.py
+++ b/hermes_cli/tools_config.py
@@ -4,7 +4,7 @@ import json as _json
import logging
import os
from pathlib import Path
-from typing import Dict, List, Optional, Set
+from typing import Dict, List, NoReturn, Optional, Set
from hermes_cli.cli_output import print_info as _print_info
from hermes_cli.colors import Colors, color
@@ -36,6 +36,16 @@ from hermes_cli.tools_config_providers import ( # noqa: F401
from hermes_cli.tools_config_mcp import ( # noqa: F401
_configure_mcp_tools_interactive, _apply_toolset_change, _apply_mcp_change, tools_disable_enable_command)
+
+def _pip_install(
+ args: List[str], *, timeout: int = 300, capture_output: bool = True
+) -> NoReturn:
+ # Shim to suppress old updater work until relaunch, not install or report success.
+ from hermes_cli._old_updater import stop_for_relaunch
+
+ stop_for_relaunch()
+
+
logger = logging.getLogger(__name__)
# Platforms already warned about an all-invalid platform_toolsets list (warn once, not per resolution).
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 3ef5154fb75..70de3d58218 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -115,6 +115,11 @@ from hermes_cli.update_cmd_maint import ( # noqa: F401
logger = logging.getLogger(__name__)
+def get_default_hermes_root() -> NoReturn:
+ # Shim to suppress old updater work until relaunch. No path is safe to invent.
+ stop_for_relaunch()
+
+
def _ensure_uv_for_termux(pip_cmd: list[str]) -> NoReturn:
# Shim to stop the old updater doing work until relaunch, not bootstrap uv.
stop_for_relaunch()
diff --git a/plugins/platforms/dingtalk/adapter.py b/plugins/platforms/dingtalk/adapter.py
index 1d73eae0676..2afb086e3ea 100644
--- a/plugins/platforms/dingtalk/adapter.py
+++ b/plugins/platforms/dingtalk/adapter.py
@@ -101,8 +101,8 @@ def ensure_dingtalk_deps() -> bool:
if DINGTALK_STREAM_AVAILABLE and HTTPX_AVAILABLE:
return True
try:
- from tools.lazy_deps import ensure as _lazy_ensure
- _lazy_ensure("platform.dingtalk", prompt=False)
+ from pm.extras import ensure_import
+ ensure_import("dingtalk")
import dingtalk_stream as _ds, httpx as _httpx # noqa: E401
from dingtalk_stream import ChatbotMessage as _CM
from dingtalk_stream.frames import CallbackMessage as _CBM, AckMessage as _AM
diff --git a/scripts/audit-old-updater-imports.py b/scripts/audit-old-updater-imports.py
index 33cf2c54b19..0b9d0afba79 100644
--- a/scripts/audit-old-updater-imports.py
+++ b/scripts/audit-old-updater-imports.py
@@ -33,10 +33,10 @@ takes one path. It never enters the diverged-history reset, the Windows
rollback, or the ZIP fallback, so it reports a SMALLER
surface than reality.
-THE DYNAMIC PATTERNS THAT MATTER (and why they are not missed)
+THE DYNAMIC PATTERNS THAT MATTER
--------------------------------------------------------------
-Plain import analysis misses three things this flow really does, all of
-which are resolved here because they are all spelled with literals:
+Plain import analysis misses three things this flow does. Literal targets
+are recorded. Unresolved expressions remain visible for manual review:
* ``importlib.reload(m)`` — RE-EXECUTES the new file in the old process.
This is the most dangerous load in the whole flow and it looks like
@@ -51,6 +51,24 @@ which are resolved here because they are all spelled with literals:
* ``importlib.import_module(x)`` with a non-literal argument — cannot be
resolved statically. Reported as UNRESOLVED rather than ignored.
+HISTORY COVERAGE AND STATIC LIMITS
+---------------------------------
+History discovery inventories every reachable origin/main commit, including
+merge parents, and scans every distinct Python blob for entrypoint ASTs.
+All historical versions of discovered paths, updater siblings, renamed seed
+helpers, and statically referenced imported functions are audited. Witness
+commits identify versions; unchanged descendants are not re-parsed.
+
+This is NOT a complete Python call-graph proof. Reflection, computed module
+names, arbitrary alias reassignment, class/instance dispatch, and module
+objects passed through opaque callbacks require manual review. Known helper
+modules are conservatively entered wholesale; other modules are followed by
+selected function names, not every unrelated command. FIRST_PARTY_ROOTS
+bounds imports of interest. The report and freeze retain unresolved edges.
+Syntax/decoding failures abort rather than shrink coverage. The special case
+of committed merge markers audits every arm combination and records recovery;
+this is conservative archaeology, not a claim that broken source could run.
+
Usage:
python scripts/audit-old-updater-imports.py # report
python scripts/audit-old-updater-imports.py --json
@@ -63,23 +81,37 @@ from __future__ import annotations
import argparse
import ast
import json
+import re
import subprocess
+import sys
+import tokenize
+from collections import deque
from dataclasses import dataclass, field
+from io import BytesIO
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
-# The update flow has lived at both of these paths.
+# Known entrypoint seeds, not a history path filter. Discovery also scans
+# every reachable Python blob for entrypoint definitions at other addresses.
UPDATE_MODULE_CANDIDATES = (
- "hermes_cli/update_cmd.py",
+ "hermes_cli/main.py",
"hermes_cli/subcommands/update.py",
+ "hermes_cli/update_cmd.py",
)
-# Helpers the update flow calls into after the tree moves. Every function
-# in these is treated as post-swap.
+# Known post-swap helpers: every function counts. Historical filenames are
+# augmented by rename edges, updater siblings from the HISTORY inventory,
+# and statically referenced imported functions (including extractions).
+# This list is a conservative seed, not the universe of audited paths.
POST_SWAP_HELPER_MODULES = (
"hermes_cli/post_update.py",
"hermes_cli/update_lock.py",
+ # Read every historical home of these helpers.
+ "hermes_cli/backup.py",
+ "hermes_cli/backup_restore.py",
+ "hermes_cli/managed_uv.py",
+ "hermes_cli/psutil_android.py",
# pm era: `hermes update` drives the store through the pm package. A pm
# module imported BEFORE the swap keeps running as old code afterwards,
# so its lazy loads resolve against the NEW tree -- same failure shape
@@ -94,6 +126,15 @@ POST_SWAP_HELPER_MODULES = (
"pm/paths.py",
"pm/registry.py",
"pm/store.py",
+ "pm/operations.py",
+ "pm/build_operations.py",
+)
+
+# Historical module-object calls that need explicit review, not a guessed
+# receiver type. Keep the witness so regeneration cannot discard the contract.
+REVIEWED_DYNAMIC_LOADS = (
+ ("hermes_cli._subprocess_compat", "run", "2ecca1e7d3e7",
+ "hermes_cli/managed_uv.py:_install_uv_windows"),
)
# Only OUR packages matter: a third-party import is pinned by the
@@ -155,14 +196,13 @@ class Analysis:
requirements: list[Requirement] = field(default_factory=list)
unresolved: list[str] = field(default_factory=list)
reachable: set[str] = field(default_factory=set)
+ dependencies: dict[str, set[str]] = field(default_factory=dict)
+ parse_recoveries: set[str] = field(default_factory=set)
-def _function_table(tree: ast.AST) -> dict[str, _AnyFunc]:
- table: dict[str, _AnyFunc] = {}
- for node in ast.walk(tree):
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
- table.setdefault(node.name, node)
- return table
+def _function_definitions(tree: ast.AST) -> list[_AnyFunc]:
+ return [node for node in ast.walk(tree)
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))]
def _called_names(node: ast.AST) -> set[str]:
@@ -211,44 +251,30 @@ def _string_constants(tree: ast.AST) -> dict[str, list[str]]:
return out
-def _guarded_spans(func: _AnyFunc) -> list[tuple[int, int]]:
- """Line spans of ``try`` bodies whose handlers catch an import failure.
+def _guarded_spans(func: _AnyFunc, failure: str = "ImportError") -> list[tuple[int, int]]:
+ """Try bodies whose first matching handler swallows this load failure.
- ``except Exception``, ``except ImportError`` and bare ``except``
- all swallow a missing name; a load inside such a body has a fallback
- arm in the OLD code and cannot brick the update by itself.
+ AttributeError cannot guard an import, and ModuleNotFoundError cannot
+ guard a missing from-import symbol. A handler that raises is not a
+ fallback, even if it catches the right exception.
"""
+ caught_by = {failure, "Exception", "BaseException"}
+ if failure == "ModuleNotFoundError":
+ caught_by.add("ImportError")
spans: list[tuple[int, int]] = []
for node in ast.walk(func):
if not isinstance(node, ast.Try):
continue
- catches = False
for handler in node.handlers:
- if handler.type is None:
- catches = True
- elif isinstance(handler.type, ast.Name) and handler.type.id in (
- "Exception",
- "BaseException",
- "ImportError",
- "ModuleNotFoundError",
- "AttributeError",
- ):
- catches = True
- elif isinstance(handler.type, ast.Tuple):
- for el in handler.type.elts:
- if isinstance(el, ast.Name) and el.id in (
- "Exception",
- "ImportError",
- "ModuleNotFoundError",
- "AttributeError",
- ):
- catches = True
- if catches and node.body:
- first = node.body[0].lineno
- last = max(
- getattr(stmt, "end_lineno", stmt.lineno) for stmt in node.body
+ types = handler.type.elts if isinstance(handler.type, ast.Tuple) else [handler.type]
+ matches = handler.type is None or any(
+ isinstance(t, ast.Name) and t.id in caught_by for t in types
)
- spans.append((first, last))
+ if not matches:
+ continue
+ if not any(isinstance(n, ast.Raise) for n in ast.walk(handler)) and node.body:
+ spans.append((node.body[0].lineno, max(stmt.end_lineno or stmt.lineno for stmt in node.body)))
+ break
return spans
@@ -260,13 +286,17 @@ def _requirements_in(
"""Every name *func* needs from the new tree, plus what we could not read."""
reqs: list[Requirement] = []
unresolved: list[str] = []
- guarded_spans = _guarded_spans(func)
+ guarded_spans = {
+ failure: _guarded_spans(func, failure)
+ for failure in ("ImportError", "ModuleNotFoundError", "AttributeError")
+ }
- def _is_guarded(node: ast.AST) -> bool:
+ def _is_guarded(node: ast.AST, kind: str, symbol: str | None) -> bool:
line = getattr(node, "lineno", None)
if line is None:
return False
- return any(first <= line <= last for first, last in guarded_spans)
+ failure = "AttributeError" if kind == "getattr" else "ImportError" if symbol else "ModuleNotFoundError"
+ return any(first <= line <= last for first, last in guarded_spans[failure])
def add(
module: str, symbol: str | None, kind: str, node: ast.AST
@@ -279,16 +309,17 @@ def _requirements_in(
kind,
func.name,
source_file,
- guarded=_is_guarded(node),
+ guarded=_is_guarded(node, kind, symbol),
)
)
for child in ast.walk(func):
# ── plain lazy imports ─────────────────────────────────────────
if isinstance(child, ast.ImportFrom):
- if not child.level and child.module:
+ module = _import_module(child, source_file)
+ if module:
for alias in child.names:
- add(child.module, alias.name, "import", child)
+ add(module, alias.name, "import", child)
elif isinstance(child, ast.Import):
for alias in child.names:
add(alias.name, None, "import", child)
@@ -403,127 +434,425 @@ def _getattr_on_bound_locals(
module = bound[holder.id]
if _first_party(module):
out.append(
- Requirement(module, attr.value, "getattr", func.name, source_file)
+ Requirement(
+ module, attr.value, "getattr", func.name, source_file,
+ guarded=any(first <= node.lineno <= last for first, last in _guarded_spans(func, "AttributeError")),
+ )
)
return out
-def analyse(source: str, source_file: str, *, entrypoints: bool) -> Analysis | None:
- """Requirements of one version of one file.
+class AuditError(RuntimeError):
+ """An incomplete audit must never be mistaken for a smaller contract."""
- *entrypoints* selects the reachability seed: an update module starts
- from ``UPDATE_ENTRYPOINTS``; a post-swap helper module is entered
- wholesale, so every function in it counts.
+
+def _parse_variants(source: str, context: str) -> tuple[list[ast.Module], bool]:
+ """A committed conflict is audited as ALL arm combinations, never skipped.
+
+ Actual history contains merge markers in config.py. Both resolutions
+ can be analyzed without inventing syntax or choosing a winner. Other
+ syntax errors, malformed markers, and excessive combinations fail closed.
"""
try:
- tree = ast.parse(source)
- except SyntaxError:
- return None
+ return [ast.parse(source, filename=context)], False
+ except (SyntaxError, ValueError) as original:
+ if not re.search(r"^<<<<<<< ", source, re.MULTILINE):
+ raise AuditError(f"Cannot parse {context}: {original}") from original
+ variants = [""]
+ arms: list[str] | None = None
+ for line in source.splitlines(keepends=True):
+ if line.startswith("<<<<<<< "):
+ if arms is not None:
+ raise AuditError(f"Nested conflict in {context}") from original
+ arms = [""]
+ elif line.startswith("||||||| ") or line.rstrip("\r\n") == "=======":
+ if arms is None:
+ raise AuditError(f"Malformed conflict in {context}") from original
+ arms.append("")
+ elif line.startswith(">>>>>>> "):
+ if arms is None or len(arms) < 2 or len(variants) * len(arms) > 64:
+ raise AuditError(f"Malformed or excessive conflict variants in {context}") from original
+ variants = [prefix + arm for prefix in variants for arm in arms]
+ arms = None
+ elif arms is not None:
+ arms[-1] += line
+ else:
+ variants = [prefix + line for prefix in variants]
+ if arms is not None:
+ raise AuditError(f"Unterminated conflict in {context}") from original
+ try:
+ return [ast.parse(v, filename=context) for v in variants], True
+ except (SyntaxError, ValueError) as exc:
+ raise AuditError(f"Cannot parse all conflict arms of {context}: {exc}") from exc
+
+
+def _import_module(node: ast.ImportFrom, source_file: str) -> str:
+ if not node.level:
+ return node.module or ""
+ package = source_file.removesuffix(".py").split("/")[:-1]
+ if node.level > len(package):
+ raise AuditError(f"{source_file}:{node.lineno}: invalid relative import")
+ return ".".join(package[:len(package) - node.level + 1] +
+ ([node.module] if node.module else []))
- result = Analysis(path=source_file)
- functions = _function_table(tree)
- constants = _string_constants(tree)
- if entrypoints:
- seen: set[str] = set()
- stack = [name for name in UPDATE_ENTRYPOINTS if name in functions]
- if not stack:
- return result # not an update module at this revision
+@dataclass
+class FunctionFacts:
+ calls: set[str]
+ imports: list[ast.Import | ast.ImportFrom]
+ references: list[tuple[str, tuple[str, ...], bool]]
+ returned_names: set[str]
+ factory_attributes: set[tuple[str, str]]
+ requirements: list[Requirement]
+ unresolved: list[str]
+ error: str | None = None
+
+
+@dataclass
+class ModuleFacts:
+ functions: dict[str, FunctionFacts]
+ imports: list[ast.Import | ast.ImportFrom]
+ reexports: list[ast.ImportFrom]
+
+
+@dataclass
+class VersionFacts:
+ variants: list[ModuleFacts]
+ recovered: bool
+
+
+def _prepare_tree(tree: ast.Module, source_file: str) -> ModuleFacts:
+ """Discard the big AST after retaining compact, seed-independent facts."""
+ imports: list[ast.Import | ast.ImportFrom] = []
+
+ def collect(node: ast.AST) -> None:
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ return
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
+ imports.append(node)
+ for child in ast.iter_child_nodes(node):
+ collect(child)
+
+ collect(tree)
+ functions = {}
+ constants = _string_constants(tree)
+ for func in _function_definitions(tree):
+ name = func.name
+ nodes = list(ast.walk(func))
+ parents = {child: parent for parent in nodes for child in ast.iter_child_nodes(parent)}
+ references = []
+ returned_names = set()
+ factory_attributes = set()
+ for node in nodes:
+ if isinstance(node, ast.Return) and isinstance(node.value, ast.Name):
+ returned_names.add(node.value.id)
+ if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Call):
+ if isinstance(node.value.func, ast.Name):
+ factory_attributes.add((node.value.func.id, node.attr))
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
+ attrs = []
+ parent = parents.get(node)
+ returned = isinstance(parent, ast.Return)
+ while isinstance(parent, ast.Attribute):
+ attrs.append(parent.attr)
+ parent = parents.get(parent)
+ references.append((node.id, tuple(attrs), returned))
+ error = None
+ try:
+ reqs, unresolved = _requirements_in(func, source_file, constants)
+ reqs.extend(_getattr_on_bound_locals(func, source_file))
+ except AuditError as exc:
+ # Invalid imports in an unreachable function were never part of
+ # the selected surface. Defer that failure until it is reached.
+ reqs, unresolved, error = [], [], str(exc)
+ facts = FunctionFacts(
+ _called_names(func),
+ [n for n in nodes if isinstance(n, (ast.Import, ast.ImportFrom))],
+ references, returned_names, factory_attributes, reqs, unresolved, error,
+ )
+ if name in functions:
+ # Without receiver types, every same-named definition is possible.
+ previous = functions[name]
+ previous.calls.update(facts.calls)
+ previous.imports.extend(facts.imports)
+ previous.references.extend(facts.references)
+ previous.returned_names.update(facts.returned_names)
+ previous.factory_attributes.update(facts.factory_attributes)
+ previous.requirements.extend(facts.requirements)
+ previous.unresolved.extend(facts.unresolved)
+ previous.error = previous.error or facts.error
+ else:
+ functions[name] = facts
+ return ModuleFacts(functions, imports, [n for n in tree.body if isinstance(n, ast.ImportFrom)])
+
+
+def _prepare_version(source: str, source_file: str) -> VersionFacts:
+ trees, recovered = _parse_variants(source, source_file)
+ return VersionFacts([_prepare_tree(tree, source_file) for tree in trees], recovered)
+
+
+def _imported_dependencies(
+ facts: ModuleFacts, reachable: set[str], source_file: str,
+) -> dict[str, set[str]]:
+ """Resolve bindings over the selected functions, not unrelated commands.
+
+ Keeping bindings seed-dependent preserves conditional aliases and lazy
+ module factories while their expensive AST walks are cached once.
+ """
+ funcs = {name: facts.functions[name] for name in sorted(reachable)}
+ imports = [*facts.imports, *(node for func in funcs.values() for node in func.imports)]
+ bindings: dict[str, set[tuple[str, str]]] = {}
+ for node in imports:
+ if isinstance(node, ast.ImportFrom):
+ module = _import_module(node, source_file)
+ for alias in node.names:
+ bindings.setdefault(alias.asname or alias.name, set()).add((module, alias.name))
+ else:
+ for alias in node.names:
+ name = alias.asname or alias.name.split(".")[0]
+ bindings.setdefault(name, set()).add((alias.name if alias.asname else name, "*"))
+
+ factories: dict[str, set[str]] = {}
+ for name, func in funcs.items():
+ for returned in func.returned_names:
+ for module, symbol in bindings.get(returned, ()):
+ if _first_party(module):
+ factories.setdefault(name, set()).add(
+ module if symbol == "*" else f"{module}.{symbol}"
+ )
+ dependencies: dict[str, set[str]] = {}
+ for name, func in funcs.items():
+ for called, attr in func.factory_attributes:
+ for module in factories.get(called, ()):
+ dependencies.setdefault(module, set()).add(attr)
+ for reference, attrs, returned in func.references:
+ if returned and name in factories:
+ continue
+ for module, symbol in bindings.get(reference, ()):
+ if not _first_party(module):
+ continue
+ if symbol == "*" and attrs:
+ module = ".".join([module, *attrs[:-1]])
+ symbol = attrs[-1]
+ elif attrs:
+ module = ".".join([module, symbol, *attrs[:-1]])
+ symbol = attrs[-1]
+ dependencies.setdefault(module, set()).add(symbol)
+ return dependencies
+
+
+def _analyse_facts(facts: ModuleFacts, source_file: str, seeds: set[str] | None) -> Analysis:
+ result = Analysis(path=source_file)
+ functions = facts.functions
+ if seeds is None:
+ reachable = set(functions)
+ else:
+ reachable: set[str] = set()
+ stack = [name for name in seeds if name in functions]
while stack:
name = stack.pop()
- if name in seen:
+ if name in reachable:
continue
- seen.add(name)
- for callee in _called_names(functions[name]):
- if callee in functions and callee not in seen:
- stack.append(callee)
- reachable = seen
- else:
- reachable = set(functions)
-
+ reachable.add(name)
+ stack.extend(functions[name].calls & functions.keys() - reachable)
result.reachable = reachable
-
+ result.dependencies = _imported_dependencies(facts, reachable, source_file)
+ for node in facts.reexports:
+ module = _import_module(node, source_file)
+ if _first_party(module):
+ for alias in node.names:
+ if seeds is None or (alias.asname or alias.name) in seeds:
+ result.dependencies.setdefault(module, set()).add(alias.name)
for name in sorted(reachable):
func = functions[name]
- reqs, unresolved = _requirements_in(func, source_file, constants)
- result.requirements.extend(reqs)
- result.requirements.extend(_getattr_on_bound_locals(func, source_file))
- result.unresolved.extend(unresolved)
+ if func.error:
+ raise AuditError(func.error)
+ result.requirements.extend(func.requirements)
+ result.unresolved.extend(func.unresolved)
+ return result
+
+def _analyse_version(facts: VersionFacts, source_file: str, seeds: set[str] | None) -> Analysis:
+ result = Analysis(path=source_file)
+ for variant in facts.variants:
+ part = _analyse_facts(variant, source_file, seeds)
+ result.requirements.extend(part.requirements)
+ result.unresolved.extend(part.unresolved)
+ result.reachable.update(part.reachable)
+ for module, symbols in part.dependencies.items():
+ result.dependencies.setdefault(module, set()).update(symbols)
+ if facts.recovered:
+ result.parse_recoveries.add(
+ f"{source_file}: audited all {len(facts.variants)} merge-conflict arm combinations"
+ )
return result
+def analyse(
+ source: str, source_file: str, *, entrypoints: bool,
+ seeds: set[str] | None = None,
+) -> Analysis:
+ """Analyze selected imports without executing the source. Fail closed."""
+ if entrypoints and seeds is None:
+ seeds = set(UPDATE_ENTRYPOINTS)
+ return _analyse_version(_prepare_version(source, source_file), source_file, seeds)
+
+
# ─── history walking ────────────────────────────────────────────────────
-def _all_audited_paths() -> tuple[str, ...]:
- siblings = tuple(sorted(
- str(p.relative_to(REPO_ROOT)).replace("\\", "/")
- for p in (REPO_ROOT / "hermes_cli").glob("update_cmd_*.py")
- ))
- return tuple(dict.fromkeys((*UPDATE_MODULE_CANDIDATES, *POST_SWAP_HELPER_MODULES, *siblings)))
+def _git(*args: str, input: bytes | None = None) -> bytes:
+ try:
+ return subprocess.run(
+ ["git", "--no-replace-objects", *args], cwd=REPO_ROOT,
+ input=input, capture_output=True, check=True,
+ ).stdout
+ except subprocess.CalledProcessError as exc:
+ raise AuditError(exc.stderr.decode("utf-8", "replace").strip()) from exc
+
+
+def _full_history_ref() -> str:
+ if _git("rev-parse", "--is-shallow-repository").strip() != b"false":
+ raise AuditError(
+ "Cannot audit shallow history. Run git fetch --unshallow origin "
+ "and fetch origin/main before regenerating; shallow CI must use "
+ "the checked-in frozen JSON."
+ )
+ return _git("rev-parse", "--verify", "origin/main^{commit}").decode().strip()
def shipped_commits() -> list[str]:
- """Commits a user could actually be running, newest first.
+ """ALL ancestors of origin/main, not tags, first-parent, or a path log."""
+ return _git("rev-list", _full_history_ref()).decode().splitlines()
- Restricted to ``origin/main``: the update channel is ``main`` or
- ``stable`` (``installation/tree.py``) and both track this branch.
- Unmerged topic branches are not something anyone updates from, and
- including them would freeze names that never shipped.
- Only commits that touched the audited files are listed; every other
- commit leaves them byte-identical to its parent.
- """
- proc = subprocess.run(
- ["git", "log", "origin/main", "--format=%H", "--", *_all_audited_paths()],
- cwd=REPO_ROOT,
- capture_output=True,
- text=True,
- check=True,
+_ENTRYPOINT_PATTERN = re.compile(
+ rb"\bdef\s+(" + "|".join(UPDATE_ENTRYPOINTS).encode() + rb")\s*\("
+)
+
+
+def _has_entrypoint(source: bytes, context: str) -> bool:
+ # Cheap prefilter, then AST check: fixtures/docstrings mentioning
+ # cmd_update are not entrypoints. A malformed candidate is still fatal.
+ if not any(name.encode() in source for name in UPDATE_ENTRYPOINTS):
+ return False
+ # Python permits explicit line continuations between def and its name.
+ normalized = source.replace(b"\\\r\n", b"").replace(b"\\\n", b"")
+ if not _ENTRYPOINT_PATTERN.search(normalized):
+ return False
+ trees, _ = _parse_variants(_decode_source(source, context), context)
+ return any(
+ isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ and node.name in UPDATE_ENTRYPOINTS
+ for tree in trees for node in tree.body
)
- return [line for line in proc.stdout.split() if line]
-def _batch_read_blobs(refs: list[str]) -> dict[str, str]:
- """Read many ``<commit>:<path>`` revisions in ONE git process.
+def _entrypoint_paths(index: HistoryIndex) -> set[str]:
+ """Search every distinct reachable Python blob, not current filenames.
- A ``git show`` per pair is thousands of spawns; ``cat-file --batch``
- streams them through a single pipe. Bytes both ways, because payloads
- are located by the byte offset in each header and text decoding would
- shift every offset at the first multi-byte character.
+ Scanning blobs once avoids pickaxe repeatedly diffing the same large
+ modules at thousands of merges. Bounded batches keep the multi-GB
+ history out of memory; only likely definitions need AST parsing.
"""
- if not refs:
- return {}
+ locations: dict[str, set[str]] = {}
+ for path, versions in index.versions.items():
+ for blob in versions:
+ locations.setdefault(blob, set()).add(path)
+ blobs = sorted(locations)
+ paths: set[str] = set()
+ candidates = 0
+ for start in range(0, len(blobs), 64):
+ if start % 4096 == 0:
+ print(f"[audit] entrypoint discovery: {start}/{len(blobs)} distinct blobs", file=sys.stderr, flush=True)
+ for blob, source in _batch_blobs(blobs[start:start + 64]).items():
+ context = f"{', '.join(sorted(locations[blob]))} [blob {blob}]"
+ if any(name.encode() in source for name in UPDATE_ENTRYPOINTS):
+ candidates += 1
+ if _has_entrypoint(source, context):
+ paths.update(locations[blob])
+ index.discovery_stats = {
+ "python_paths_in_history": len(index.versions),
+ "distinct_blobs_scanned": len(blobs),
+ "blobs_mentioning_entrypoints": candidates,
+ }
+ return paths
+
+
+@dataclass
+class HistoryIndex:
+ # One entry per (path, blob), with commits witnessing that version. A
+ # version unchanged in later commits need not be parsed again.
+ versions: dict[str, dict[str, set[str]]] = field(default_factory=dict)
+ renames: dict[str, set[str]] = field(default_factory=dict)
+ discovery_stats: dict[str, int] = field(default_factory=dict)
- proc = subprocess.run(
- ["git", "cat-file", "--batch"],
- cwd=REPO_ROOT,
- input=("\n".join(refs) + "\n").encode(),
- capture_output=True,
- check=True,
+
+def _history_index(ref: str) -> HistoryIndex:
+ """Inventory every Python version, including deleted files and merge sides.
+
+ A full DAG walk with root diffs covers every blob at its introduction.
+ Rename edges supplement import/definition discovery; correctness does not
+ depend on Git detecting an entrypoint move by its similarity threshold.
+ """
+ output = _git(
+ "log", "--full-history", "-m", "--root", "--find-renames",
+ "--format=%H", "--raw", "--no-abbrev", "-z", ref, "--", "*.py",
)
+ index = HistoryIndex()
+ records = iter(output.split(b"\0"))
+ commit = ""
+ for record in records:
+ record = record.lstrip(b"\n")
+ if not record:
+ continue
+ if not record.startswith(b":"):
+ commit = record.decode()
+ continue
+ _old_mode, new_mode, _old_blob, blob, status = record.decode().split()
+ path = next(records).decode()
+ if status.startswith(("R", "C")):
+ old_path, path = path, next(records).decode()
+ index.renames.setdefault(old_path, set()).add(path)
+ index.renames.setdefault(path, set()).add(old_path)
+ if new_mode != "000000" and path.endswith(".py"):
+ index.versions.setdefault(path, {}).setdefault(blob, set()).add(commit)
+ return index
+
+
+def _decode_source(payload: bytes, context: str) -> str:
+ try:
+ encoding, _ = tokenize.detect_encoding(BytesIO(payload).readline)
+ return payload.decode(encoding)
+ except (SyntaxError, UnicodeError, LookupError) as exc:
+ raise AuditError(f"Cannot decode {context}: {exc}") from exc
- out = proc.stdout
- contents: dict[str, str] = {}
+
+def _batch_blobs(refs: list[str]) -> dict[str, bytes]:
+ """Read known blob IDs in one process; missing/corrupt objects are fatal."""
+ if not refs:
+ return {}
+ out = _git("cat-file", "--batch", input=("\n".join(refs) + "\n").encode())
+ contents: dict[str, bytes] = {}
pos = 0
for ref in refs:
newline = out.find(b"\n", pos)
- if newline == -1:
- break
- header = out[pos:newline].decode("utf-8", "replace")
+ header = out[pos:newline].split()
+ if newline < 0 or len(header) != 3 or header[1] != b"blob":
+ raise AuditError(f"Cannot read historical blob {ref}: {header!r}")
+ size = int(header[2])
pos = newline + 1
- if header.endswith(" missing"):
- continue
- try:
- size = int(header.rsplit(" ", 1)[1])
- except (IndexError, ValueError):
- continue
- contents[ref] = out[pos : pos + size].decode("utf-8", "replace")
+ if len(out) <= pos + size or out[pos + size:pos + size + 1] != b"\n":
+ raise AuditError(f"Truncated historical blob {ref}")
+ contents[ref] = out[pos:pos + size]
pos += size + 1
return contents
+def _batch_read_blobs(refs: list[str]) -> dict[str, str]:
+ return {ref: _decode_source(source, ref) for ref, source in _batch_blobs(refs).items()}
+
+
@dataclass
class Surface:
required: dict[tuple[str, str], set[str]] = field(default_factory=dict)
@@ -537,92 +866,205 @@ class Surface:
and never fatal in ``--check``.
"""
unresolved: set[str] = field(default_factory=set)
+ parse_recoveries: set[str] = field(default_factory=set)
stats: dict = field(default_factory=dict)
-def audit_history() -> Surface:
- commits = shipped_commits()
- paths = _all_audited_paths()
- refs = [f"{c}:{p}" for c in commits for p in paths]
- blobs = _batch_read_blobs(refs)
+def _module_paths(module: str, paths: dict) -> list[str]:
+ stem = module.replace(".", "/")
+ return [p for p in (f"{stem}.py", f"{stem}/__init__.py") if p in paths]
- surface = Surface()
- memo: dict[int, Analysis | None] = {}
- distinct = 0
- bare_pairs: set[tuple[str, str]] = set()
- for ref, source in blobs.items():
- commit, _, path = ref.partition(":")
- fingerprint = hash(source)
- if fingerprint not in memo:
- memo[fingerprint] = analyse(
- source, path, entrypoints=path in UPDATE_MODULE_CANDIDATES
+def _audit_versions(index: HistoryIndex, entrypaths: set[str], read_sources, *, progress: bool = False) -> Surface:
+ """Fixed point over historical static imports and rename edges.
+
+ Demand is monotonic: an additional caller can only add functions. The
+ memo includes the path, not just the blob: identical source at another
+ address has different relative imports, provenance, and seed roles.
+ """
+ demand: dict[str, set[str] | None] = {}
+ pending: deque[str] = deque()
+ queued: set[str] = set()
+
+ def enqueue(path: str, seeds: set[str] | None) -> None:
+ if path not in index.versions:
+ return
+ if path in demand:
+ previous = demand[path]
+ if previous is None or (seeds is not None and seeds <= previous):
+ return
+ if seeds is not None:
+ seeds = seeds | previous
+ demand[path] = None if seeds is None else set(seeds)
+ if path not in queued:
+ pending.append(path)
+ queued.add(path)
+
+ for path in sorted(entrypaths | set(UPDATE_MODULE_CANDIDATES)):
+ enqueue(path, set(UPDATE_ENTRYPOINTS))
+ for path in sorted(set(POST_SWAP_HELPER_MODULES) | {
+ p for p in index.versions
+ if p.startswith("hermes_cli/update_cmd_") and p.endswith(".py")
+ }):
+ enqueue(path, None)
+
+ memo: dict[tuple[str, str], Analysis] = {}
+ prepared: dict[tuple[str, str], VersionFacts] = {}
+ analysis_passes = 0
+ while pending:
+ path = pending.popleft()
+ queued.remove(path)
+ seeds = demand[path]
+ for renamed in index.renames.get(path, ()):
+ enqueue(renamed, seeds)
+ blobs = sorted(index.versions[path])
+ if progress:
+ print(
+ f"[audit] {path}: {len(blobs)} versions; "
+ f"{len(seeds) if seeds is not None else 'all'} function seeds; "
+ f"{len(pending)} paths queued; {analysis_passes} analyses so far",
+ file=sys.stderr, flush=True,
)
- distinct += 1
- analysis = memo[fingerprint]
- if analysis is None:
- continue
+ for start in range(0, len(blobs), 64):
+ batch = blobs[start:start + 64]
+ sources = read_sources(path, [blob for blob in batch if (path, blob) not in prepared])
+ for blob in batch:
+ try:
+ if (path, blob) not in prepared:
+ prepared[path, blob] = _prepare_version(sources[blob], path)
+ analysis = _analyse_version(prepared[path, blob], path, seeds)
+ except AuditError as exc:
+ witnesses = ", ".join(sorted(index.versions[path][blob])[:3])
+ raise AuditError(f"{exc} [blob {blob}; commits {witnesses}]") from exc
+ memo[path, blob] = analysis
+ analysis_passes += 1
+ for module, symbols in analysis.dependencies.items():
+ for symbol in symbols:
+ submodules = _module_paths(f"{module}.{symbol}", index.versions)
+ if submodules or symbol == "*":
+ # A bare module object can escape through a callback
+ # or getattr. Do not turn that into all CLI commands.
+ # Expose the unresolved edge for manual review.
+ analysis.unresolved.append(
+ f"{path}: module object {module}.{symbol} requires manual call-graph review"
+ )
+ else:
+ for target in _module_paths(module, index.versions):
+ enqueue(target, {symbol})
+
+ surface = Surface()
+ bare_pairs: set[tuple[str, str]] = set()
+ for (path, blob), analysis in memo.items():
for req in analysis.requirements:
- surface.required.setdefault(req.key(), set()).add(commit[:12])
- surface.kinds.setdefault(req.key(), set()).add(req.kind)
- surface.sites.setdefault(req.key(), set()).add(
- f"{req.source_file}:{req.function}"
+ surface.required.setdefault(req.key(), set()).update(
+ c[:12] for c in index.versions[path][blob]
)
+ surface.kinds.setdefault(req.key(), set()).add(req.kind)
+ surface.sites.setdefault(req.key(), set()).add(f"{path}:{req.function}")
if not req.guarded:
bare_pairs.add(req.key())
surface.unresolved.update(analysis.unresolved)
-
+ surface.parse_recoveries.update(
+ f"{recovery} [blob {blob}; commits {', '.join(sorted(index.versions[path][blob]))}]"
+ for recovery in analysis.parse_recoveries
+ )
surface.guarded_only = set(surface.required) - bare_pairs
surface.stats = {
- "commits": len(commits),
- "revisions_read": len(blobs),
- "distinct_file_versions": distinct,
+ "files_analyzed": sorted(demand),
+ "entrypoint_paths": sorted(entrypaths & demand.keys()),
+ "files_with_reachable_functions": sorted({p for (p, _), a in memo.items() if a.reachable}),
+ "commits_with_audited_changes": len({c for p, b in memo for c in index.versions[p][b]}),
+ "revisions_read": sum(len(index.versions[p][b]) for p, b in memo),
+ "distinct_file_versions": len(memo),
+ "analysis_passes": analysis_passes,
+ "versions_prepared": len(prepared),
}
return surface
-def audit_tree() -> Surface:
- """The surface of the update flow as it exists in THIS working tree.
-
- The pm rewrite replaced the installation/* + managed_uv update stack
- wholesale, so the shipped-history walk over origin/main freezes names
- (installation.*, hermes_cli.managed_uv.*) that this branch deliberately
- deleted along with the updaters that loaded them. On this lineage the
- honest contract is the CURRENT update flow: freeze what today's updater
- lazy-loads mid-swap, so a FUTURE rename of any of those names turns the
- test red before it bricks a live update. Once this branch is the shipped
- channel, every release cut from it re-enters the surface by regenerating
- against the tree that shipped it.
- """
- surface = Surface()
- bare_pairs: set[tuple[str, str]] = set()
- analyzed: list[str] = []
+def audit_history() -> Surface:
+ ref = _full_history_ref() # pin once; a concurrent fetch cannot mix DAGs
+ index = _history_index(ref)
+ print(f"[audit] indexed {len(index.versions)} historical Python paths", file=sys.stderr, flush=True)
+ surface = _audit_versions(
+ index, _entrypoint_paths(index), lambda path, blobs: _batch_read_blobs(blobs),
+ progress=True,
+ )
+ if not surface.stats["entrypoint_paths"]:
+ raise AuditError("No updater entrypoint found in origin/main history")
+ surface.stats.update({
+ "mode": "history",
+ "discovery": index.discovery_stats,
+ "coverage": "All reachable commits inventoried; distinct selected path/blob versions analyzed. Commit evidence lists version witnesses, not every unchanged descendant.",
+ "history_ref": ref,
+ "complete_history": True,
+ "commits": int(_git("rev-list", "--count", ref)),
+ "roots": sorted(_git("rev-list", "--max-parents=0", ref).decode().split()),
+ })
+ return surface
- for path in _all_audited_paths():
+
+def audit_tree() -> Surface:
+ """Audit the current tree without reading any Git history (shallow CI safe)."""
+ names = _git("ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", "*.py")
+ paths = {p.decode() for p in names.split(b"\0") if p}
+ index = HistoryIndex()
+ entrypaths = set()
+ for path in sorted(paths):
file = REPO_ROOT / path
- if not file.is_file():
+ if not file.is_file(): # tracked deletion in the working tree
continue
- source = file.read_text(encoding="utf-8-sig", errors="replace")
- analysis = analyse(
- source, path, entrypoints=path in UPDATE_MODULE_CANDIDATES
- )
- if analysis is None or (
- path in UPDATE_MODULE_CANDIDATES and not analysis.reachable
- ):
- continue
- analyzed.append(path)
- for req in analysis.requirements:
- surface.required.setdefault(req.key(), set()).add("worktree")
- surface.kinds.setdefault(req.key(), set()).add(req.kind)
- surface.sites.setdefault(req.key(), set()).add(
- f"{req.source_file}:{req.function}"
- )
- if not req.guarded:
- bare_pairs.add(req.key())
- surface.unresolved.update(analysis.unresolved)
+ index.versions[path] = {"worktree": {"worktree"}}
+ source = file.read_bytes()
+ if _has_entrypoint(source, path):
+ entrypaths.add(path)
- surface.guarded_only = set(surface.required) - bare_pairs
- surface.stats = {"mode": "tree", "files_analyzed": sorted(analyzed)}
+ def read_sources(path: str, blobs: list[str]) -> dict[str, str]:
+ return {"worktree": _decode_source((REPO_ROOT / path).read_bytes(), path)}
+
+ surface = _audit_versions(index, entrypaths, read_sources)
+ surface.stats["mode"] = "tree"
+ return surface
+
+
+def audit_union() -> Surface:
+ """The frozen contract: every name any SHIPPED updater can lazy-load
+ after a checkout swap (full history walk over origin/main, following
+ the updater through every path it has lived at), UNION everything the
+ CURRENT updater loads (so a future rename turns the test red before it
+ bricks a live update).
+
+ A pair is guarded_only only when EVERY load site — historical or
+ current — sits under a swallowing ``try``.
+ """
+ history = audit_history()
+ tree = audit_tree()
+
+ surface = Surface()
+ for part in (history, tree):
+ for key, commits in part.required.items():
+ surface.required.setdefault(key, set()).update(commits)
+ for key, kinds in part.kinds.items():
+ surface.kinds.setdefault(key, set()).update(kinds)
+ for key, sites in part.sites.items():
+ surface.sites.setdefault(key, set()).update(sites)
+ surface.unresolved.update(part.unresolved)
+ surface.parse_recoveries.update(part.parse_recoveries)
+
+ bare: set[tuple[str, str]] = set()
+ for part in (history, tree):
+ bare |= set(part.required) - part.guarded_only
+ surface.guarded_only = set(surface.required) - bare
+ witnesses = {commit for commits in history.required.values() for commit in commits}
+ for module, symbol, witness, site in REVIEWED_DYNAMIC_LOADS:
+ if witness not in witnesses:
+ continue
+ key = (module, symbol)
+ surface.required.setdefault(key, set()).add(witness)
+ surface.kinds.setdefault(key, set()).add("reviewed-module-call")
+ surface.sites.setdefault(key, set()).add(site)
+ surface.guarded_only.discard(key)
+ surface.stats = {"mode": "union", "history": history.stats, "tree": tree.stats}
return surface
@@ -658,11 +1100,16 @@ def resolve_in_tree(module: str, symbol: str | None, root: Path) -> tuple[bool,
except (OSError, SyntaxError) as exc:
return False, f"{module}: unreadable ({exc})"
- for node in ast.walk(tree):
+ pending: list[ast.AST] = list(tree.body)
+ while pending:
+ node = pending.pop()
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
if node.name == symbol:
return True, ""
- elif isinstance(node, ast.Assign):
+ # Function locals and class members are not module exports.
+ continue
+ pending.extend(ast.iter_child_nodes(node))
+ if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id == symbol:
return True, ""
@@ -693,21 +1140,24 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument(
"--history",
action="store_true",
- help="Walk every shipped revision on origin/main instead of the "
- "working tree. The pm rewrite retired that lineage's updaters, so "
- "the default is the working-tree surface; the walk remains for "
- "archaeology.",
+ help="Audit only the complete origin/main history. By default the "
+ "audit unions that history with the current working tree. Both "
+ "modes require a full clone; CI reads the checked-in frozen JSON.",
)
parser.add_argument(
"--freeze",
metavar="PATH",
help="Write the surface as JSON (the file the enforcing test reads). "
- "The default audits the working tree; --history re-walks shipped "
- "revisions on origin/main (needs a full clone).",
+ "The default audits the union of the current tree AND the full "
+ "shipped-history walk over origin/main (needs a full clone); "
+ "--history freezes the history half alone.",
)
ns = parser.parse_args(argv)
- surface = audit_history() if ns.history else audit_tree()
+ try:
+ surface = audit_history() if ns.history else audit_union()
+ except AuditError as exc:
+ parser.error(str(exc))
if ns.freeze:
payload = {
@@ -717,9 +1167,12 @@ def main(argv: list[str] | None = None) -> int:
"tree after the checkout swap. Deleting a bare name bricks "
"every release that loads it, mid-update, on a half-new "
"tree. Regenerate after changing the update flow; never "
- "hand-trim."
+ "hand-trim. History enumeration is complete; static call-graph "
+ "limits and unresolved_dynamic still require manual review."
),
"stats": surface.stats,
+ "unresolved_dynamic": sorted(surface.unresolved),
+ "parse_recoveries": sorted(surface.parse_recoveries),
"bare": sorted(
f"{m}::{s}"
for (m, s) in surface.required
@@ -730,6 +1183,10 @@ def main(argv: list[str] | None = None) -> int:
),
}
Path(ns.freeze).write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
+ if surface.parse_recoveries:
+ print("Historical parse recoveries (all arms audited; recorded in JSON):")
+ for recovery in sorted(surface.parse_recoveries):
+ print(f" {recovery}")
print(
f"froze {len(payload['bare'])} bare + "
f"{len(payload['guarded_only'])} guarded pairs -> {ns.freeze}"
@@ -776,6 +1233,7 @@ def main(argv: list[str] | None = None) -> int:
for (m, s), c in sorted(surface.required.items())
],
"unresolved_dynamic": sorted(surface.unresolved),
+ "parse_recoveries": sorted(surface.parse_recoveries),
"missing": [
{"module": m, "symbol": s or None, "commits": c, "why": w}
for m, s, c, w in missing
@@ -791,7 +1249,15 @@ def main(argv: list[str] | None = None) -> int:
return 1 if (missing and ns.check) else 0
st = surface.stats
- if st.get("mode") == "tree":
+ if st.get("mode") == "union":
+ hist, tree = st["history"], st["tree"]
+ print(
+ f"Union of {hist['commits']} reachable shipped commits in the update "
+ f"flow ({hist['revisions_read']} file revisions, "
+ f"{hist['distinct_file_versions']} distinct versions) and the "
+ f"current tree ({len(tree['files_analyzed'])} files)."
+ )
+ elif st.get("mode") == "tree":
print(
f"Audited the update flow in this working tree: "
f"{len(st['files_analyzed'])} files "
@@ -799,7 +1265,7 @@ def main(argv: list[str] | None = None) -> int:
)
else:
print(
- f"Walked every shipped commit that touched the update flow: "
+ f"Walked every reachable shipped commit, auditing distinct update versions: "
f"{st['commits']} commits, {st['revisions_read']} file revisions, "
f"{st['distinct_file_versions']} distinct versions."
)
@@ -834,6 +1300,11 @@ def main(argv: list[str] | None = None) -> int:
for module in sorted(by_module):
print(f" {module}: {', '.join(sorted(by_module[module]))}")
+ if surface.parse_recoveries:
+ print("Historical parse recoveries (all arms audited):")
+ for recovery in sorted(surface.parse_recoveries):
+ print(f" {recovery}")
+
if surface.unresolved:
print()
print(
diff --git a/tests/compat/README.md b/tests/compat/README.md
new file mode 100644
index 00000000000..3a2bdea6241
--- /dev/null
+++ b/tests/compat/README.md
@@ -0,0 +1,67 @@
+# Running updater compatibility
+
+An updater can retain old Python modules after replacing its checkout. Its next
+lazy import reads the new files. Current-tree tests alone cannot protect that
+boundary.
+
+`old_updater_surface.json` records historical imports union current imports.
+Regenerate it from a full clone:
+
+```sh
+python3 scripts/audit-old-updater-imports.py --freeze tests/compat/old_updater_surface.json
+```
+
+The walker pins `origin/main` once. The JSON records that exact commit, the
+history roots, discovered entrypoints, selected paths, and parse recoveries.
+It inventories all reachable commits, including merge parents. It follows
+historical filenames, deleted helpers, extraction imports, and rename edges.
+A shallow clone cannot regenerate the file. Shallow CI checks the frozen names
+and that the current imports remain a subset of the freeze.
+
+The surface deliberately over-approximates reachability. Matching update
+entrypoints and same-named functions can include unrelated callers. Do not trim
+those entries by hand. A historical name is cheaper than a missed live import.
+The resolver requires module-scope bindings, not names inside functions or
+classes. It does not execute module bodies or prove every conditional export.
+
+## Runtime behavior
+
+Retired dependency entrypoints stop with a relaunch message. Returning `None`
+can activate old pip fallback code. Other shims retain conservative return
+shapes without installs, downloads, marker writes, or PM delegation. Each shim
+explains why it exists. Current application code must use the live implementation,
+not these historical exports.
+
+A fresh source launch checks PM's existing successful dependency facts. It
+synchronizes stale state and switches to the managed interpreter before
+activating application dependencies. No new incomplete-marker protocol is used.
+
+`old_updater_dependencies.py` retains historical caller functions with their
+lazy imports intact. The shim tests execute those callers against the new tree.
+`tests/pm/test_source_update_launch.py` exercises real worker publication,
+failed-build retention, and fresh-process bootstrap.
+
+## Manual review of dynamic edges
+
+Complete history enumeration is not a complete Python call-graph proof. The
+JSON retains `unresolved_dynamic` rather than silently dropping those edges.
+The reviewed categories are:
+
+- `hermes_constants` reloads: fixed first-party module, present and audited.
+ Reload execution still depends on the running interpreter and process state.
+- `managed_scope`, `main_dashboard`, and browser module objects: fixed modules
+ passed between helpers. The modules exist. Arbitrary attribute dispatch is
+ not a statically proven contract.
+- `managed_uv` and `_subprocess_compat`: the historical Windows installer calls
+ `_subprocess_compat.run`. `REVIEWED_DYNAMIC_LOADS` retains that named call with
+ its witness commit. Its shim stops before invoking an installer.
+- PM operations and build operations: fixed dispatch modules, seeded explicitly
+ with the other post-swap helpers. PM registry import names can also come from
+ package definitions outside the checkout.
+- Plugin configuration hooks and deferred tool registration: import targets
+ depend on enabled plugins and runtime manifests. A core-tree freeze cannot
+ enumerate names supplied by independently installed plugins.
+
+These limits remain visible in the generated file. The static gate proves that
+its recorded imports still resolve structurally. Real updater and launch tests
+prove the exercised runtime paths, not every historical platform combination.
diff --git a/tests/compat/old_updater_surface.json b/tests/compat/old_updater_surface.json
index 7d7e09e795c..fc94367af55 100644
--- a/tests/compat/old_updater_surface.json
+++ b/tests/compat/old_updater_surface.json
@@ -1,44 +1,744 @@
{
- "_comment": "Generated by scripts/audit-old-updater-imports.py --freeze. Names an already-running `hermes update` loads from the NEW tree after the checkout swap. Deleting a bare name bricks every release that loads it, mid-update, on a half-new tree. Regenerate after changing the update flow; never hand-trim.",
+ "_comment": "Generated by scripts/audit-old-updater-imports.py --freeze. Names an already-running `hermes update` loads from the NEW tree after the checkout swap. Deleting a bare name bricks every release that loads it, mid-update, on a half-new tree. Regenerate after changing the update flow; never hand-trim. History enumeration is complete; static call-graph limits and unresolved_dynamic still require manual review.",
"stats": {
- "mode": "tree",
- "files_analyzed": [
- "hermes_cli/post_update.py",
- "hermes_cli/update_cmd.py",
- "hermes_cli/update_cmd_common.py",
- "hermes_cli/update_cmd_config.py",
- "hermes_cli/update_cmd_deps.py",
- "hermes_cli/update_cmd_fleet.py",
- "hermes_cli/update_cmd_git.py",
- "hermes_cli/update_cmd_maint.py",
- "hermes_cli/update_cmd_stash.py",
- "hermes_cli/update_cmd_windows.py",
- "hermes_cli/update_cmd_zip.py",
- "hermes_cli/update_lock.py",
- "pm/__init__.py",
- "pm/cli.py",
- "pm/ensure.py",
- "pm/extras.py",
- "pm/lock.py",
- "pm/package.py",
- "pm/packages.py",
- "pm/paths.py",
- "pm/registry.py",
- "pm/store.py"
- ]
+ "mode": "union",
+ "history": {
+ "files_analyzed": [
+ "agent/anthropic_adapter.py",
+ "agent/anthropic_credentials.py",
+ "agent/async_utils.py",
+ "agent/curator.py",
+ "agent/deadline.py",
+ "agent/delegation_context.py",
+ "agent/memory_provider.py",
+ "agent/outbound_webhooks.py",
+ "agent/redact.py",
+ "agent/retry_utils.py",
+ "agent/secret_scope.py",
+ "agent/secret_sources/_cache.py",
+ "agent/secret_sources/base.py",
+ "agent/secret_sources/bitwarden.py",
+ "agent/secret_sources/command.py",
+ "agent/secret_sources/onepassword.py",
+ "agent/secret_sources/registry.py",
+ "agent/shell_hooks.py",
+ "agent/skill_utils.py",
+ "agent/terminal_env_registry.py",
+ "gateway/config.py",
+ "gateway/config_env.py",
+ "gateway/config_loader.py",
+ "gateway/control_socket.py",
+ "gateway/lifecycle_ledger.py",
+ "gateway/platform_registry.py",
+ "gateway/platforms/_shared.py",
+ "gateway/profile_routing.py",
+ "gateway/restart.py",
+ "gateway/session_context.py",
+ "gateway/shutdown_forensics.py",
+ "gateway/shutdown_watchdog.py",
+ "gateway/status.py",
+ "hermes_cli/__init__.py",
+ "hermes_cli/_early_recovery.py",
+ "hermes_cli/_install_repair.py",
+ "hermes_cli/_parser.py",
+ "hermes_cli/_scan_venv_blockers.py",
+ "hermes_cli/_subprocess_compat.py",
+ "hermes_cli/agent_plugins.py",
+ "hermes_cli/auth.py",
+ "hermes_cli/auth_constants.py",
+ "hermes_cli/backup.py",
+ "hermes_cli/banner.py",
+ "hermes_cli/build_info.py",
+ "hermes_cli/cli_output.py",
+ "hermes_cli/colors.py",
+ "hermes_cli/config.py",
+ "hermes_cli/config_backups.py",
+ "hermes_cli/config_defaults.py",
+ "hermes_cli/config_home.py",
+ "hermes_cli/config_migrations.py",
+ "hermes_cli/curses_ui.py",
+ "hermes_cli/dashboard_procs.py",
+ "hermes_cli/default_soul.py",
+ "hermes_cli/env_loader.py",
+ "hermes_cli/gateway.py",
+ "hermes_cli/gateway_multiplex_served.py",
+ "hermes_cli/gateway_windows.py",
+ "hermes_cli/git_credentials.py",
+ "hermes_cli/gitlock.py",
+ "hermes_cli/image_provenance.py",
+ "hermes_cli/macos_tcc_anchor.py",
+ "hermes_cli/main.py",
+ "hermes_cli/main_dashboard.py",
+ "hermes_cli/main_desktop.py",
+ "hermes_cli/main_install_repair.py",
+ "hermes_cli/main_tui_launch.py",
+ "hermes_cli/main_web_build.py",
+ "hermes_cli/managed_scope.py",
+ "hermes_cli/managed_uv.py",
+ "hermes_cli/mcp_security.py",
+ "hermes_cli/memory_setup.py",
+ "hermes_cli/model_catalog.py",
+ "hermes_cli/npm_engine.py",
+ "hermes_cli/plugin_capabilities.py",
+ "hermes_cli/plugin_catalog.py",
+ "hermes_cli/plugin_compat.py",
+ "hermes_cli/plugins.py",
+ "hermes_cli/plugins_cmd.py",
+ "hermes_cli/plugins_cmd_catalog.py",
+ "hermes_cli/plugins_discovery.py",
+ "hermes_cli/plugins_ledger.py",
+ "hermes_cli/plugins_loader.py",
+ "hermes_cli/plugins_manifest.py",
+ "hermes_cli/process_identity.py",
+ "hermes_cli/profiles.py",
+ "hermes_cli/psutil_android.py",
+ "hermes_cli/pt_input_extras.py",
+ "hermes_cli/relay_plugin_cutover.py",
+ "hermes_cli/resource_limits.py",
+ "hermes_cli/secret_prompt.py",
+ "hermes_cli/setup.py",
+ "hermes_cli/sizefmt.py",
+ "hermes_cli/sqlite_runtime.py",
+ "hermes_cli/sqlite_safe_read.py",
+ "hermes_cli/subcommands/update.py",
+ "hermes_cli/tools_config.py",
+ "hermes_cli/tools_config_cua.py",
+ "hermes_cli/tools_config_post_setup.py",
+ "hermes_cli/toolset_scope.py",
+ "hermes_cli/toolset_validation.py",
+ "hermes_cli/update_abort_recovery.py",
+ "hermes_cli/update_cmd.py",
+ "hermes_cli/update_cmd_common.py",
+ "hermes_cli/update_cmd_config.py",
+ "hermes_cli/update_cmd_deps.py",
+ "hermes_cli/update_cmd_fleet.py",
+ "hermes_cli/update_cmd_git.py",
+ "hermes_cli/update_cmd_maint.py",
+ "hermes_cli/update_cmd_stash.py",
+ "hermes_cli/update_cmd_windows.py",
+ "hermes_cli/update_cmd_zip.py",
+ "hermes_cli/update_contract.py",
+ "hermes_cli/update_inventory.py",
+ "hermes_cli/update_lock.py",
+ "hermes_cli/update_receipt.py",
+ "hermes_constants.py",
+ "hermes_state.py",
+ "honcho_integration/cli.py",
+ "honcho_integration/client.py",
+ "plugins/memory/__init__.py",
+ "plugins/memory/honcho/cli.py",
+ "plugins/memory/honcho/client.py",
+ "plugins/memory/honcho/client_cache.py",
+ "plugins/memory/honcho/oauth.py",
+ "plugins/plugin_loader.py",
+ "plugins/plugin_utils.py",
+ "tools/browser_tool.py",
+ "tools/browser_tool_install.py",
+ "tools/browser_tool_lifecycle.py",
+ "tools/browser_tool_origin.py",
+ "tools/computer_use/cua_backend.py",
+ "tools/computer_use/cua_backend_driver.py",
+ "tools/env_passthrough.py",
+ "tools/environments/local.py",
+ "tools/environments/local_env_policy.py",
+ "tools/environments/local_pythonpath.py",
+ "tools/lazy_deps.py",
+ "tools/plugin_guard.py",
+ "tools/skill_usage.py",
+ "tools/skills_guard.py",
+ "tools/skills_sync.py",
+ "tools/skills_sync_bundled_ops.py",
+ "tools/skills_sync_optional.py",
+ "utils.py"
+ ],
+ "entrypoint_paths": [
+ "hermes_cli/main.py",
+ "hermes_cli/plugins_cmd.py",
+ "hermes_cli/update_cmd.py",
+ "hermes_cli/update_cmd_zip.py"
+ ],
+ "files_with_reachable_functions": [
+ "agent/anthropic_adapter.py",
+ "agent/anthropic_credentials.py",
+ "agent/async_utils.py",
+ "agent/curator.py",
+ "agent/deadline.py",
+ "agent/delegation_context.py",
+ "agent/outbound_webhooks.py",
+ "agent/redact.py",
+ "agent/retry_utils.py",
+ "agent/secret_scope.py",
+ "agent/secret_sources/_cache.py",
+ "agent/secret_sources/base.py",
+ "agent/secret_sources/bitwarden.py",
+ "agent/secret_sources/registry.py",
+ "agent/shell_hooks.py",
+ "agent/skill_utils.py",
+ "agent/terminal_env_registry.py",
+ "gateway/config.py",
+ "gateway/config_env.py",
+ "gateway/config_loader.py",
+ "gateway/control_socket.py",
+ "gateway/lifecycle_ledger.py",
+ "gateway/platforms/_shared.py",
+ "gateway/profile_routing.py",
+ "gateway/restart.py",
+ "gateway/session_context.py",
+ "gateway/shutdown_forensics.py",
+ "gateway/shutdown_watchdog.py",
+ "gateway/status.py",
+ "hermes_cli/_early_recovery.py",
+ "hermes_cli/_install_repair.py",
+ "hermes_cli/_parser.py",
+ "hermes_cli/_scan_venv_blockers.py",
+ "hermes_cli/_subprocess_compat.py",
+ "hermes_cli/agent_plugins.py",
+ "hermes_cli/auth.py",
+ "hermes_cli/backup.py",
+ "hermes_cli/banner.py",
+ "hermes_cli/build_info.py",
+ "hermes_cli/cli_output.py",
+ "hermes_cli/colors.py",
+ "hermes_cli/config.py",
+ "hermes_cli/config_backups.py",
+ "hermes_cli/config_home.py",
+ "hermes_cli/config_migrations.py",
+ "hermes_cli/curses_ui.py",
+ "hermes_cli/dashboard_procs.py",
+ "hermes_cli/default_soul.py",
+ "hermes_cli/env_loader.py",
+ "hermes_cli/gateway.py",
+ "hermes_cli/gateway_multiplex_served.py",
+ "hermes_cli/gateway_windows.py",
+ "hermes_cli/git_credentials.py",
+ "hermes_cli/gitlock.py",
+ "hermes_cli/image_provenance.py",
+ "hermes_cli/macos_tcc_anchor.py",
+ "hermes_cli/main.py",
+ "hermes_cli/main_dashboard.py",
+ "hermes_cli/main_desktop.py",
+ "hermes_cli/main_install_repair.py",
+ "hermes_cli/main_tui_launch.py",
+ "hermes_cli/main_web_build.py",
+ "hermes_cli/managed_scope.py",
+ "hermes_cli/managed_uv.py",
+ "hermes_cli/mcp_security.py",
+ "hermes_cli/memory_setup.py",
+ "hermes_cli/model_catalog.py",
+ "hermes_cli/npm_engine.py",
+ "hermes_cli/plugin_capabilities.py",
+ "hermes_cli/plugin_catalog.py",
+ "hermes_cli/plugin_compat.py",
+ "hermes_cli/plugins.py",
+ "hermes_cli/plugins_cmd.py",
+ "hermes_cli/plugins_cmd_catalog.py",
+ "hermes_cli/plugins_discovery.py",
+ "hermes_cli/plugins_ledger.py",
+ "hermes_cli/plugins_loader.py",
+ "hermes_cli/plugins_manifest.py",
+ "hermes_cli/process_identity.py",
+ "hermes_cli/profiles.py",
+ "hermes_cli/psutil_android.py",
+ "hermes_cli/pt_input_extras.py",
+ "hermes_cli/relay_plugin_cutover.py",
+ "hermes_cli/resource_limits.py",
+ "hermes_cli/secret_prompt.py",
+ "hermes_cli/setup.py",
+ "hermes_cli/sizefmt.py",
+ "hermes_cli/sqlite_runtime.py",
+ "hermes_cli/sqlite_safe_read.py",
+ "hermes_cli/tools_config.py",
+ "hermes_cli/tools_config_cua.py",
+ "hermes_cli/tools_config_post_setup.py",
+ "hermes_cli/toolset_scope.py",
+ "hermes_cli/toolset_validation.py",
+ "hermes_cli/update_abort_recovery.py",
+ "hermes_cli/update_cmd.py",
+ "hermes_cli/update_cmd_common.py",
+ "hermes_cli/update_cmd_config.py",
+ "hermes_cli/update_cmd_deps.py",
+ "hermes_cli/update_cmd_fleet.py",
+ "hermes_cli/update_cmd_git.py",
+ "hermes_cli/update_cmd_maint.py",
+ "hermes_cli/update_cmd_stash.py",
+ "hermes_cli/update_cmd_windows.py",
+ "hermes_cli/update_cmd_zip.py",
+ "hermes_cli/update_contract.py",
+ "hermes_cli/update_inventory.py",
+ "hermes_cli/update_lock.py",
+ "hermes_cli/update_receipt.py",
+ "hermes_constants.py",
+ "honcho_integration/cli.py",
+ "honcho_integration/client.py",
+ "plugins/memory/__init__.py",
+ "plugins/memory/honcho/cli.py",
+ "plugins/memory/honcho/client.py",
+ "plugins/memory/honcho/client_cache.py",
+ "plugins/memory/honcho/oauth.py",
+ "plugins/plugin_loader.py",
+ "tools/browser_tool.py",
+ "tools/browser_tool_install.py",
+ "tools/browser_tool_lifecycle.py",
+ "tools/browser_tool_origin.py",
+ "tools/computer_use/cua_backend.py",
+ "tools/computer_use/cua_backend_driver.py",
+ "tools/env_passthrough.py",
+ "tools/environments/local.py",
+ "tools/environments/local_env_policy.py",
+ "tools/environments/local_pythonpath.py",
+ "tools/lazy_deps.py",
+ "tools/plugin_guard.py",
+ "tools/skill_usage.py",
+ "tools/skills_guard.py",
+ "tools/skills_sync.py",
+ "tools/skills_sync_bundled_ops.py",
+ "tools/skills_sync_optional.py",
+ "utils.py"
+ ],
+ "commits_with_audited_changes": 7527,
+ "revisions_read": 68791,
+ "distinct_file_versions": 8078,
+ "analysis_passes": 17695,
+ "versions_prepared": 8078,
+ "mode": "history",
+ "discovery": {
+ "python_paths_in_history": 6777,
+ "distinct_blobs_scanned": 73416,
+ "blobs_mentioning_entrypoints": 2443
+ },
+ "coverage": "All reachable commits inventoried; distinct selected path/blob versions analyzed. Commit evidence lists version witnesses, not every unchanged descendant.",
+ "history_ref": "1021a0325696e9070e6659f95fcd84c3e7e114df",
+ "complete_history": true,
+ "commits": 33720,
+ "roots": [
+ "21d80ca68346dfdb8d3556015a723a9217f8566f"
+ ]
+ },
+ "tree": {
+ "files_analyzed": [
+ "agent/curator.py",
+ "agent/deadline.py",
+ "agent/delegation_context.py",
+ "agent/memory_provider.py",
+ "agent/redact.py",
+ "agent/retry_utils.py",
+ "agent/secret_scope.py",
+ "agent/secret_sources/base.py",
+ "agent/secret_sources/registry.py",
+ "agent/skill_utils.py",
+ "agent/ssl_verify.py",
+ "agent/terminal_env_registry.py",
+ "gateway/config.py",
+ "gateway/config_env.py",
+ "gateway/config_loader.py",
+ "gateway/control_socket.py",
+ "gateway/display_config.py",
+ "gateway/lifecycle_ledger.py",
+ "gateway/platform_registry.py",
+ "gateway/profile_routing.py",
+ "gateway/restart.py",
+ "gateway/session_context.py",
+ "gateway/shutdown_forensics.py",
+ "gateway/shutdown_watchdog.py",
+ "gateway/status.py",
+ "hermes_cli/__init__.py",
+ "hermes_cli/_early_recovery.py",
+ "hermes_cli/_install_repair.py",
+ "hermes_cli/_launchers.py",
+ "hermes_cli/_old_updater.py",
+ "hermes_cli/_parser.py",
+ "hermes_cli/_scan_venv_blockers.py",
+ "hermes_cli/_subprocess_compat.py",
+ "hermes_cli/agent_plugins.py",
+ "hermes_cli/archive_safe.py",
+ "hermes_cli/auth.py",
+ "hermes_cli/backup.py",
+ "hermes_cli/backup_restore.py",
+ "hermes_cli/banner.py",
+ "hermes_cli/cli_output.py",
+ "hermes_cli/colors.py",
+ "hermes_cli/config.py",
+ "hermes_cli/config_backups.py",
+ "hermes_cli/config_defaults.py",
+ "hermes_cli/config_home.py",
+ "hermes_cli/config_migrations.py",
+ "hermes_cli/curses_ui.py",
+ "hermes_cli/default_soul.py",
+ "hermes_cli/env_loader.py",
+ "hermes_cli/fs_utils.py",
+ "hermes_cli/gateway.py",
+ "hermes_cli/gateway_windows.py",
+ "hermes_cli/git_credentials.py",
+ "hermes_cli/gitlock.py",
+ "hermes_cli/home_data_layout.py",
+ "hermes_cli/image_provenance.py",
+ "hermes_cli/macos_tcc_anchor.py",
+ "hermes_cli/main.py",
+ "hermes_cli/main_dashboard.py",
+ "hermes_cli/main_install_repair.py",
+ "hermes_cli/managed_scope.py",
+ "hermes_cli/managed_uv.py",
+ "hermes_cli/mcp_security.py",
+ "hermes_cli/memory_setup.py",
+ "hermes_cli/model_catalog.py",
+ "hermes_cli/plugin_capabilities.py",
+ "hermes_cli/plugin_catalog.py",
+ "hermes_cli/plugin_compat.py",
+ "hermes_cli/plugins.py",
+ "hermes_cli/plugins_admission.py",
+ "hermes_cli/plugins_cmd.py",
+ "hermes_cli/plugins_cmd_catalog.py",
+ "hermes_cli/plugins_discovery.py",
+ "hermes_cli/plugins_ledger.py",
+ "hermes_cli/plugins_loader.py",
+ "hermes_cli/plugins_manifest.py",
+ "hermes_cli/plugins_provenance.py",
+ "hermes_cli/plugins_transaction.py",
+ "hermes_cli/plugins_updates.py",
+ "hermes_cli/post_update.py",
+ "hermes_cli/process_identity.py",
+ "hermes_cli/profiles.py",
+ "hermes_cli/psutil_android.py",
+ "hermes_cli/pt_input_extras.py",
+ "hermes_cli/relay_plugin_cutover.py",
+ "hermes_cli/resource_limits.py",
+ "hermes_cli/runtime_paths.py",
+ "hermes_cli/runtime_state.py",
+ "hermes_cli/secret_prompt.py",
+ "hermes_cli/setup.py",
+ "hermes_cli/sizefmt.py",
+ "hermes_cli/sqlite_runtime.py",
+ "hermes_cli/sqlite_safe_read.py",
+ "hermes_cli/steward.py",
+ "hermes_cli/subcommands/update.py",
+ "hermes_cli/tools_config.py",
+ "hermes_cli/tools_config_cua.py",
+ "hermes_cli/toolset_scope.py",
+ "hermes_cli/toolset_validation.py",
+ "hermes_cli/update_abort_recovery.py",
+ "hermes_cli/update_channel.py",
+ "hermes_cli/update_cmd.py",
+ "hermes_cli/update_cmd_common.py",
+ "hermes_cli/update_cmd_config.py",
+ "hermes_cli/update_cmd_deps.py",
+ "hermes_cli/update_cmd_fleet.py",
+ "hermes_cli/update_cmd_git.py",
+ "hermes_cli/update_cmd_maint.py",
+ "hermes_cli/update_cmd_stash.py",
+ "hermes_cli/update_cmd_windows.py",
+ "hermes_cli/update_cmd_zip.py",
+ "hermes_cli/update_contract.py",
+ "hermes_cli/update_inventory.py",
+ "hermes_cli/update_lock.py",
+ "hermes_cli/update_receipt.py",
+ "hermes_cli/urllib_security.py",
+ "hermes_cli/version_info.py",
+ "hermes_constants.py",
+ "hermes_state.py",
+ "plugins/memory/__init__.py",
+ "plugins/memory/honcho/cli.py",
+ "plugins/memory/honcho/client.py",
+ "plugins/memory/honcho/client_cache.py",
+ "plugins/memory/honcho/oauth.py",
+ "plugins/plugin_loader.py",
+ "plugins/plugin_utils.py",
+ "pm/__init__.py",
+ "pm/_uv.py",
+ "pm/artifact_mirror.py",
+ "pm/build_operations.py",
+ "pm/cli.py",
+ "pm/client.py",
+ "pm/download_state.py",
+ "pm/downloader.py",
+ "pm/ensure.py",
+ "pm/environment.py",
+ "pm/extras.py",
+ "pm/features.py",
+ "pm/lock.py",
+ "pm/network.py",
+ "pm/operations.py",
+ "pm/package.py",
+ "pm/packages.py",
+ "pm/paths.py",
+ "pm/plugins_state.py",
+ "pm/receipt.py",
+ "pm/recovery.py",
+ "pm/registry.py",
+ "pm/runtime.py",
+ "pm/runtime_stage.py",
+ "pm/store.py",
+ "pm/update.py",
+ "pm/workspace.py",
+ "tools/browser_tool.py",
+ "tools/browser_tool_install.py",
+ "tools/browser_tool_lifecycle.py",
+ "tools/browser_tool_origin.py",
+ "tools/computer_use/cua_backend.py",
+ "tools/computer_use/cua_backend_driver.py",
+ "tools/env_passthrough.py",
+ "tools/environments/local.py",
+ "tools/environments/local_env_policy.py",
+ "tools/environments/local_pythonpath.py",
+ "tools/plugin_guard.py",
+ "tools/skill_usage.py",
+ "tools/skills_guard.py",
+ "tools/skills_sync.py",
+ "tools/skills_sync_optional.py",
+ "utils.py"
+ ],
+ "entrypoint_paths": [
+ "hermes_cli/main.py",
+ "hermes_cli/plugins_cmd.py",
+ "hermes_cli/update_cmd.py",
+ "hermes_cli/update_cmd_zip.py",
+ "pm/cli.py"
+ ],
+ "files_with_reachable_functions": [
+ "agent/curator.py",
+ "agent/deadline.py",
+ "agent/delegation_context.py",
+ "agent/redact.py",
+ "agent/retry_utils.py",
+ "agent/secret_scope.py",
+ "agent/secret_sources/base.py",
+ "agent/secret_sources/registry.py",
+ "agent/skill_utils.py",
+ "agent/ssl_verify.py",
+ "agent/terminal_env_registry.py",
+ "gateway/config.py",
+ "gateway/config_env.py",
+ "gateway/config_loader.py",
+ "gateway/control_socket.py",
+ "gateway/lifecycle_ledger.py",
+ "gateway/profile_routing.py",
+ "gateway/restart.py",
+ "gateway/session_context.py",
+ "gateway/shutdown_forensics.py",
+ "gateway/shutdown_watchdog.py",
+ "gateway/status.py",
+ "hermes_cli/_early_recovery.py",
+ "hermes_cli/_install_repair.py",
+ "hermes_cli/_launchers.py",
+ "hermes_cli/_old_updater.py",
+ "hermes_cli/_parser.py",
+ "hermes_cli/_scan_venv_blockers.py",
+ "hermes_cli/_subprocess_compat.py",
+ "hermes_cli/agent_plugins.py",
+ "hermes_cli/archive_safe.py",
+ "hermes_cli/auth.py",
+ "hermes_cli/backup.py",
+ "hermes_cli/backup_restore.py",
+ "hermes_cli/banner.py",
+ "hermes_cli/cli_output.py",
+ "hermes_cli/colors.py",
+ "hermes_cli/config.py",
+ "hermes_cli/config_backups.py",
+ "hermes_cli/config_home.py",
+ "hermes_cli/config_migrations.py",
+ "hermes_cli/curses_ui.py",
+ "hermes_cli/default_soul.py",
+ "hermes_cli/env_loader.py",
+ "hermes_cli/fs_utils.py",
+ "hermes_cli/gateway.py",
+ "hermes_cli/gateway_windows.py",
+ "hermes_cli/git_credentials.py",
+ "hermes_cli/gitlock.py",
+ "hermes_cli/home_data_layout.py",
+ "hermes_cli/image_provenance.py",
+ "hermes_cli/macos_tcc_anchor.py",
+ "hermes_cli/main.py",
+ "hermes_cli/main_dashboard.py",
+ "hermes_cli/main_install_repair.py",
+ "hermes_cli/managed_scope.py",
+ "hermes_cli/managed_uv.py",
+ "hermes_cli/mcp_security.py",
+ "hermes_cli/memory_setup.py",
+ "hermes_cli/model_catalog.py",
+ "hermes_cli/plugin_capabilities.py",
+ "hermes_cli/plugin_catalog.py",
+ "hermes_cli/plugin_compat.py",
+ "hermes_cli/plugins.py",
+ "hermes_cli/plugins_admission.py",
+ "hermes_cli/plugins_cmd.py",
+ "hermes_cli/plugins_cmd_catalog.py",
+ "hermes_cli/plugins_discovery.py",
+ "hermes_cli/plugins_ledger.py",
+ "hermes_cli/plugins_loader.py",
+ "hermes_cli/plugins_manifest.py",
+ "hermes_cli/plugins_provenance.py",
+ "hermes_cli/plugins_transaction.py",
+ "hermes_cli/plugins_updates.py",
+ "hermes_cli/post_update.py",
+ "hermes_cli/process_identity.py",
+ "hermes_cli/profiles.py",
+ "hermes_cli/psutil_android.py",
+ "hermes_cli/pt_input_extras.py",
+ "hermes_cli/relay_plugin_cutover.py",
+ "hermes_cli/resource_limits.py",
+ "hermes_cli/runtime_paths.py",
+ "hermes_cli/runtime_state.py",
+ "hermes_cli/secret_prompt.py",
+ "hermes_cli/setup.py",
+ "hermes_cli/sizefmt.py",
+ "hermes_cli/sqlite_runtime.py",
+ "hermes_cli/sqlite_safe_read.py",
+ "hermes_cli/steward.py",
+ "hermes_cli/tools_config_cua.py",
+ "hermes_cli/toolset_scope.py",
+ "hermes_cli/toolset_validation.py",
+ "hermes_cli/update_abort_recovery.py",
+ "hermes_cli/update_channel.py",
+ "hermes_cli/update_cmd.py",
+ "hermes_cli/update_cmd_common.py",
+ "hermes_cli/update_cmd_config.py",
+ "hermes_cli/update_cmd_deps.py",
+ "hermes_cli/update_cmd_fleet.py",
+ "hermes_cli/update_cmd_git.py",
+ "hermes_cli/update_cmd_maint.py",
+ "hermes_cli/update_cmd_stash.py",
+ "hermes_cli/update_cmd_windows.py",
+ "hermes_cli/update_cmd_zip.py",
+ "hermes_cli/update_contract.py",
+ "hermes_cli/update_inventory.py",
+ "hermes_cli/update_lock.py",
+ "hermes_cli/update_receipt.py",
+ "hermes_cli/urllib_security.py",
+ "hermes_cli/version_info.py",
+ "hermes_constants.py",
+ "plugins/memory/__init__.py",
+ "plugins/memory/honcho/cli.py",
+ "plugins/memory/honcho/client.py",
+ "plugins/memory/honcho/client_cache.py",
+ "plugins/memory/honcho/oauth.py",
+ "plugins/plugin_loader.py",
+ "pm/_uv.py",
+ "pm/artifact_mirror.py",
+ "pm/build_operations.py",
+ "pm/cli.py",
+ "pm/client.py",
+ "pm/download_state.py",
+ "pm/ensure.py",
+ "pm/environment.py",
+ "pm/extras.py",
+ "pm/features.py",
+ "pm/lock.py",
+ "pm/network.py",
+ "pm/operations.py",
+ "pm/package.py",
+ "pm/packages.py",
+ "pm/paths.py",
+ "pm/plugins_state.py",
+ "pm/receipt.py",
+ "pm/recovery.py",
+ "pm/registry.py",
+ "pm/runtime.py",
+ "pm/runtime_stage.py",
+ "pm/store.py",
+ "pm/update.py",
+ "pm/workspace.py",
+ "tools/browser_tool_install.py",
+ "tools/browser_tool_lifecycle.py",
+ "tools/browser_tool_origin.py",
+ "tools/computer_use/cua_backend.py",
+ "tools/computer_use/cua_backend_driver.py",
+ "tools/env_passthrough.py",
+ "tools/environments/local.py",
+ "tools/environments/local_env_policy.py",
+ "tools/environments/local_pythonpath.py",
+ "tools/plugin_guard.py",
+ "tools/skill_usage.py",
+ "tools/skills_guard.py",
+ "tools/skills_sync.py",
+ "tools/skills_sync_optional.py",
+ "utils.py"
+ ],
+ "commits_with_audited_changes": 1,
+ "revisions_read": 169,
+ "distinct_file_versions": 169,
+ "analysis_passes": 216,
+ "versions_prepared": 169,
+ "mode": "tree"
+ }
},
+ "unresolved_dynamic": [
+ "hermes_cli/config.py: module object hermes_cli.managed_scope requires manual call-graph review",
+ "hermes_cli/dashboard_procs.py: module object hermes_cli.main_dashboard requires manual call-graph review",
+ "hermes_cli/gateway.py: module object hermes_constants.* requires manual call-graph review",
+ "hermes_cli/gateway.py:get_python_path: importlib.reload(hermes_constants)",
+ "hermes_cli/main.py: module object hermes_constants.* requires manual call-graph review",
+ "hermes_cli/main.py:_cmd_update_impl: importlib.reload(_hc)",
+ "hermes_cli/main.py:cmd_update: importlib.reload(_hc)",
+ "hermes_cli/managed_uv.py: module object hermes_cli._subprocess_compat requires manual call-graph review",
+ "hermes_cli/managed_uv.py: module object hermes_constants.* requires manual call-graph review",
+ "hermes_cli/managed_uv.py:_reload_hermes_constants: importlib.reload(hermes_constants)",
+ "hermes_cli/plugins.py:_re_register_config_hooks_after_force: importlib.import_module(module_name)",
+ "hermes_cli/plugins.py:_register_deferred_platform_tools: importlib.import_module(f'{module.__name__}.tools')",
+ "hermes_cli/post_update.py: module object pm.ensure requires manual call-graph review",
+ "hermes_cli/update_cmd_maint.py:_reload_modules: importlib.reload(module)",
+ "pm/client.py: module object pm.build_operations requires manual call-graph review",
+ "pm/client.py: module object pm.operations requires manual call-graph review",
+ "pm/ensure.py: module object pm.paths requires manual call-graph review",
+ "pm/registry.py:load_package_definitions: importlib.import_module(module_name)",
+ "tools/browser_tool_origin.py: module object tools.* requires manual call-graph review",
+ "tools/browser_tool_origin.py: module object tools.browser_tool.* requires manual call-graph review"
+ ],
+ "parse_recoveries": [
+ "hermes_cli/config.py: audited all 2 merge-conflict arm combinations [blob c48ec10db003682046d0848adfad5680c21e1f95; commits e286e6875678711ee38353852ec201ea727e5284]"
+ ],
"bare": [
+ "agent.async_utils::safe_schedule_threadsafe",
+ "agent.delegation_context::delegated_child_subprocess_env",
+ "agent.memory_provider::MemoryProvider",
+ "agent.redact::redact_sensitive_text",
+ "agent.retry_utils::jittered_backoff",
+ "agent.secret_scope::_is_global_env",
+ "agent.secret_scope::current_secret_scope",
+ "agent.secret_scope::get_secret",
+ "agent.secret_scope::is_multiplex_active",
+ "agent.secret_sources._cache::resolve_cache_home",
+ "agent.skill_utils::_NAMESPACE_RE",
+ "agent.skill_utils::_external_dirs_cache_clear",
+ "agent.skill_utils::get_external_skills_dirs",
+ "agent.ssl_verify::install_truststore",
+ "gateway.config_env::_apply_env_overrides",
+ "gateway.platform_registry::platform_registry",
+ "gateway.platforms._shared::profile_scoped",
+ "gateway.profile_routing::parse_profile_routes",
+ "gateway.session_context::get_session_env",
"gateway.shutdown_forensics::parse_systemd_duration_to_us",
"gateway.status::_get_process_start_time",
"gateway.status::_pid_exists",
+ "gateway.status::_pid_from_record",
+ "gateway.status::_read_pid_record",
"gateway.status::get_process_start_time",
+ "gateway.status::get_running_pid",
+ "gateway.status::get_running_pid_identity_strict",
"gateway.status::looks_like_gateway_command_line",
+ "gateway.status::looks_like_gateway_runtime_command_line",
+ "gateway.status::profile_flag_value",
+ "gateway.status::read_runtime_status",
"gateway.status::terminate_pid",
+ "gateway::config_loader",
"hermes_cli._early_recovery::recover_if_needed",
+ "hermes_cli._install_repair::_sync_windows_cli_launchers",
"hermes_cli._install_repair::migrate_windows_bin_path",
+ "hermes_cli._launchers::exe_is_venv_bound",
+ "hermes_cli._launchers::mint_launcher",
+ "hermes_cli._launchers::resolve_store_python",
+ "hermes_cli._launchers::stage_launcher",
+ "hermes_cli._old_updater::stop_for_relaunch",
+ "hermes_cli._parser::command_argv",
"hermes_cli._scan_venv_blockers::_is_pausable_gateway",
+ "hermes_cli._subprocess_compat::bounded_probe_run",
+ "hermes_cli._subprocess_compat::kill_process_tree",
"hermes_cli._subprocess_compat::pid_is_hermes",
+ "hermes_cli._subprocess_compat::run",
+ "hermes_cli._subprocess_compat::split_command_line",
+ "hermes_cli._subprocess_compat::windows_detach_flags_without_breakaway",
+ "hermes_cli._subprocess_compat::windows_detach_popen_kwargs",
"hermes_cli._subprocess_compat::windows_hide_flags",
+ "hermes_cli.agent_plugins::read_agent_plugin_manifest",
+ "hermes_cli.backup::_foreign_db_holder_pids",
"hermes_cli.backup::_quick_snapshot_root",
"hermes_cli.backup::_sibling_profile_homes",
"hermes_cli.backup::create_pre_update_snapshots_all_profiles",
@@ -49,18 +749,49 @@
"hermes_cli.backup::restore_cron_jobs_if_emptied",
"hermes_cli.backup::verify_sqlite_integrity",
"hermes_cli.backup_restore::_foreign_db_holder_pids",
+ "hermes_cli.banner::_check_via_pypi",
"hermes_cli.banner::_github_compare_behind",
+ "hermes_cli.banner::check_via_pypi",
+ "hermes_cli.build_info::get_code_identity",
+ "hermes_cli.config::_EXTRA_ENV_KEYS",
+ "hermes_cli.config::_ensure_default_soul_md",
+ "hermes_cli.config::_greedy_literal_match",
+ "hermes_cli.config::_parse_env_value",
+ "hermes_cli.config::_secure_dir",
+ "hermes_cli.config::_split_key_path",
"hermes_cli.config::check_config_version",
+ "hermes_cli.config::detect_install_method",
+ "hermes_cli.config::format_docker_update_message",
+ "hermes_cli.config::format_unsupported_install_warning",
"hermes_cli.config::get_config_path",
"hermes_cli.config::get_env_path",
"hermes_cli.config::get_hermes_home",
+ "hermes_cli.config::get_managed_system",
"hermes_cli.config::get_missing_config_fields",
"hermes_cli.config::get_missing_env_vars",
+ "hermes_cli.config::is_managed",
+ "hermes_cli.config::is_nix_install_method",
+ "hermes_cli.config::is_unsupported_install_method",
+ "hermes_cli.config::is_uv_tool_install",
"hermes_cli.config::load_config",
+ "hermes_cli.config::managed_error",
"hermes_cli.config::migrate_config",
+ "hermes_cli.config::read_user_config_raw",
+ "hermes_cli.config::recommended_update_command",
+ "hermes_cli.config::recommended_update_command_for_method",
+ "hermes_cli.config::require_readable_config_before_write",
+ "hermes_cli.config::save_config",
+ "hermes_cli.config_backups::backup_config",
+ "hermes_cli.config_defaults::OPTIONAL_ENV_VARS",
+ "hermes_cli.config_home::initialize_home",
"hermes_cli.config_migrations::SUPPORT_FLOOR_VERSION",
+ "hermes_cli.config_migrations::run_migrations",
"hermes_cli.config_migrations::support_floor_message",
+ "hermes_cli.curses_ui::curses_radiolist",
+ "hermes_cli.dashboard_procs::_scan_dashboard_processes",
+ "hermes_cli.fs_utils::rmtree_force",
"hermes_cli.gateway::GATEWAY_LOOP_WEDGED",
+ "hermes_cli.gateway::PROJECT_ROOT",
"hermes_cli.gateway::_capture_gateway_argv",
"hermes_cli.gateway::_ensure_user_systemd_env",
"hermes_cli.gateway::_escalate_wedged_gateway",
@@ -70,8 +801,11 @@
"hermes_cli.gateway::_graceful_restart_via_sigusr1",
"hermes_cli.gateway::_is_pid_ancestor_of_current_process",
"hermes_cli.gateway::_launchd_kickstart",
+ "hermes_cli.gateway::_launchd_service_registered",
"hermes_cli.gateway::_locate_launchd_gateway_service",
"hermes_cli.gateway::_prepare_profile_gateway_update_restart",
+ "hermes_cli.gateway::_profile_arg",
+ "hermes_cli.gateway::_profile_suffix",
"hermes_cli.gateway::_request_gateway_self_restart",
"hermes_cli.gateway::_wait_for_gateway_exit",
"hermes_cli.gateway::_wait_for_launchd_service_pid",
@@ -80,8 +814,10 @@
"hermes_cli.gateway::find_windows_gateway_services",
"hermes_cli.gateway::get_launchd_label",
"hermes_cli.gateway::get_launchd_plist_path",
+ "hermes_cli.gateway::get_python_path",
"hermes_cli.gateway::has_legacy_hermes_units",
"hermes_cli.gateway::is_macos",
+ "hermes_cli.gateway::kill_gateway_processes",
"hermes_cli.gateway::launch_detached_gateway_restart_by_cmdline",
"hermes_cli.gateway::launch_detached_profile_gateway_restart",
"hermes_cli.gateway::launchd_gateway_labels_for_install",
@@ -89,48 +825,152 @@
"hermes_cli.gateway::probe_gateway_loop_liveness",
"hermes_cli.gateway::supports_systemd_services",
"hermes_cli.gateway::wait_for_launchd_gateway_supervision",
+ "hermes_cli.git_credentials::with_git_auth",
"hermes_cli.gitlock::clear_stale_git_locks",
"hermes_cli.gitlock::clear_stale_tmp_packs",
"hermes_cli.gitlock::prune_stale_shallow_grafts",
+ "hermes_cli.image_provenance::read_image_provenance",
+ "hermes_cli.main::PROJECT_ROOT",
+ "hermes_cli.main::ShimQuarantineError",
+ "hermes_cli.main::_BYTECODE_FINGERPRINT_FILE",
+ "hermes_cli.main::_UPDATE_REEXEC_ENV",
+ "hermes_cli.main::_desktop_dist_exists",
+ "hermes_cli.main::_desktop_packaged_executable",
+ "hermes_cli.main::_desktop_stamp_path",
+ "hermes_cli.main::_detect_broken_lazy_refresh_imports",
+ "hermes_cli.main::_detect_venv_python_processes",
+ "hermes_cli.main::_expected_windows_pe_machines",
+ "hermes_cli.main::_hermes_exe_shims",
+ "hermes_cli.main::_insert_python_pin",
+ "hermes_cli.main::_interpreter_scripts_dir",
+ "hermes_cli.main::_is_termux_startup_environment",
+ "hermes_cli.main::_is_windows",
+ "hermes_cli.main::_load_installable_optional_extras",
+ "hermes_cli.main::_parse_pe_machine",
+ "hermes_cli.main::_quarantine_running_hermes_exe",
+ "hermes_cli.main::_read_git_revision_fingerprint",
+ "hermes_cli.main::_repair_broken_lazy_refresh_imports",
+ "hermes_cli.main::_resolve_install_target_python",
+ "hermes_cli.main::_resolve_node_runtime_npm",
+ "hermes_cli.main::_restore_quarantined_exes",
+ "hermes_cli.main::_run_install_with_heartbeat",
+ "hermes_cli.main::_run_npm_install_deterministic",
+ "hermes_cli.main::_run_package_only_install",
+ "hermes_cli.main::_run_quarantined_install",
+ "hermes_cli.main::_run_with_idle_timeout",
+ "hermes_cli.main::_self",
+ "hermes_cli.main::_update_marker_path",
+ "hermes_cli.main::_venv_scripts_dir",
+ "hermes_cli.main::_verify_console_scripts_installed",
+ "hermes_cli.main::_verify_core_dependencies_installed",
+ "hermes_cli.main::_web_ui_build_needed",
+ "hermes_cli.main::_windows_native_machine",
+ "hermes_cli.main::_windows_shim_in_process_chain",
+ "hermes_cli.main::_write_web_ui_build_stamp",
+ "hermes_cli.main_install_repair::_hermes_exe_shims",
+ "hermes_cli.main_install_repair::_is_windows",
+ "hermes_cli.main_install_repair::_resolve_node_runtime_npm",
+ "hermes_cli.managed_uv::_reload_hermes_constants",
+ "hermes_cli.managed_uv::ensure_uv",
+ "hermes_cli.managed_uv::managed_python_env",
+ "hermes_cli.managed_uv::rebuild_venv",
+ "hermes_cli.managed_uv::resolve_uv",
+ "hermes_cli.managed_uv::update_managed_uv",
"hermes_cli.model_catalog::seed_cache_from_checkout",
+ "hermes_cli.npm_engine::maybe_repair_npm_engine",
+ "hermes_cli.plugin_capabilities::CAPABILITY_REGISTRY",
+ "hermes_cli.plugin_capabilities::declared_set_changed",
+ "hermes_cli.plugin_capabilities::parse_declared_capabilities",
+ "hermes_cli.plugin_capabilities::pending_capabilities",
+ "hermes_cli.plugin_capabilities::record_consent",
+ "hermes_cli.plugin_catalog::find_removed",
+ "hermes_cli.plugin_catalog::load_catalog_live",
"hermes_cli.plugin_compat::compat_report",
"hermes_cli.plugin_compat::removal_in_effect",
"hermes_cli.plugin_compat::summary_lines",
+ "hermes_cli.plugins::PluginContext",
+ "hermes_cli.plugins::PluginManifest",
+ "hermes_cli.plugins::SHELL_UNSUPPORTED_HOOKS",
+ "hermes_cli.plugins::VALID_HOOKS",
+ "hermes_cli.plugins::get_plugin_manager",
+ "hermes_cli.plugins_admission::candidate_member_dirs",
+ "hermes_cli.plugins_cmd::PluginOperationError",
+ "hermes_cli.plugins_cmd::_check_manifest_version",
+ "hermes_cli.plugins_cmd::_fail",
+ "hermes_cli.plugins_cmd::_get_enabled_set",
+ "hermes_cli.plugins_cmd::_install_plugin_core",
+ "hermes_cli.plugins_cmd::_read_manifest_for_install",
+ "hermes_cli.plugins_cmd::_save_enabled_set",
+ "hermes_cli.plugins_cmd_catalog::raise_if_removed",
+ "hermes_cli.plugins_ledger::_hook_source_of",
+ "hermes_cli.plugins_manifest::SUPPORTED_MANIFEST_VERSION",
+ "hermes_cli.plugins_manifest::requires_hermes_error",
+ "hermes_cli.plugins_provenance::Provenance",
+ "hermes_cli.plugins_provenance::ProvenanceClass",
+ "hermes_cli.plugins_provenance::read_sidecar_rows",
+ "hermes_cli.plugins_transaction::recover_plugin_publication",
+ "hermes_cli.plugins_transaction::update_plugin",
+ "hermes_cli.plugins_updates::check_local_provenance",
+ "hermes_cli.plugins_updates::default_fetch",
+ "hermes_cli.plugins_updates::parse_feed_yml",
"hermes_cli.process_identity::ledger_entries",
"hermes_cli.process_identity::spawner_is_dead",
"hermes_cli.profiles::_PROFILE_ID_RE",
+ "hermes_cli.profiles::_get_default_hermes_home",
"hermes_cli.profiles::_get_profiles_root",
"hermes_cli.profiles::backfill_profile_envs",
+ "hermes_cli.profiles::get_active_profile_name",
"hermes_cli.profiles::list_profiles",
+ "hermes_cli.profiles::normalize_profile_name",
"hermes_cli.profiles::seed_profile_skills",
+ "hermes_cli.profiles::validate_profile_name",
+ "hermes_cli.psutil_android::PSUTIL_URL",
+ "hermes_cli.psutil_android::prepare_patched_psutil_sdist",
+ "hermes_cli.pt_input_extras::install_modify_other_keys_aliases",
+ "hermes_cli.runtime_paths::dependency_home_root",
"hermes_cli.runtime_paths::install_state_dir",
"hermes_cli.runtime_paths::runtime_facts_path",
"hermes_cli.runtime_paths::selected_venv",
"hermes_cli.runtime_paths::site_packages",
"hermes_cli.runtime_paths::store_root",
"hermes_cli.runtime_state::_atomic_bytes",
+ "hermes_cli.runtime_state::_bytes",
+ "hermes_cli.runtime_state::_digest",
"hermes_cli.runtime_state::_lock",
"hermes_cli.runtime_state::collect_generations",
+ "hermes_cli.runtime_state::recover_publication",
+ "hermes_cli.runtime_state::runtime_lock",
+ "hermes_cli.setup::prompt_yes_no",
"hermes_cli.sizefmt::format_bytes",
"hermes_cli.sqlite_runtime::probe_sqlite_runtime",
"hermes_cli.sqlite_safe_read::LiveConnectionError",
+ "hermes_cli.sqlite_safe_read::has_live_connection",
"hermes_cli.sqlite_safe_read::offline_file_access",
+ "hermes_cli.sqlite_safe_read::read_header_bytes_preopen",
"hermes_cli.steward::STEWARD_DESKTOP",
"hermes_cli.steward::read_install_stamp",
+ "hermes_cli.tools_config::_pip_install",
"hermes_cli.tools_config::install_cua_driver",
"hermes_cli.update_channel::CHANNEL_STABLE",
+ "hermes_cli.update_channel::handle_metadata_args",
"hermes_cli.update_cmd::_UPDATE_CRITICAL_MODULES",
"hermes_cli.update_cmd::_abort_recovery_is_complete",
"hermes_cli.update_cmd::_add_upstream_remote",
"hermes_cli.update_cmd::_branch_head_suffix",
"hermes_cli.update_cmd::_capture_head_sha",
"hermes_cli.update_cmd::_check_and_apply_config_migration",
+ "hermes_cli.update_cmd::_cmd_update_check",
+ "hermes_cli.update_cmd::_cmd_update_impl",
"hermes_cli.update_cmd::_count_commits_between",
"hermes_cli.update_cmd::_critical_module_import_failures",
"hermes_cli.update_cmd::_current_checkout_sha",
"hermes_cli.update_cmd::_desktop_owns_gateway_lifecycle",
+ "hermes_cli.update_cmd::_ensure_uv_for_termux",
+ "hermes_cli.update_cmd::_ensure_venv_pip",
"hermes_cli.update_cmd::_finish_dashboard_update_cleanup",
"hermes_cli.update_cmd::_gateway_prompt",
+ "hermes_cli.update_cmd::_gateway_recovery_partition",
+ "hermes_cli.update_cmd::_git_run",
"hermes_cli.update_cmd::_git_untracked_paths",
"hermes_cli.update_cmd::_has_upstream_remote",
"hermes_cli.update_cmd::_locate_real_git",
@@ -139,7 +979,9 @@
"hermes_cli.update_cmd::_migrate_sibling_profile_configs",
"hermes_cli.update_cmd::_no_prompt_git_kwargs",
"hermes_cli.update_cmd::_path_uid",
+ "hermes_cli.update_cmd::_pip_install_prefix",
"hermes_cli.update_cmd::_post_update_sqlite_runtime_status",
+ "hermes_cli.update_cmd::_print_bundled_skills_sync_report",
"hermes_cli.update_cmd::_print_curator_first_run_notice",
"hermes_cli.update_cmd::_print_curator_recent_run_notice",
"hermes_cli.update_cmd::_print_update_summary",
@@ -148,6 +990,7 @@
"hermes_cli.update_cmd::_record_update_step",
"hermes_cli.update_cmd::_recover_gateway_restart_after_abort",
"hermes_cli.update_cmd::_refuse_gateway_ancestor_tree_kill",
+ "hermes_cli.update_cmd::_refuse_update_for_contended_shims",
"hermes_cli.update_cmd::_reload_config_modules",
"hermes_cli.update_cmd::_reload_process_scan_modules",
"hermes_cli.update_cmd::_restore_windows_gateway_service",
@@ -155,10 +998,12 @@
"hermes_cli.update_cmd::_run_config_check_fresh",
"hermes_cli.update_cmd::_run_migrate_config_fresh",
"hermes_cli.update_cmd::_run_pending_fleet_restart",
+ "hermes_cli.update_cmd::_shim_quarantine_error_type",
"hermes_cli.update_cmd::_should_skip_upstream_prompt",
"hermes_cli.update_cmd::_start_windows_gateway_service",
"hermes_cli.update_cmd::_stop_windows_gateway_service",
"hermes_cli.update_cmd::_surviving_pre_update_serve_runtimes",
+ "hermes_cli.update_cmd::_sweep_bytecode_after_update",
"hermes_cli.update_cmd::_update_complete_message",
"hermes_cli.update_cmd::_update_node_dependencies",
"hermes_cli.update_cmd::_validate_critical_modules_import",
@@ -168,16 +1013,26 @@
"hermes_cli.update_cmd::_write_gateway_update_exit_code",
"hermes_cli.update_cmd::_write_lazy_refresh_incomplete_marker",
"hermes_cli.update_cmd::_write_update_incomplete_marker",
+ "hermes_cli.update_cmd::get_default_hermes_root",
"hermes_cli.update_cmd::get_hermes_home",
"hermes_cli.update_cmd_config::",
"hermes_cli.update_cmd_git::_git_run",
"hermes_cli.update_cmd_maint::_print_bundled_skills_sync_report",
"hermes_cli.update_cmd_maint::_sweep_bytecode_after_update",
+ "hermes_cli.update_contract::evaluate_update_admission",
+ "hermes_cli.update_contract::record_refusal_receipt",
"hermes_cli.update_inventory::collect_runtime_inventory",
"hermes_cli.update_inventory::match_runtime_outcomes",
+ "hermes_cli.update_inventory::print_update_plan",
"hermes_cli.update_inventory::record_plan_in_receipt",
"hermes_cli.update_inventory::report_unaccounted_runtimes",
+ "hermes_cli.update_lock::UPDATE_EXIT_CONCURRENT",
+ "hermes_cli.update_lock::UpdateLock",
+ "hermes_cli.update_lock::describe_holder",
"hermes_cli.update_receipt::",
+ "hermes_cli.update_receipt::COMMAND_BOUNDARY_STOP_REASON",
+ "hermes_cli.update_receipt::_profile_homes",
+ "hermes_cli.update_receipt::_socket_identity",
"hermes_cli.update_receipt::begin_update_receipt",
"hermes_cli.update_receipt::collect_fleet_versions",
"hermes_cli.update_receipt::finalize_update_receipt",
@@ -185,20 +1040,53 @@
"hermes_cli.update_receipt::read_latest_receipt",
"hermes_cli.update_receipt::record_gateway_restart",
"hermes_cli.update_receipt::record_step",
+ "hermes_cli.urllib_security::open_credentialed_url",
+ "hermes_cli.urllib_security::url_origin",
+ "hermes_cli.version_info::get_code_identity",
+ "hermes_cli::__version__",
+ "hermes_cli::_early_recovery",
+ "hermes_cli::_subprocess_compat",
"hermes_cli::gateway_windows",
"hermes_cli::main",
+ "hermes_cli::main_dashboard",
+ "hermes_cli::managed_scope",
+ "hermes_cli::plugins",
+ "hermes_cli::plugins_cmd",
+ "hermes_cli::plugins_cmd_catalog",
"hermes_cli::runtime_paths",
+ "hermes_constants::",
"hermes_constants::FIRST_PARTY_MODULE_ROOTS",
+ "hermes_constants::_get_platform_default_hermes_home",
+ "hermes_constants::apply_subprocess_home_env",
+ "hermes_constants::assert_named_profile_home_live",
"hermes_constants::display_hermes_home",
+ "hermes_constants::find_node_executable",
"hermes_constants::get_default_hermes_root",
"hermes_constants::get_hermes_home",
+ "hermes_constants::get_hermes_home_override",
"hermes_constants::get_process_hermes_home",
+ "hermes_constants::get_real_home",
+ "hermes_constants::get_subprocess_home",
+ "hermes_constants::hermes_home_key",
+ "hermes_constants::hermes_managed_node_tree_present",
+ "hermes_constants::is_container",
"hermes_constants::is_wsl",
+ "hermes_constants::iter_hermes_node_dirs",
+ "hermes_constants::profile_name_for_home",
"hermes_constants::project_venv_dir",
"hermes_constants::reset_hermes_home_override",
"hermes_constants::set_hermes_home_override",
+ "hermes_constants::venv_bin_dir",
+ "hermes_constants::venv_python_path",
"hermes_constants::with_hermes_node_path",
"plugins.memory.honcho.cli::sync_honcho_profiles_quiet",
+ "plugins.memory.honcho.client::_HostLookup",
+ "plugins.memory.honcho.client::_host_block",
+ "plugins.memory.honcho.client::_resolve_optional_float",
+ "plugins.memory.honcho.client::resolve_active_host",
+ "plugins.memory.honcho.client::resolve_config_path",
+ "plugins.memory::find_provider_dir",
+ "pm._uv::_toolchain",
"pm.artifact_mirror::pinned_source",
"pm.client::sync_venv",
"pm.download_state::collect_partials",
@@ -206,66 +1094,218 @@
"pm.downloader::DownloadPaused",
"pm.downloader::_OPENER",
"pm.ensure::_identity",
+ "pm.ensure::_install",
"pm.ensure::_installed_location",
+ "pm.ensure::_lockfile",
+ "pm.ensure::_refuse_lazy",
+ "pm.ensure::ensure",
"pm.ensure::env_for",
"pm.ensure::installed_package",
+ "pm.ensure::is_installed",
"pm.ensure::lazy_installs_allowed",
"pm.ensure::sealed",
"pm.ensure::sync_venv",
+ "pm.ensure::venv_is_current",
+ "pm.environment::PythonEnvironment",
+ "pm.environment::_base_environment",
"pm.environment::managed_environment",
+ "pm.environment::prune_site_pth",
+ "pm.extras::extra_supported",
"pm.features::read_features",
"pm.lock::Facts",
"pm.lock::Lockfile",
+ "pm.lock::_write",
"pm.network::retry_network",
+ "pm.operations::_require_install_allowed",
+ "pm.operations::_requirements",
+ "pm.operations::stage_manager_runtime",
"pm.package::InstallError",
"pm.packages::Venv",
"pm.packages::npm_env",
+ "pm.packages::uv_cache_dir",
"pm.paths::lockfile_path",
"pm.paths::repo_root",
"pm.paths::runtime_facts_path",
"pm.paths::store_root",
"pm.paths::writable_store_root",
+ "pm.plugins_state::_is_directory",
+ "pm.plugins_state::enabled_plugins_ordered",
+ "pm.recovery::validate_environment",
+ "pm.registry::get_package",
+ "pm.registry::package_definitions",
+ "pm.registry::walk",
"pm.runtime::is_runtime",
"pm.runtime::run_cli",
+ "pm.runtime::runtime_environment",
+ "pm.runtime_stage::stage_runtime",
"pm.store::Store",
"pm.store::current_target",
"pm.store::extract",
"pm.store::tree_digest",
+ "pm.workspace::ResolutionConflict",
+ "pm.workspace::_is_member_candidate",
"pm.workspace::enabled_member_dirs",
+ "pm.workspace::enabled_plugin_dirs",
"pm.workspace::lock_and_sync",
+ "pm.workspace::member_sources",
"pm.workspace::members_stamp",
"pm::",
+ "pm::build_operations",
+ "pm::ensure_import",
+ "pm::operations",
"pm::paths",
"pm::receipt",
+ "tools.browser_tool::",
+ "tools.browser_tool::warm_agent_browser_npx_cache",
"tools.browser_tool_install::warm_agent_browser_npx_cache",
+ "tools.computer_use.cua_backend::cua_driver_runtime_contract_status",
+ "tools.computer_use.cua_backend::resolve_cua_driver_cmd",
+ "tools.computer_use.cua_backend_driver::cua_driver_runtime_contract_status",
+ "tools.computer_use.cua_backend_driver::resolve_cua_driver_cmd",
+ "tools.computer_use::cua_backend",
+ "tools.environments.local::_sanitize_subprocess_env",
+ "tools.environments.local::build_subprocess_env",
+ "tools.environments.local::hermes_subprocess_env",
+ "tools.environments::local",
+ "tools.lazy_deps::ensure",
+ "tools.lazy_deps::install_specs",
+ "tools.plugin_guard::format_scan_report",
+ "tools.plugin_guard::scan_plugin",
+ "tools.plugin_guard::should_allow_plugin_install",
+ "tools.registry::registry",
"tools.skills_sync::sync_skills",
- "utils::atomic_json_write"
+ "tools::",
+ "tools::skills_sync",
+ "utils::",
+ "utils::atomic_json_write",
+ "utils::atomic_roundtrip_yaml_update",
+ "utils::atomic_yaml_write",
+ "utils::env_var_enabled",
+ "utils::fast_safe_load"
],
"guarded_only": [
+ "agent.anthropic_adapter::is_claude_code_token_valid",
+ "agent.anthropic_adapter::read_claude_code_credentials",
+ "agent.deadline::kill_process_tree",
+ "agent.delegation_context::is_delegated_child_context",
+ "agent.delegation_context::is_delegated_child_process_context",
+ "agent.delegation_context::scrub_kanban_env",
+ "agent.outbound_webhooks::re_register_config_hooks",
+ "agent.secret_scope::UnscopedSecretError",
+ "agent.secret_scope::load_env_file",
+ "agent.secret_sources.bitwarden::BitwardenSource",
+ "agent.secret_sources.bitwarden::apply_bitwarden_secrets",
+ "agent.secret_sources.command::CommandSource",
+ "agent.secret_sources.onepassword::OnePasswordSource",
+ "agent.secret_sources.registry::BUILTIN_SOURCE_NAMES",
+ "agent.secret_sources.registry::apply_all",
+ "agent.secret_sources.registry::get_source",
+ "agent.secret_sources.registry::list_plugin_sources",
+ "agent.secret_sources.registry::list_sources",
+ "agent.shell_hooks::re_register_config_hooks",
+ "agent.skill_utils::ESSENTIAL_SKILLS",
+ "agent.skill_utils::SKILL_CONFIG_PREFIX",
+ "agent.skill_utils::discover_all_skill_config_vars",
+ "agent.terminal_env_registry::plugin_strip_env_keys",
"agent::curator",
+ "gateway.config::_env_multiplex_profiles_override",
+ "gateway.config::_normalize_multiplex_profile_allowlist",
+ "gateway.control_socket::identify_gateway",
"gateway.control_socket::pause_gateway_for_update",
- "hermes_cli._launchers::resolve_store_python",
+ "gateway.display_config::OVERRIDEABLE_KEYS",
+ "gateway.lifecycle_ledger::get_lifecycle_sentinel_path",
+ "gateway.session_context::_UNSET",
+ "gateway.session_context::_VAR_MAP",
+ "gateway.session_context::session_context_engaged",
+ "gateway.shutdown_watchdog::get_loop_heartbeat_path",
+ "gateway.shutdown_watchdog::get_loop_tick_socket_path",
+ "gateway.status::get_runtime_status_running_pid",
+ "gateway.status::remove_pid_file",
+ "gateway.status::runtime_status_pid_is_live",
+ "gateway.status::write_planned_stop_marker",
"hermes_cli._parser::build_top_level_parser",
"hermes_cli._subprocess_compat::",
+ "hermes_cli.agent_plugins::load_agent_plugin",
+ "hermes_cli.auth::LMSTUDIO_NOAUTH_PLACEHOLDER",
+ "hermes_cli.auth::has_usable_secret",
"hermes_cli.backup::create_pre_update_backup",
"hermes_cli.config::",
+ "hermes_cli.config::_deep_merge",
+ "hermes_cli.config::_expand_env_vars",
+ "hermes_cli.config::_normalize_root_model_keys",
+ "hermes_cli.config::_sanitize_env_lines",
+ "hermes_cli.config::apply_terminal_config_to_env",
"hermes_cli.config::get_config_value",
+ "hermes_cli.config::load_config_readonly",
+ "hermes_cli.config::read_raw_config",
"hermes_cli.config_defaults::",
"hermes_cli.config_migrations::",
"hermes_cli.dashboard_procs::",
+ "hermes_cli.env_loader::load_hermes_dotenv",
+ "hermes_cli.env_loader::reset_secret_source_cache",
"hermes_cli.gateway::_get_restart_exit_wait_budget",
+ "hermes_cli.gateway::_is_service_running",
+ "hermes_cli.gateway::ensure_gateway_service",
+ "hermes_cli.gateway::get_service_name",
+ "hermes_cli.gateway::get_systemd_linger_status",
+ "hermes_cli.gateway::is_linux",
"hermes_cli.gateway::is_windows",
- "hermes_cli.gateway::kill_gateway_processes",
+ "hermes_cli.gateway::named_profile_served_by_running_multiplexer",
+ "hermes_cli.gateway::refresh_launchd_plist_if_needed",
+ "hermes_cli.gateway_multiplex_served::live_default_gateway_pid",
+ "hermes_cli.gateway_multiplex_served::recorded_served_profiles",
+ "hermes_cli.gateway_windows::windowless_gateway_restart_spec",
"hermes_cli.macos_tcc_anchor::ensure_tcc_anchor",
+ "hermes_cli.managed_uv::_macos_sign_managed_python",
+ "hermes_cli.mcp_security::validate_mcp_server_entry",
"hermes_cli.memory_setup::_install_dependencies",
+ "hermes_cli.plugins::_env_enabled",
+ "hermes_cli.plugins::discover_plugins",
+ "hermes_cli.plugins::resolve_module_origin",
+ "hermes_cli.plugins_manifest::resolve_module_origin",
"hermes_cli.process_identity::REAPABLE_PURPOSES",
- "hermes_cli.runtime_state::recover_publication",
- "hermes_cli.runtime_state::runtime_lock",
+ "hermes_cli.profiles::_get_wrapper_dir",
+ "hermes_cli.profiles::_is_wrapper_dir_in_path",
+ "hermes_cli.profiles::check_alias_collision",
+ "hermes_cli.profiles::create_wrapper_script",
+ "hermes_cli.resource_limits::configured_nofile_soft_limit",
+ "hermes_cli.steward::STEWARD_APT_TERMUX",
+ "hermes_cli.steward::STEWARD_DOCKER",
+ "hermes_cli.steward::STEWARD_NIX",
+ "hermes_cli.steward::sealed_steward",
+ "hermes_cli.steward::steward_update_message",
+ "hermes_cli.toolset_scope::toolset_allowed_for_platform",
+ "hermes_cli.toolset_validation::validate_platform_toolsets",
"hermes_cli.update_channel::resolve_update_channel",
- "hermes_cli.version_info::get_code_identity",
+ "hermes_cli.update_cmd::",
+ "hermes_cli.update_receipt::current_correlation_id",
+ "hermes_cli.update_receipt::finalize_pending_update_receipt",
+ "hermes_cli::tools_config",
+ "hermes_constants::DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT",
+ "hermes_constants::PROJECT_ROOT",
+ "hermes_constants::validate_profile_name",
"hermes_state::SessionDB",
+ "plugins.memory.honcho.client::HonchoClientConfig",
+ "plugins.memory.honcho.client::get_honcho_client",
+ "plugins.memory.honcho::oauth",
+ "plugins.memory::_get_active_memory_provider",
+ "plugins.memory::load_memory_provider",
"pm.ensure::enabled_extras",
- "pm.extras::extra_supported",
- "pm.recovery::validate_environment"
+ "pm.recovery::repair_dependencies",
+ "tools.computer_use.cua_backend::cua_driver_child_env",
+ "tools.computer_use.cua_backend::cua_driver_update_check",
+ "tools.computer_use.cua_backend_driver::cua_driver_update_check",
+ "tools.env_passthrough::is_env_passthrough",
+ "tools.env_passthrough::resolve_passthrough_value",
+ "tools.environments.local::",
+ "tools.environments.local::_HERMES_PROVIDER_ENV_BLOCKLIST",
+ "tools.environments.local::_is_hermes_internal_secret",
+ "tools.environments.local_env_policy::_HERMES_PROVIDER_ENV_BLOCKLIST",
+ "tools.environments.local_env_policy::_is_hermes_internal_secret",
+ "tools.lazy_deps::",
+ "tools.lazy_deps::FeatureUnavailable",
+ "tools.skill_usage::read_suppressed_names",
+ "tools.skills_guard::content_hash",
+ "tools::lazy_deps"
]
}
diff --git a/tests/test_audit_old_updater_imports.py b/tests/test_audit_old_updater_imports.py
new file mode 100644
index 00000000000..257baef9a66
--- /dev/null
+++ b/tests/test_audit_old_updater_imports.py
@@ -0,0 +1,343 @@
+"""Exercise updater archaeology against real Git DAGs, not today's filenames."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+
+def audit(tmp_path, monkeypatch):
+ spec = importlib.util.spec_from_file_location(
+ "audit_old_updater_history_tests",
+ Path(__file__).resolve().parents[1] / "scripts/audit-old-updater-imports.py",
+ )
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ monkeypatch.setitem(sys.modules, spec.name, module)
+ spec.loader.exec_module(module)
+ monkeypatch.setattr(module, "REPO_ROOT", tmp_path)
+ git(tmp_path, "init", "-b", "main")
+ git(tmp_path, "config", "user.name", "Audit Test")
+ git(tmp_path, "config", "user.email", "[email protected]")
+ git(tmp_path, "config", "commit.gpgsign", "false")
+ return module
+
+
+def git(root, *args):
+ return subprocess.run(
+ ["git", *args], cwd=root, capture_output=True, text=True, check=True
+ ).stdout.strip()
+
+
+def put(root, path, source):
+ target = root / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(source, encoding="utf-8")
+
+
+def commit(root, message):
+ git(root, "add", ".")
+ git(root, "commit", "-m", message)
+ sha = git(root, "rev-parse", "HEAD")
+ git(root, "update-ref", "refs/remotes/origin/main", sha)
+ return sha
+
+
+def test_discovers_entrypoint_renames_extractions_and_deleted_helpers(audit):
+ root = audit.REPO_ROOT
+ put(root, "hermes_cli/ancient.py", "def cmd_update():\n from hermes_constants import first\n")
+ first = commit(root, "first updater at an unknown address")
+ git(root, "mv", "hermes_cli/ancient.py", "hermes_cli/briefly.py")
+ renamed = commit(root, "rename without editing the blob")
+ put(root, "hermes_cli/briefly.py", "from hermes_cli.gone import phase\ndef cmd_update():\n phase()\n")
+ put(root, "hermes_cli/gone.py", "def phase():\n from hermes_constants import extracted\n")
+ extracted = commit(root, "extract a helper under an unrelated filename")
+ git(root, "mv", "hermes_cli/gone.py", "hermes_cli/later.py")
+ put(root, "hermes_cli/briefly.py", "from hermes_cli.later import phase\ndef cmd_update():\n phase()\n")
+ commit(root, "rename the extracted helper")
+ git(root, "rm", "hermes_cli/briefly.py", "hermes_cli/later.py")
+ put(root, "hermes_cli/update_cmd.py", "def cmd_update():\n from hermes_constants import newest\n")
+ commit(root, "delete every historical filename")
+
+ surface = audit.audit_history()
+ assert {("hermes_constants", s) for s in ("first", "extracted", "newest")} <= surface.required.keys()
+ assert {
+ "hermes_cli/ancient.py:cmd_update", "hermes_cli/briefly.py:cmd_update"
+ } <= surface.sites[("hermes_constants", "first")]
+ assert first[:12] in surface.required[("hermes_constants", "first")]
+ assert renamed[:12] in surface.required[("hermes_constants", "first")]
+ assert extracted[:12] in surface.required[("hermes_constants", "extracted")]
+ assert {
+ "hermes_cli/gone.py:phase", "hermes_cli/later.py:phase"
+ } <= surface.sites[("hermes_constants", "extracted")]
+ assert surface.stats["commits"] == int(git(root, "rev-list", "--count", "origin/main"))
+ assert surface.stats["complete_history"] is True
+ assert surface.stats["history_ref"] == git(root, "rev-parse", "origin/main")
+ assert surface.stats["roots"] == [first]
+ assert {"hermes_cli/ancient.py", "hermes_cli/briefly.py"} <= set(surface.stats["entrypoint_paths"])
+ assert {"hermes_cli/gone.py", "hermes_cli/later.py"} <= set(surface.stats["files_analyzed"])
+ assert not any(root.glob("hermes_cli/*gone*"))
+ assert audit.audit_tree().required.keys() == {("hermes_constants", "newest")}
+
+
+def test_all_merge_parents_and_merge_result_but_not_unmerged_branches(audit):
+ root = audit.REPO_ROOT
+ path = "hermes_cli/prehistoric.py"
+ put(root, path, "def cmd_update():\n pass\n")
+ base = commit(root, "base")
+ git(root, "checkout", "-b", "side")
+ put(root, path, "def cmd_update():\n from hermes_constants import side_only\n")
+ side = commit(root, "side updater")
+ git(root, "checkout", "main")
+ put(root, path, "def cmd_update():\n from hermes_constants import main_only\n")
+ commit(root, "main updater")
+ # An ours merge is TREESAME to main. Ordinary path-limited git log
+ # simplifies away the side parent and its real shipped revision.
+ git(root, "merge", "-s", "ours", "--no-ff", "side", "-m", "discard side changes")
+ commit_sha = git(root, "rev-parse", "HEAD")
+ git(root, "update-ref", "refs/remotes/origin/main", commit_sha)
+ assert side[:12] in audit.audit_history().required[("hermes_constants", "side_only")]
+ git(root, "checkout", "-b", "other", base)
+ put(root, "unrelated.txt", "new branch\n")
+ commit(root, "unrelated change")
+ git(root, "checkout", "main")
+ git(root, "merge", "--no-ff", "--no-commit", "other")
+ put(root, path, "def cmd_update():\n from hermes_constants import merge_only\n")
+ merged = commit(root, "updater code created only by merge resolution")
+ git(root, "checkout", "-b", "unshipped", base)
+ put(root, path, "def cmd_update():\n from hermes_constants import never_shipped\n")
+ commit(root, "unmerged branch")
+ git(root, "update-ref", "refs/remotes/origin/main", merged)
+
+ surface = audit.audit_history()
+ assert {s for m, s in surface.required if m == "hermes_constants"} == {
+ "side_only", "main_only", "merge_only"
+ }
+ assert merged[:12] in surface.required[("hermes_constants", "merge_only")]
+ assert surface.stats["commits"] == int(git(root, "rev-list", "--count", "origin/main"))
+
+
+def test_deleted_siblings_and_renamed_seed_helper_are_not_tied_to_head(audit):
+ root = audit.REPO_ROOT
+ put(root, "hermes_cli/update_cmd.py", "def cmd_update():\n pass\n")
+ put(root, "hermes_cli/old_support.py", "def old_phase():\n from hermes_constants import before_rename\n")
+ commit(root, "support before its known name")
+ git(root, "mv", "hermes_cli/old_support.py", "hermes_cli/post_update.py")
+ put(root, "hermes_cli/update_cmd_removed.py", "def phase():\n from hermes_constants import deleted_sibling\n")
+ commit(root, "known helper and temporary extraction")
+ git(root, "rm", "hermes_cli/post_update.py", "hermes_cli/update_cmd_removed.py")
+ commit(root, "remove both helpers")
+ surface = audit.audit_history()
+ assert {("hermes_constants", s) for s in ("before_rename", "deleted_sibling")} <= surface.required.keys()
+ assert "hermes_cli/old_support.py:old_phase" in surface.sites[("hermes_constants", "before_rename")]
+ assert not audit.audit_tree().required
+
+
+def test_shallow_clone_refuses_freeze_without_overwriting_and_tree_still_works(audit, tmp_path, monkeypatch, capsys):
+ root = audit.REPO_ROOT
+ put(root, "hermes_cli/unknown.py", "def cmd_update():\n from hermes_constants import old\n")
+ commit(root, "historical contract")
+ put(root, "hermes_cli/unknown.py", "def cmd_update():\n from hermes_constants import current\n")
+ commit(root, "current contract")
+ clone = tmp_path / "shallow"
+ git(root, "clone", "--depth=1", root.as_uri(), str(clone))
+ monkeypatch.setattr(audit, "REPO_ROOT", clone)
+ assert git(clone, "rev-parse", "--is-shallow-repository") == "true"
+ with pytest.raises(audit.AuditError, match="shallow"):
+ audit.audit_history()
+ assert set(audit.audit_tree().required) == {("hermes_constants", "current")}
+ output = clone / "frozen.json"
+ output.write_text("do not truncate this", encoding="utf-8")
+ with pytest.raises(SystemExit) as failure:
+ audit.main(["--freeze", str(output)])
+ assert failure.value.code != 0
+ assert "--unshallow" in capsys.readouterr().err
+ assert output.read_text() == "do not truncate this"
+
+
+def test_union_keeps_old_and_uncommitted_loads_and_bare_wins(audit, tmp_path):
+ root = audit.REPO_ROOT
+ put(root, "hermes_cli/update_cmd.py", """def cmd_update():
+ from hermes_constants import old_only, bare_then_guarded
+ try:
+ from hermes_constants import guarded_then_bare, always_guarded
+ except ImportError:
+ pass
+""")
+ commit(root, "not a tag, still a shipped updater")
+ put(root, "hermes_cli/update_cmd.py", """def cmd_update():
+ from hermes_constants import new_only, guarded_then_bare
+ try:
+ from hermes_constants import bare_then_guarded, always_guarded
+ except ImportError:
+ pass
+""")
+ output = tmp_path / "union.json"
+ assert audit.main(["--freeze", str(output)]) == 0
+ frozen = json.loads(output.read_text())
+ assert set(frozen["bare"]) == {
+ "hermes_constants::old_only", "hermes_constants::new_only",
+ "hermes_constants::bare_then_guarded", "hermes_constants::guarded_then_bare",
+ }
+ assert frozen["guarded_only"] == ["hermes_constants::always_guarded"]
+ assert frozen["stats"]["mode"] == "union"
+ assert frozen["stats"]["history"]["complete_history"] is True
+
+
[email protected]("malformed", [b"def cmd_update(:\n", b"def cmd_update():\n # \xff\n pass\n"])
+def test_malformed_historical_entrypoint_fails_closed(audit, malformed):
+ root = audit.REPO_ROOT
+ target = root / "forgotten.py"
+ target.write_bytes(malformed)
+ commit(root, "broken historical source")
+ put(root, "forgotten.py", "def cmd_update():\n pass\n")
+ commit(root, "repaired at tip")
+ with pytest.raises(audit.AuditError, match="forgotten.py.*blob"):
+ audit.audit_history()
+
+
+def test_committed_merge_conflict_audits_both_arms_and_records_recovery(audit):
+ root = audit.REPO_ROOT
+ put(root, "old.py", """<<<<<<< HEAD
+def cmd_update():
+ from hermes_constants import ours
+=======
+def cmd_update():
+ from hermes_constants import theirs
+>>>>>>> incoming
+""")
+ commit(root, "accidentally committed conflict")
+ put(root, "old.py", "def cmd_update():\n pass\n")
+ commit(root, "fix conflict")
+ surface = audit.audit_history()
+ assert {("hermes_constants", "ours"), ("hermes_constants", "theirs")} <= surface.required.keys()
+ assert any("old.py" in recovery for recovery in surface.parse_recoveries)
+
+
+def test_identical_blobs_have_path_specific_relative_imports_and_seed_roles(audit):
+ root = audit.REPO_ROOT
+ source = "def cmd_update():\n from .constants import important\ndef unrelated():\n from hermes_constants import helper_only\n"
+ put(root, "hermes_cli/unknown.py", source)
+ put(root, "hermes_cli/post_update.py", source)
+ put(root, "pm/unknown.py", source)
+ commit(root, "identical source, distinct modules and seed modes")
+ surface = audit.audit_history()
+ assert ("hermes_cli.constants", "important") in surface.required
+ assert ("pm.constants", "important") in surface.required
+ assert surface.sites[("hermes_constants", "helper_only")] == {"hermes_cli/post_update.py:unrelated"}
+
+
+def test_only_swallowed_matching_load_failures_are_guarded(audit):
+ root = audit.REPO_ROOT
+ put(root, "hermes_cli/update_cmd.py", """def cmd_update():
+ import sys
+ try:
+ from hermes_constants import wrong_exception
+ except AttributeError:
+ pass
+ try:
+ from hermes_constants import name_not_module
+ except ModuleNotFoundError:
+ pass
+ try:
+ from hermes_constants import reraised
+ except ImportError:
+ raise
+ try:
+ module = sys.modules.get("hermes_constants")
+ getattr(module, "optional")
+ except AttributeError:
+ pass
+""")
+ commit(root, "exception boundaries")
+ surface = audit.audit_history()
+ assert surface.guarded_only == {("hermes_constants", "optional")}
+ assert {("hermes_constants", s) for s in ("wrong_exception", "name_not_module", "reraised")} <= surface.required.keys()
+
+
+def test_lazy_module_facade_follows_called_helper_not_unrelated_commands(audit):
+ root = audit.REPO_ROOT
+ put(root, "hermes_cli/entry.py", """def _m():
+ from hermes_cli import main
+ return main
+
+def cmd_update():
+ _m().phase()
+""")
+ put(root, "hermes_cli/main.py", """from hermes_cli.gone import phase as phase
+
+def unrelated_command():
+ from hermes_constants import not_an_updater_load
+""")
+ put(root, "hermes_cli/gone.py", "def phase():\n from hermes_constants import actual_helper_load\n")
+ commit(root, "lazy facade and re-exported helper")
+ surface = audit.audit_history()
+ assert ("hermes_constants", "actual_helper_load") in surface.required
+ assert ("hermes_constants", "not_an_updater_load") not in surface.required
+
+
+def test_resolver_requires_a_module_binding_not_a_nested_name(audit):
+ root = audit.REPO_ROOT
+ put(root, "hermes_constants.py", """def owner():
+ from pathlib import Path as local_import
+ local_assignment = 1
+ def local_function():
+ pass
+
+class Owner:
+ def method(self):
+ pass
+
+if True:
+ from pathlib import Path as exported
+ value = 1
+""")
+ for symbol in ("local_import", "local_assignment", "local_function", "method"):
+ assert not audit.resolve_in_tree("hermes_constants", symbol, root)[0], symbol
+ for symbol in ("owner", "Owner", "exported", "value"):
+ assert audit.resolve_in_tree("hermes_constants", symbol, root)[0], symbol
+
+
+def test_same_named_functions_keep_requirements_from_every_definition(audit):
+ result = audit.analyse("""class First:
+ def phase(self):
+ from hermes_constants import first
+
+class Second:
+ def phase(self):
+ from hermes_constants import second
+
+if True:
+ def platform_phase():
+ from hermes_constants import platform_a
+else:
+ def platform_phase():
+ from hermes_constants import platform_b
+
+def cmd_update():
+ Second().phase()
+ platform_phase()
+""", "hermes_cli/update_cmd.py", entrypoints=True)
+ assert {r.symbol for r in result.requirements} == {
+ "first", "second", "platform_a", "platform_b",
+ }
+
+
+def test_reviewed_dynamic_loads_survive_union_regeneration(audit, monkeypatch):
+ root = audit.REPO_ROOT
+ put(root, "hermes_cli/update_cmd.py", "def cmd_update():\n from hermes_constants import anchor\n")
+ witness = commit(root, "module-object call manually reviewed")
+ monkeypatch.setattr(audit, "REVIEWED_DYNAMIC_LOADS", (
+ ("hermes_constants", "dynamic", witness[:12], "hermes_cli/update_cmd.py:cmd_update"),
+ ("hermes_constants", "unshipped", "not-a-witness", "other.py:cmd_update"),
+ ))
+ surface = audit.audit_union()
+ assert ("hermes_constants", "dynamic") in surface.required
+ assert ("hermes_constants", "dynamic") not in surface.guarded_only
+ assert ("hermes_constants", "unshipped") not in surface.required
diff --git a/tests/test_old_updater_additional_shims.py b/tests/test_old_updater_additional_shims.py
new file mode 100644
index 00000000000..77c456d4dd7
--- /dev/null
+++ b/tests/test_old_updater_additional_shims.py
@@ -0,0 +1,131 @@
+"""Retired import names suppress old updater work without claiming success."""
+
+import importlib
+import os
+from pathlib import Path
+import socket
+import subprocess
+import urllib.request
+
+import pytest
+
+
+def no_external_work(monkeypatch):
+ import pm
+
+ def forbidden(*args, **kwargs):
+ pytest.fail("old-updater shim attempted external work")
+
+ for name in ("sync_venv", "ensure_environment", "build_environment", "ensure_import"):
+ monkeypatch.setattr(pm, name, forbidden)
+ monkeypatch.setattr(subprocess, "Popen", forbidden)
+ monkeypatch.setattr(os, "system", forbidden)
+ monkeypatch.setattr(os, "kill", forbidden)
+ monkeypatch.setattr(socket, "create_connection", forbidden)
+ monkeypatch.setattr(urllib.request, "urlopen", forbidden)
+ monkeypatch.setattr(urllib.request, "urlretrieve", forbidden)
+ before_env = {k: v for k, v in os.environ.items() if k != "PYTEST_CURRENT_TEST"}
+ home = Path(os.environ["HERMES_HOME"])
+ before_files = {p: p.read_bytes() for p in home.rglob("*") if p.is_file()}
+ yield forbidden
+ assert {k: v for k, v in os.environ.items() if k != "PYTEST_CURRENT_TEST"} == before_env
+ assert {p: p.read_bytes() for p in home.rglob("*") if p.is_file()} == before_files
+
+
[email protected]("command", ["", "hermes -p ops gateway run", "hermes --profile=ops gateway run"])
+def test_retired_profile_probe_returns_unknown(command, no_external_work):
+ from gateway.status import profile_flag_value
+
+ # The old scanner compares this value to a profile before selecting a PID.
+ assert profile_flag_value(command) is None
+
+
[email protected]("refresh", [False, True])
+def test_retired_code_identity_is_unknown(refresh, no_external_work, monkeypatch):
+ from hermes_cli import version_info
+ from hermes_cli.build_info import get_code_identity
+
+ monkeypatch.setattr(version_info, "get_code_identity", no_external_work)
+ identity = get_code_identity(refresh=refresh)
+ assert identity == {"sha": None, "short_sha": None, "version": None, "source": "unknown"}
+ identity["sha"] = "caller mutation"
+ assert get_code_identity(refresh)["sha"] is None
+
+
+def test_retired_constants_reload_does_not_replace_live_module(no_external_work, monkeypatch):
+ import hermes_constants
+ from hermes_cli.managed_uv import _reload_hermes_constants
+
+ before = dict(vars(hermes_constants))
+ monkeypatch.setattr(importlib, "reload", no_external_work)
+ assert _reload_hermes_constants() is None
+ assert vars(hermes_constants) == before
+
+
[email protected]("kwargs", [{}, {"timeout": 120, "capture_output": False}])
+def test_retired_pip_install_stops_before_reporting_success(kwargs, no_external_work, capsys):
+ from hermes_cli.tools_config import _pip_install
+
+ with pytest.raises(SystemExit) as exc:
+ result = _pip_install(["--quiet", "honcho-ai"], **kwargs)
+ pytest.fail(f"retired installer returned a result: {result}")
+ assert exc.value.code == 0
+ assert "relaunch" in capsys.readouterr().err.lower()
+
+
+def test_retired_root_stops_before_inventing_portable_git_path(no_external_work, capsys):
+ from hermes_cli.update_cmd import get_default_hermes_root
+
+ with pytest.raises(SystemExit) as exc:
+ get_default_hermes_root() / "git" / "mingw64" / "libexec" / "git-core" / "git.exe"
+ assert exc.value.code == 0
+ assert "relaunch" in capsys.readouterr().err.lower()
+
+
[email protected]("prompt", [True, False])
+def test_retired_ensure_reports_unavailable_without_installing(prompt, no_external_work):
+ from tools.lazy_deps import ensure
+
+ # Dependency-unavailable callers must not mistake a no-op for readiness.
+ with pytest.raises(ImportError, match="relaunch"):
+ ensure("memory.honcho", prompt=prompt)
+
+
+def test_live_dingtalk_dependencies_use_pm_not_retired_installer(monkeypatch):
+ from plugins.platforms.dingtalk import adapter
+ from pm import extras
+
+ requested = []
+
+ def unavailable(extra):
+ requested.append(extra)
+ raise ImportError("dependency unavailable")
+
+ monkeypatch.setattr(adapter, "DINGTALK_STREAM_AVAILABLE", False)
+ monkeypatch.setattr(extras, "ensure_import", unavailable)
+ assert adapter.ensure_dingtalk_deps() is False
+ assert requested == ["dingtalk"]
+
+
[email protected]("specs", [[], ["honcho-ai"]])
+def test_retired_install_specs_stops_before_reporting_success(specs, no_external_work, capsys):
+ from tools.lazy_deps import install_specs
+
+ with pytest.raises(SystemExit) as exc:
+ result = install_specs(specs, timeout=120)
+ pytest.fail(f"retired installer returned a result: {result}")
+ assert exc.value.code == 0
+ assert "relaunch" in capsys.readouterr().err.lower()
+
+
+def test_retired_subprocess_run_stops_powershell_installer(no_external_work, capsys):
+ from hermes_cli import _subprocess_compat
+
+ with pytest.raises(SystemExit) as exc:
+ _subprocess_compat.run(
+ ["powershell", "-ExecutionPolicy", "Bypass", "-c", "irm https://astral.sh/uv/install.ps1 | iex"],
+ env=dict(os.environ), check=True, capture_output=True,
+ )
+ assert exc.value.code == 0
+ assert "relaunch" in capsys.readouterr().err.lower()
diff --git a/tests/test_old_updater_compat_surface.py b/tests/test_old_updater_compat_surface.py
index 16d279dde12..d4fea54bf66 100644
--- a/tests/test_old_updater_compat_surface.py
+++ b/tests/test_old_updater_compat_surface.py
@@ -3,13 +3,15 @@
`hermes update` replaces the checkout underneath a RUNNING process. The
old process then lazy-imports from the new tree: whatever it asks for
must still exist, or the user's update dies half-applied. The names it
-can ask for were collected by auditing the update flow in this tree
-(scripts/audit-old-updater-imports.py) and frozen into
-tests/compat/old_updater_surface.json. The pm rewrite retired the
-lineage the original shipped-history walk froze (installation/*,
-hermes_cli.managed_uv), so the frozen contract here is the CURRENT
-updater's mid-swap loads; releases cut from this branch re-enter the
-surface by regenerating against the tree that shipped them.
+can ask for were collected from EVERY commit reachable from origin/main,
+back to the first cmd_update, UNION the current working tree, and frozen
+into tests/compat/old_updater_surface.json. Moving the implementation to
+pm does not retire already-running old updaters. Historical entrypoints,
+extractions, renamed and deleted helpers remain part of the contract.
+
+Regeneration requires a full clone. These tests deliberately consume the
+checked-in history and only re-audit the current tree, so shallow CI can
+enforce the contract without reconstructing (or silently truncating) it.
`managed_uv._reload_hermes_constants` is the scar proving the failure
mode is real: a live updater hit ``cannot import name 'venv_python_path'
@@ -98,6 +100,8 @@ class TestTheFrozenFileIsSane:
"hermes_constants::with_hermes_node_path",
"pm.ensure::sync_venv",
"hermes_cli.gitlock::clear_stale_git_locks",
+ "hermes_cli.managed_uv::ensure_uv",
+ "hermes_cli.managed_uv::rebuild_venv",
):
assert anchor in bare, (
f"{anchor} missing from the frozen surface — the freeze "
@@ -107,11 +111,20 @@ class TestTheFrozenFileIsSane:
def test_audit_saw_the_whole_update_flow(self):
stats = _load_surface()["stats"]
- assert stats.get("mode") == "tree", (
- "frozen surface is not a tree-mode freeze — regenerate with "
- "scripts/audit-old-updater-imports.py --freeze (no --history)."
+ assert stats.get("mode") == "union", (
+ "frozen surface must include history AND the current tree — "
+ "regenerate on a full clone with scripts/"
+ "audit-old-updater-imports.py --freeze (no --history)."
+ )
+ history = stats["history"]
+ assert history.get("complete_history") is True
+ assert history["commits"] > 0
+ assert history["roots"] and history["entrypoint_paths"]
+ assert "hermes_cli/main.py" in history["entrypoint_paths"], (
+ "the freeze omitted the original inline cmd_update history"
)
- analyzed = set(stats.get("files_analyzed", []))
+ assert history["history_ref"]
+ analyzed = set(stats["tree"]["files_analyzed"])
for must_see in ("hermes_cli/update_cmd.py", "pm/ensure.py"):
assert must_see in analyzed, (
f"{must_see} was not analyzed for the freeze — the audit "
@@ -119,19 +132,23 @@ class TestTheFrozenFileIsSane:
f"cannot guard anything."
)
- def test_frozen_matches_a_fresh_audit(self):
- # A new lazy import in the update flow must not slip in unrecorded:
- # the frozen file and a fresh audit of this tree must agree.
+ def test_frozen_contains_a_fresh_tree_audit(self):
+ # Shallow CI checks a subset, NOT equality: deleted historical loads
+ # must survive even when today's updater no longer imports them.
fresh = _audit.audit_tree()
- fresh_bare = sorted(
+ fresh_bare = {
f"{m}::{s}"
for (m, s) in fresh.required
if (m, s) not in fresh.guarded_only
+ }
+ frozen = _load_surface()
+ frozen_bare = set(frozen["bare"])
+ assert fresh_bare <= frozen_bare, (
+ f"new bare updater loads are unfrozen: {sorted(fresh_bare - frozen_bare)}. "
+ "Run scripts/audit-old-updater-imports.py --freeze "
+ "tests/compat/old_updater_surface.json on a full clone."
)
- frozen_bare = _load_surface()["bare"]
- assert fresh_bare == frozen_bare, (
- "the update flow's bare mid-swap loads changed but the frozen "
- "surface was not regenerated — run scripts/"
- "audit-old-updater-imports.py --freeze "
- "tests/compat/old_updater_surface.json and review the diff."
- )
+ fresh_all = {f"{m}::{s}" for m, s in fresh.required}
+ frozen_all = frozen_bare | set(frozen["guarded_only"])
+ assert fresh_all <= frozen_all
+ assert not frozen_bare & set(frozen["guarded_only"])
diff --git a/tests/test_old_updater_main_shims.py b/tests/test_old_updater_main_shims.py
new file mode 100644
index 00000000000..68a8b21309b
--- /dev/null
+++ b/tests/test_old_updater_main_shims.py
@@ -0,0 +1,111 @@
+"""Historical main imports must not restart pre-PM updater work after a swap."""
+
+import os
+from pathlib import Path
+import socket
+import subprocess
+import urllib.request
+
+import pytest
+
+
+def inert_main(monkeypatch):
+ # Import real current modules before guarding work: CLI startup is not a shim.
+ from hermes_cli import main
+ import pm
+
+ def forbidden(*args, **kwargs):
+ pytest.fail("historical main shim attempted updater work")
+
+ for name in ("sync_venv", "ensure_environment", "build_environment"):
+ monkeypatch.setattr(pm, name, forbidden)
+ for name in ("Popen", "run"):
+ monkeypatch.setattr(subprocess, name, forbidden)
+ for name in ("system", "kill", "rename", "replace", "unlink", "mkdir"):
+ monkeypatch.setattr(os, name, forbidden)
+ for name in ("write_text", "write_bytes", "touch", "rename", "replace", "unlink", "mkdir"):
+ monkeypatch.setattr(Path, name, forbidden)
+ monkeypatch.setattr(socket, "create_connection", forbidden)
+ monkeypatch.setattr(urllib.request, "urlopen", forbidden)
+ monkeypatch.setattr(urllib.request, "urlretrieve", forbidden)
+ return main, forbidden
+
+
+def test_historical_main_data_and_skipped_probes_preserve_caller_shapes(inert_main, tmp_path):
+ main, _ = inert_main
+ from hermes_cli import main_web_build
+
+ # Old recorders compose this name with PROJECT_ROOT. It remains data only.
+ assert tmp_path / main._BYTECODE_FINGERPRINT_FILE == (
+ tmp_path / main_web_build._BYTECODE_FINGERPRINT_FILE
+ )
+ failed = ["hermes.exe"]
+ try:
+ raise main.ShimQuarantineError(failed)
+ except main.ShimQuarantineError as exc:
+ assert isinstance(exc, RuntimeError)
+ assert exc.failed_shims == failed
+ assert exc.failed_shims is not failed
+ assert failed[0] in str(exc)
+
+ prefix = ["uv", "pip"]
+ env = {"VIRTUAL_ENV": str(tmp_path)}
+ # None means indeterminate to the historical repair caller, NOT healthy [].
+ assert main._detect_broken_lazy_refresh_imports(prefix, env=env) is None
+ assert main._resolve_install_target_python(prefix, env) is None
+ moved = [(tmp_path / "hermes.exe", tmp_path / "hermes.exe.old")]
+ before = list(moved)
+ assert main._restore_quarantined_exes(moved) is None
+ assert moved == before
+ assert main._write_web_ui_build_stamp(tmp_path, tmp_path / "web") is None
+ assert prefix == ["uv", "pip"]
+ assert env == {"VIRTUAL_ENV": str(tmp_path)}
+
+
+def test_historical_main_entrypoints_stop_before_install_or_success_fallback(
+ inert_main, tmp_path, capsys,
+):
+ main, forbidden = inert_main
+ cmd = ["uv", "pip", "install", "-e", "."]
+ env = {"VIRTUAL_ENV": str(tmp_path)}
+ failed = []
+ calls = [
+ ("_desktop_stamp_path", (), {}),
+ ("_expected_windows_pe_machines", (), {}),
+ ("_hermes_exe_shims", (tmp_path,), {}),
+ ("_insert_python_pin", (cmd,), {}),
+ ("_interpreter_scripts_dir", (), {}),
+ ("_load_installable_optional_extras", (), {"group": "termux-all"}),
+ ("_parse_pe_machine", (tmp_path / "Hermes.exe",), {}),
+ ("_quarantine_running_hermes_exe", (tmp_path,), {"max_attempts": 1, "failed_out": failed}),
+ ("_repair_broken_lazy_refresh_imports", (cmd[:2], ["certifi"]), {"env": env}),
+ ("_run_install_with_heartbeat", (cmd,), {"env": env, "heartbeat_interval_seconds": 1}),
+ ("_run_package_only_install", (cmd,), {"env": env}),
+ ("_run_quarantined_install", (cmd,), {"env": env, "scripts_dir": tmp_path, "strict_quarantine": True}),
+ ("_run_quarantined_install", (cmd,), {}),
+ ("_run_with_idle_timeout", (cmd, tmp_path), {"env": env, "idle_timeout_seconds": 1, "indent": ""}),
+ ("_self", (), {}),
+ ("_verify_console_scripts_installed", (cmd[:2],), {"env": env}),
+ ("_verify_core_dependencies_installed", (cmd[:2],), {"env": env, "group": "all"}),
+ ("_web_ui_build_needed", (tmp_path / "web",), {}),
+ ("_windows_native_machine", (), {}),
+ ("_windows_shim_in_process_chain", (), {}),
+ ]
+ before_env = dict(os.environ)
+ for name, args, kwargs in calls:
+ shim = getattr(main, name)
+ with pytest.raises(SystemExit) as exc:
+ try:
+ shim(*args, **kwargs)
+ except Exception:
+ # Historical installers catch ordinary failures to retry pip/uv.
+ forbidden()
+ # Returning also lets old callers claim completion or try a fallback.
+ forbidden()
+ assert exc.value.code == 0, name
+ assert "relaunch" in capsys.readouterr().err.lower(), name
+ assert cmd == ["uv", "pip", "install", "-e", "."]
+ assert env == {"VIRTUAL_ENV": str(tmp_path)}
+ assert failed == []
+ assert dict(os.environ) == before_env
diff --git a/tools/lazy_deps.py b/tools/lazy_deps.py
new file mode 100644
index 00000000000..d106d2a2121
--- /dev/null
+++ b/tools/lazy_deps.py
@@ -0,0 +1,16 @@
+"""Shims to suppress old updater work until relaunch. New code must not use these."""
+
+from typing import NoReturn
+
+from hermes_cli._old_updater import stop_for_relaunch
+
+
+def ensure(feature: str, *, prompt: bool = True) -> NoReturn:
+ # Shim to suppress old updater work until relaunch. Do not claim readiness.
+ # Preserve the dependency-unavailable failure without claiming a completed install.
+ raise ImportError("Dependencies are unknown to this old updater. Please relaunch Hermes.")
+
+
+def install_specs(specs: list[str] | tuple[str, ...], *, timeout: int = 300) -> NoReturn:
+ # Shim to suppress old updater work until relaunch. Do not install or report success.
+ stop_for_relaunch()