The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): detect restored import-time failures
fangliquanflq7b958b3575a1
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex 4acbd7f7c17..2db4342f805 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -655,7 +655,9 @@ _UPDATE_CRITICAL_MODULES = ()-def _validate_critical_modules_import(root) -> tuple[bool, str | None, str | None]:+def _validate_critical_modules_import(+ root, *, report_runtime_errors: bool = False+) -> tuple[bool, str | None, str | None]:"""Import each module in ``_UPDATE_CRITICAL_MODULES`` in a subprocess.``_validate_critical_files_syntax`` only *parses* files, so it cannot see@@ -678,7 +680,10 @@ def _validate_critical_modules_import(root) -> tuple[bool, str | None, str | Nondifferent Python than the install's own, and probing the wronginterpreter would test a tree the user never runs.- Returns ``(ok, failing_module, error_message)``.+ Returns ``(ok, failing_module, error_message)``. Generic import-time+ exceptions remain tolerated by default because they can depend on local+ config or environment. ``report_runtime_errors=True`` exposes them so a+ caller can compare two states of the same checkout."""from hermes_constants import FIRST_PARTY_MODULE_ROOTS@@ -699,8 +704,9 @@ def _validate_critical_modules_import(root) -> tuple[bool, str | None, str | Non" except ImportError as exc:\n"" sys.stdout.write(name + '\\n' + str(exc))\n"" raise SystemExit(3)\n"- " except Exception:\n"- " pass\n" # non-import errors (config/env) aren't update breakage+ " except Exception as exc:\n"+ " sys.stdout.write(name + '\\n' + str(exc))\n"+ " raise SystemExit(4)\n""raise SystemExit(0)\n"% (_UPDATE_CRITICAL_MODULES, tuple(sorted(FIRST_PARTY_MODULE_ROOTS))))@@ -726,8 +732,16 @@ def _validate_critical_modules_import(root) -> tuple[bool, str | None, str | Nonexcept (OSError, subprocess.SubprocessError):# Can't run the probe — don't block the update on our own tooling.return True, None, None- if result.returncode == 3:- parts = (result.stdout or "").split("\n", 1)+ if result.returncode != 0:+ if result.returncode == 4 and not report_runtime_errors:+ # Generic import-time failures can depend on local config or env,+ # so the ordinary post-update guard keeps its historical tolerance.+ # Stash restoration opts into reporting them and compares the clean+ # tree with the restored tree to detect failures introduced by the+ # user's local changes.+ return True, None, None+ output = result.stdout or result.stderr or ""+ parts = output.split("\n", 1)module = parts[0].strip() or "unknown"detail = parts[1].strip() if len(parts) > 1 else ""return False, module, detail@@ -2529,6 +2543,9 @@ def _restore_stashed_changes(return Falsepreexisting_untracked = _git_untracked_paths(git_cmd, cwd)+ clean_import_health = _validate_critical_modules_import(+ cwd, report_runtime_errors=True+ )print("→ Restoring local changes...")restore = subprocess.run(git_cmd + ["stash", "apply", stash_ref],@@ -2604,8 +2621,11 @@ def _restore_stashed_changes(syntax_error,)- import_ok, failing_module, import_error = _validate_critical_modules_import(cwd)- if not import_ok:+ restored_import_health = _validate_critical_modules_import(+ cwd, report_runtime_errors=True+ )+ import_ok, failing_module, import_error = restored_import_health+ if not import_ok and restored_import_health != clean_import_health:_reject_unsafe_stash_restore(git_cmd,cwd,diff --git a/tests/hermes_cli/test_update_autostash.py b/tests/hermes_cli/test_update_autostash.pyindex b428481464f..87f9f28e357 100644--- a/tests/hermes_cli/test_update_autostash.py+++ b/tests/hermes_cli/test_update_autostash.py@@ -482,6 +482,87 @@ def test_restore_rejects_invalid_python_and_keeps_clean_updated_tree(assert f"git stash apply {stash_ref}" in output+def test_restore_rejects_new_import_time_failure_and_preserves_stash(+ monkeypatch, tmp_path, capsys+):+ """A valid-Python stash must not introduce a critical import failure."""+ import subprocess+ from hermes_cli import update_cmd++ def git(*args, check=True):+ return subprocess.run(+ ["git", *args],+ cwd=tmp_path,+ capture_output=True,+ text=True,+ check=check,+ )++ git("init", "-q", "-b", "main")+ git("config", "user.email", "[email protected]")+ git("config", "user.name", "t")+ source = tmp_path / "consumer.py"+ source.write_text("VALUE = 1\n", encoding="utf-8")+ git("add", "-A")+ git("commit", "-qm", "init")++ source.write_text("raise RuntimeError('restored local failure')\n", encoding="utf-8")+ stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)+ assert stash_ref+ monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ with pytest.raises(SystemExit) as exc_info:+ hermes_main._restore_stashed_changes(+ ["git"], tmp_path, stash_ref, prompt_user=False+ )++ assert exc_info.value.code == 1+ assert source.read_text(encoding="utf-8") == "VALUE = 1\n"+ assert git("status", "--porcelain").stdout == ""+ assert git("stash", "list").stdout.strip()+ output = capsys.readouterr().out+ assert "agent import consumer" in output+ assert "restored local failure" in output+ assert "gateway was not restarted" in output+++def test_restore_allows_preexisting_import_time_failure(monkeypatch, tmp_path):+ """A restore may proceed when it does not worsen an environment failure."""+ import subprocess+ from hermes_cli import update_cmd++ def git(*args, check=True):+ return subprocess.run(+ ["git", *args],+ cwd=tmp_path,+ capture_output=True,+ text=True,+ check=check,+ )++ git("init", "-q", "-b", "main")+ git("config", "user.email", "[email protected]")+ git("config", "user.name", "t")+ (tmp_path / "consumer.py").write_text(+ "raise RuntimeError('missing local config')\n", encoding="utf-8"+ )+ local_file = tmp_path / "local.txt"+ local_file.write_text("original\n", encoding="utf-8")+ git("add", "-A")+ git("commit", "-qm", "init")++ local_file.write_text("restored\n", encoding="utf-8")+ stash_ref = hermes_main._stash_local_changes_if_needed(["git"], tmp_path)+ assert stash_ref+ monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ assert hermes_main._restore_stashed_changes(+ ["git"], tmp_path, stash_ref, prompt_user=False+ )+ assert local_file.read_text(encoding="utf-8") == "restored\n"+ assert git("stash", "list").stdout.strip() == ""++def test_gateway_restore_prompt_defaults_to_keep_stash(tmp_path, capsys):prompts = []diff --git a/tests/hermes_cli/test_update_import_guard.py b/tests/hermes_cli/test_update_import_guard.pyindex 3e581ea3374..6d786af216f 100644--- a/tests/hermes_cli/test_update_import_guard.py+++ b/tests/hermes_cli/test_update_import_guard.py@@ -82,6 +82,20 @@ def test_import_guard_ignores_non_import_errors(monkeypatch, tmp_path):assert ok is True+def test_import_guard_can_report_non_import_errors(monkeypatch, tmp_path):+ """Stash restore can compare runtime failures before and after apply."""+ (tmp_path / "consumer.py").write_text("raise RuntimeError('broken config')\n")+ monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))++ ok, module, error = hermes_main._validate_critical_modules_import(+ tmp_path, report_runtime_errors=True+ )++ assert ok is False+ assert module == "consumer"+ assert error == "broken config"++def test_import_guard_is_non_fatal_when_probe_cannot_run(monkeypatch, tmp_path):"""If we can't spawn the probe, don't block the user's update."""