Skip to content

The agent that grows with you

test(install): lock no in-place venv gut on rename failure

HexLab98737d6339b757
diff --git a/tests/hermes_cli/test_scan_venv_blockers.py b/tests/hermes_cli/test_scan_venv_blockers.py
index 5eeeedb9ed2..2082d082c58 100644
--- a/tests/hermes_cli/test_scan_venv_blockers.py
+++ b/tests/hermes_cli/test_scan_venv_blockers.py
@@ -18,6 +18,7 @@ import pytest
import agent.redact as redact_module
from hermes_cli._scan_venv_blockers import (
_is_pausable_gateway,
+ _probe_fail_json,
_redact_sensitive_cmdline,
main,
)
@@ -164,6 +165,43 @@ def _run_main_with_detector(monkeypatch, capsys, matches):
return excinfo.value.code, json.loads(out)
+def test_probe_fail_json_is_unambiguous_failure() -> None:
+ """A failed probe must not look like a clear scan (#83149).
+
+ Humans and naive callers used to read ``blocked: false`` as "no holders"
+ when psutil was missing after a gutted venv. The document must mark
+ ``probe_failed`` and keep ``ok`` false.
+ """
+ data = json.loads(_probe_fail_json("psutil is not available: No module named 'psutil'"))
+ assert data["ok"] is False
+ assert data["probe_failed"] is True
+ assert data["blocked"] is False
+ assert data["processes"] == []
+ assert "psutil" in data["error"]
+
+
+def test_main_psutil_missing_is_probe_failure_not_clear(monkeypatch, capsys):
+ """Missing psutil exits non-zero with probe_failed JSON — never a clear scan."""
+ real_import = builtins.__import__
+
+ def _no_psutil(name, *args, **kwargs):
+ if name == "psutil" or name.startswith("psutil."):
+ raise ImportError("No module named 'psutil'")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", _no_psutil)
+ monkeypatch.delitem(sys.modules, "psutil", raising=False)
+
+ with pytest.raises(SystemExit) as excinfo:
+ main()
+ captured = capsys.readouterr()
+ assert excinfo.value.code == 1
+ data = json.loads(captured.out)
+ assert data["ok"] is False
+ assert data["probe_failed"] is True
+ assert "psutil" in captured.err.lower()
+
+
def test_main_exempts_gateway_chain_but_keeps_other_holders(monkeypatch, capsys):
"""A gateway launcher/worker pair alone must scan clear; a non-gateway
holder alongside it must still block (and be the only reported PID)."""
diff --git a/tests/test_install_ps1_venv_rename_abort.py b/tests/test_install_ps1_venv_rename_abort.py
new file mode 100644
index 00000000000..a7798417095
--- /dev/null
+++ b/tests/test_install_ps1_venv_rename_abort.py
@@ -0,0 +1,64 @@
+"""Regression: Windows installer must not gut the venv on rename failure (#83149).
+
+When recreating an existing venv, ``Install-Venv`` renames the directory aside
+first. An older fallback deleted the tree in place when rename was denied; a
+partial ``Remove-Item`` could wipe most of ``site-packages`` and then fail on
+one locked ``.pyd``, leaving Hermes unusable with no rollback.
+
+These tests lock the contract at the source level (the script only runs on
+Windows, so Linux CI cannot execute the PowerShell path).
+"""
+
+from pathlib import Path
+
+import pytest
+
+_INSTALL_PS1 = Path(__file__).resolve().parents[1] / "scripts" / "install.ps1"
+
+
[email protected](scope="module")
+def source() -> str:
+ return _INSTALL_PS1.read_text(encoding="utf-8")
+
+
+def _function_body(source: str, name: str) -> str:
+ """Return the text of a PowerShell ``function <name> { ... }`` block."""
+ start = source.index(f"function {name}")
+ brace = source.index("{", start)
+ depth = 0
+ for i in range(brace, len(source)):
+ if source[i] == "{":
+ depth += 1
+ elif source[i] == "}":
+ depth -= 1
+ if depth == 0:
+ return source[brace : i + 1]
+ raise AssertionError(f"unterminated function body for {name}")
+
+
+def test_install_venv_aborts_when_rename_aside_fails(source: str):
+ """Rename failure must throw with the previous install left intact."""
+ body = _function_body(source, "Install-Venv")
+ assert (
+ "Rename-Item -LiteralPath \"venv\"" in body
+ or "Rename-Item -LiteralPath 'venv'" in body
+ )
+ assert "falling back to in-place delete" not in body
+ throw_at = body.find("Could not move the existing venv aside")
+ assert throw_at != -1, "rename failure must abort with an actionable error"
+ assert "throw" in body[max(0, throw_at - 80) : throw_at + 40]
+
+
+def test_install_venv_never_removes_live_venv_in_place_on_rename_fail(source: str):
+ """After a failed rename, Install-Venv must not Remove-Item the live venv.
+
+ Parked ``venv.stale.*`` trees may still be deleted best-effort; the live
+ ``venv`` directory must only disappear via Rename-Item.
+ """
+ body = _function_body(source, "Install-Venv")
+ # The only Remove-Item targeting the active tree used to be the fallback:
+ # Remove-Item -Recurse -Force "venv"
+ # That path must be gone. Stale-parking cleanup uses $staleName / filter.
+ assert 'Remove-Item -Recurse -Force "venv"' not in body
+ assert "Remove-Item -Recurse -Force 'venv'" not in body
+ assert "venv.stale." in body
diff --git a/tests/test_install_unmerged_index.py b/tests/test_install_unmerged_index.py
index 35d403111fa..ade18486c97 100644
--- a/tests/test_install_unmerged_index.py
+++ b/tests/test_install_unmerged_index.py
@@ -159,9 +159,10 @@ def test_install_ps1_stops_venv_resident_processes_before_parking_venv() -> None
A gateway autostarted by a scheduled task runs as
``venv\\Scripts\\pythonw.exe -m hermes_cli.main gateway run`` — image name
``pythonw``, not ``hermes.exe`` — so the ``taskkill /IM hermes.exe`` guard
- misses it, the loaded ``.pyd`` stays locked, and ``Remove-Item venv`` fails
- mid-recursion (issues #47036/#47557/#47910). The recreate branch must also
- sweep by venv path prefix, and that sweep must run before the delete.
+ misses it and the loaded ``.pyd`` stays locked (issues #47036/#47557/#47910).
+ The recreate branch must sweep by venv path prefix before Rename-Item, and
+ must never fall back to an in-place ``Remove-Item`` of the live ``venv``
+ (#83149 — that path can gut site-packages with no rollback).
"""
text = INSTALL_PS1.read_text()
@@ -184,3 +185,7 @@ def test_install_ps1_stops_venv_resident_processes_before_parking_venv() -> None
assert idx_sweep < idx_park, (
"venv-resident processes must be stopped before Rename-Item parks the venv"
)
+ assert 'Remove-Item -Recurse -Force "venv"' not in text[idx_recreate:], (
+ "must not fall back to in-place delete of the live venv (#83149)"
+ )
+ assert "Could not move the existing venv aside" in text[idx_recreate:]