The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): refresh a stale editable finder before skipping reinstall
joaomarcos60a088795da6
diff --git a/hermes_cli/main_install_repair.py b/hermes_cli/main_install_repair.pyindex 6e1fd553530..33e17f0bc95 100644--- a/hermes_cli/main_install_repair.py+++ b/hermes_cli/main_install_repair.py@@ -951,7 +951,8 @@ def _interpreter_scripts_dir() -> Path | None:def _install_python_dependencies_with_optional_fallback(- install_cmd_prefix: list[str], *, env: dict[str, str] | None = None, group: str = "all"+ install_cmd_prefix: list[str], *, env: dict[str, str] | None = None, group: str = "all",+ reinstall: bool = False,) -> None:"""Install base deps plus as many optional extras as the environment supports.@@ -980,6 +981,8 @@ def _install_python_dependencies_with_optional_fallback(scripts_dir = _interpreter_scripts_dir()def _install(args: list[str]) -> None:+ if reinstall:+ args = [args[0], "--reinstall", *args[1:]]if pin_python:args = _insert_python_pin(args)# strict_quarantine: this is the UPDATE dependency sync; ShimQuarantineError propagatesdiff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.pyindex 6cee9656c06..1bacabf4e4d 100644--- a/hermes_cli/update_cmd_deps.py+++ b/hermes_cli/update_cmd_deps.py@@ -4,12 +4,14 @@ npm/Desktop rebuilds, self-lock deferral. Names are re-imported by ``update_cmd`import loggingfrom contextlib import suppress+import astimport hashlibimport jsonimport osimport shutilimport subprocessimport sys+import tomllibfrom pathlib import Pathfrom typing import Optionalfrom hermes_constants import project_venv_dir, venv_python_path@@ -22,11 +24,83 @@ logger = logging.getLogger("hermes_cli.update_cmd")_INSTALL_DEFINING_FILES = "pyproject.toml", "setup.py", "setup.cfg", "MANIFEST.in", "uv.lock"+def _mapping_literal(tree: ast.AST):+ """The setuptools finder uses ``MAPPING: dict[str, str] = {...}``, not a bare assign."""+ for node in tree.body:+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == "MAPPING":+ return ast.literal_eval(node.value)+ if isinstance(node, ast.Assign) and any(+ isinstance(target, ast.Name) and target.id == "MAPPING" for target in node.targets+ ):+ return ast.literal_eval(node.value)+ return None+++def _checkout_import_names(root: Path) -> set[str]:+ """Top-level names an editable install records: root modules plus configured packages."""+ names = {path.stem for path in root.glob("*.py") if path.name != "setup.py"}+ with (root / "pyproject.toml").open("rb") as stream:+ includes = (+ tomllib.load(stream)+ .get("tool", {})+ .get("setuptools", {})+ .get("packages", {})+ .get("find", {})+ .get("include", [])+ )+ prefixes = {item.removesuffix(".*") for item in includes if isinstance(item, str)}+ names.update(+ path.name+ for path in root.iterdir()+ if path.is_dir() and (path / "__init__.py").is_file() and path.name in prefixes+ )+ return names+++def _editable_finder_files(venv: Path) -> list[Path]:+ sites = [*venv.glob("lib/python*/site-packages"), venv / "Lib" / "site-packages"]+ return [+ finder+ for site in sites+ if site.is_dir()+ for finder in site.glob("__editable__*hermes_agent*finder.py")+ ]+++def _editable_finder_mapping_current(cwd) -> bool | None:+ """None when the install venv has no static finder; False when its map misses the checkout.++ Module entries point at the stem (``cli``, not ``cli.py``). Existence of that+ path is not the contract — the key set is. A dangling path is a different repair.+ """+ root = Path(cwd)+ venv = project_venv_dir(root)+ if venv is None:+ return None+ finders = _editable_finder_files(venv)+ if not finders:+ return None+ try:+ inventory = _checkout_import_names(root)+ for finder in finders:+ mapping = _mapping_literal(ast.parse(finder.read_text(encoding="utf-8")))+ if not isinstance(mapping, dict) or set(mapping) != inventory:+ return False+ except (OSError, SyntaxError, ValueError, TypeError, AttributeError):+ return False+ return True++def _editable_install_is_current(git_cmd, cwd, pre_pull_sha: str | None) -> bool:- """True when the pulled commits cannot have invalidated the editable install: ``uv pip install- -e .`` always rewrites console-script shims (Windows: ``hermes.exe`` quarantine, ``os error 32``- on a lost race), so skip it when only non-install files changed. Safe because the editable- finder uses a *static* module list. Fails closed: no pre-pull SHA or failed diff -> False."""+ """True when the pull cannot invalidate the editable install.++ ``uv pip install -e .`` rewrites console-script shims. On Windows that rewrite+ quarantines the running ``hermes.exe``, and a lost race is the ``os error 32``+ family, so skip it only when packaging files are unchanged and the installed+ finder still names every top-level import the checkout exposes. No finder keeps+ the packaging-file gate. An unreadable finder, or a map that disagrees with the+ checkout, is not current. No pre-pull SHA or a failed diff fails closed.+ """if not pre_pull_sha:return Falsetry:@@ -35,7 +109,10 @@ def _editable_install_is_current(git_cmd, cwd, pre_pull_sha: str | None) -> boolcwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace")except OSError:return False- return result.returncode == 0 and not result.stdout.strip()+ if result.returncode != 0 or result.stdout.strip():+ return False+ mapping_current = _editable_finder_mapping_current(cwd)+ return mapping_current is not False# Modules imported on every startup. Unlike _UPDATE_CRITICAL_FILES (only parsed) these are@@ -1122,6 +1199,7 @@ def _sync_python_dependencies_after_pull(# by the next launch (``_recover_from_interrupted_install``). Lazy refresh uses its own marker._write_update_incomplete_marker()deps_current = _editable_install_is_current(git_cmd, _m().PROJECT_ROOT, pre_pull_sha)+ mapping_current = _editable_finder_mapping_current(_m().PROJECT_ROOT)print("→ Python dependencies unchanged — skipping reinstall" if deps_currentelse "→ Updating Python dependencies...")@@ -1154,7 +1232,8 @@ def _sync_python_dependencies_after_pull(print(" → Termux/Android detected: prebuilding psutil with Linux source path compatibility...")_install_psutil_android_compat(install_prefix, env=lazy_env)_m()._install_python_dependencies_with_optional_fallback(- install_prefix, env=lazy_env, group=install_group)+ install_prefix, env=lazy_env, group=install_group,+ reinstall=mapping_current is False)# Clear the core breadcrumb before lazy refresh, which uses its own marker so a lazy# failure can't be "healed" by a narrow core import probe.diff --git a/tests/hermes_cli/test_update_skip_unchanged_editable_install.py b/tests/hermes_cli/test_update_skip_unchanged_editable_install.pyindex afdb386ee30..b781b2c0fee 100644--- a/tests/hermes_cli/test_update_skip_unchanged_editable_install.py+++ b/tests/hermes_cli/test_update_skip_unchanged_editable_install.py@@ -13,6 +13,7 @@ git prints rather than what it does."""import subprocess+from pathlib import Pathimport pytest@@ -49,6 +50,96 @@ def _commit(cwd, message):subprocess.run(GIT + ["commit", "-qm", message], cwd=cwd, check=True)+def _finder(repo, mapping, *, layout="lib/python3.11/site-packages", annotated=False):+ site = repo / "venv" / Path(layout)+ site.mkdir(parents=True)+ body = (+ "MAPPING: dict[str, str] = " + repr(mapping) + "\n"+ if annotated+ else "MAPPING = " + repr(mapping) + "\n"+ )+ (site / "__editable___hermes_agent_0_21_4_finder.py").write_text(body, encoding="utf-8")+ return site+++def _declare_packages(repo, include):+ (repo / "pyproject.toml").write_text(+ "[tool.setuptools.packages.find]\ninclude = " + repr(include) + "\n",+ encoding="utf-8",+ )+ _commit(repo, "declare packages")+++def test_missing_new_top_level_package_forces_reinstall(repo, monkeypatch):+ _declare_packages(repo, ["agent", "agent.*", "newpkg", "newpkg.*"])+ before = _head(repo)+ (repo / "newpkg").mkdir()+ (repo / "newpkg" / "__init__.py").write_text("")+ _commit(repo, "add package")+ _finder(repo, {"agent": str(repo / "agent"), "cli": str(repo / "cli")}, annotated=True)+ monkeypatch.setattr("hermes_cli.update_cmd_deps.project_venv_dir", lambda _: repo / "venv")+ assert _editable_install_is_current(GIT, repo, before) is False+++def test_covered_annotated_finder_allows_source_churn(repo, monkeypatch):+ """A current setuptools map uses annotated assignment and module stems, not cli.py."""+ _declare_packages(repo, ["agent", "agent.*"])+ _finder(+ repo,+ {"agent": str(repo / "agent"), "cli": str(repo / "cli")},+ annotated=True,+ )+ monkeypatch.setattr("hermes_cli.update_cmd_deps.project_venv_dir", lambda _: repo / "venv")+ before = _head(repo)+ (repo / "agent" / "loop.py").write_text("y = 2\n")+ _commit(repo, "source churn")+ assert _editable_install_is_current(GIT, repo, before) is True++[email protected]("layout", ["lib/python3.11/site-packages", "Lib/site-packages"])+def test_windows_and_posix_site_packages_are_both_read(repo, monkeypatch, layout):+ _declare_packages(repo, ["agent", "agent.*"])+ _finder(repo, {"agent": str(repo / "agent"), "cli": str(repo / "cli")}, layout=layout, annotated=True)+ monkeypatch.setattr("hermes_cli.update_cmd_deps.project_venv_dir", lambda _: repo / "venv")+ before = _head(repo)+ (repo / "agent" / "loop.py").write_text("y = 3\n")+ _commit(repo, "source churn")+ assert _editable_install_is_current(GIT, repo, before) is True+++def test_unreadable_finder_fails_closed(repo, monkeypatch):+ before = _head(repo)+ site = repo / "venv" / "lib" / "python3.11" / "site-packages"+ site.mkdir(parents=True)+ (site / "__editable___hermes_agent_0_21_4_finder.py").write_text("MAPPING = (\n", encoding="utf-8")+ monkeypatch.setattr("hermes_cli.update_cmd_deps.project_venv_dir", lambda _: repo / "venv")+ assert _editable_install_is_current(GIT, repo, before) is False+++def test_mapping_drift_requests_reinstall_flag():+ from hermes_cli.main_install_repair import _install_python_dependencies_with_optional_fallback++ recorded = []+ monkeypatch = pytest.MonkeyPatch()+ monkeypatch.setattr(+ "hermes_cli.main_install_repair._run_quarantined_install",+ lambda cmd, **kwargs: recorded.append(cmd),+ )+ monkeypatch.setattr(+ "hermes_cli.main_install_repair._verify_console_scripts_installed",+ lambda *args, **kwargs: None,+ )+ monkeypatch.setattr("hermes_cli.main_install_repair._is_windows", lambda: False)+ try:+ _install_python_dependencies_with_optional_fallback(["uv", "pip"], reinstall=True)+ assert recorded and "--reinstall" in recorded[0]+ recorded.clear()+ _install_python_dependencies_with_optional_fallback(["uv", "pip"], reinstall=False)+ assert recorded and "--reinstall" not in recorded[0]+ finally:+ monkeypatch.undo()++def test_source_only_pull_skips_the_reinstall(repo):"""The common update: .py churn inside already-mapped packages."""before = _head(repo)