The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: reconcile Termux TUI and platform tests
ethernet02f136438390
diff --git a/tests/computer_use/test_cua_wayland_env.py b/tests/computer_use/test_cua_wayland_env.pyindex 05f18ef9acd..02ee05017c4 100644--- a/tests/computer_use/test_cua_wayland_env.py+++ b/tests/computer_use/test_cua_wayland_env.py@@ -4,7 +4,7 @@ import pytestfrom tools.computer_use import cua_backend-pytestmark = pytest.mark.linux_only+pytestmark = pytest.mark.platforms("linux")_VAR = "CUA_DRIVER_RS_ENABLE_WAYLAND"diff --git a/tests/cron/test_cron_bot_chat_delivery.py b/tests/cron/test_cron_bot_chat_delivery.pyindex afc33e0d80a..01436b5a2ea 100644--- a/tests/cron/test_cron_bot_chat_delivery.py+++ b/tests/cron/test_cron_bot_chat_delivery.py@@ -243,7 +243,7 @@ def test_turn_report_books_the_delivery_while_the_child_still_lingers(tmp_path):proc.wait(timeout=10)[email protected]_only[email protected]("linux")def test_delivery_child_runs_in_the_target_home_not_the_schedulers_cwd(tmp_path, monkeypatch):"""The spawn pins ``cwd`` to the target home: a scheduler left in a reaped kanban scratchworkspace must not hand its dead cwd to the child, which then dies before argv (#102941)."""@@ -277,7 +277,7 @@ def test_turn_that_never_ends_is_still_killed_at_the_cap(tmp_path):[email protected]_only[email protected]("linux")def test_bot_chat_turn_failure_tail_decodes_lossily(tmp_path):"""The exit-1 tail is still surfaced (with U+FFFD for the bad byte) instead ofvanishing when the drain thread dies at the first undecodable byte (#105582)."""@@ -289,7 +289,7 @@ def test_bot_chat_turn_failure_tail_decodes_lossily(tmp_path):assert result.stderr == "boom before \ufffd after\n"[email protected]_only[email protected]("windows")def test_bot_chat_turn_roundtrips_accented_utf8_reply(tmp_path):"""The delivery child writes UTF-8 unconditionally — hermes_cli reconfigures itsown streams via hermes_bootstrap on Windows even under PYTHONIOENCODING=cp1252 —diff --git a/tests/cron/test_cron_script.py b/tests/cron/test_cron_script.pyindex df09189ae5a..b0b9a74c34b 100644--- a/tests/cron/test_cron_script.py+++ b/tests/cron/test_cron_script.py@@ -161,7 +161,7 @@ class TestRunJobScript:assert success is Trueassert output == "ABSENT"- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_windows_uv_venv_python_script_bypasses_launcher(self, cron_env, tmp_path, monkeypatch):# Windows-only: the fake ``sys.platform`` could not reproduce the# ``Scripts/python.exe`` launcher layout or the CREATE_NO_WINDOWdiff --git a/tests/gateway/test_agent_cache_pressure.py b/tests/gateway/test_agent_cache_pressure.pyindex ff4d63fa542..daeeece18ae 100644--- a/tests/gateway/test_agent_cache_pressure.py+++ b/tests/gateway/test_agent_cache_pressure.py@@ -95,7 +95,7 @@ class TestMemoryBudgetResolution:assert resolve_memory_high_mb("auto") is None[email protected]_only[email protected]("linux")class TestPressureSignalScope:"""The budget is the unit's cgroup limit, so the signal must be the unit's anon charge:an execute_code kernel in the same cgroup counts even while the gateway itself is small (#110549)."""diff --git a/tests/gateway/test_launchd_exit_timeout_drain_cap.py b/tests/gateway/test_launchd_exit_timeout_drain_cap.pyindex e92c2c27c21..8754de52693 100644--- a/tests/gateway/test_launchd_exit_timeout_drain_cap.py+++ b/tests/gateway/test_launchd_exit_timeout_drain_cap.py@@ -40,7 +40,7 @@ def _read_budget(label):return read_launchd_exit_timeout_s(environ={"XPC_SERVICE_NAME": label}, uid=501, run=fake_run)[email protected]_only[email protected]("macos")@pytest.mark.parametrize("label, expected",[@@ -53,7 +53,7 @@ def test_launchd_reader_yields_a_budget_only_for_hermes_jobs(label, expected):assert resolve_launchd_capped_drain(180.0, _read_budget(label)) == expected[email protected]_only[email protected]("linux")def test_launchd_label_leaked_onto_linux_is_ignored():assert _read_budget("ai.hermes.gateway") is Nonediff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.pyindex caa553a0724..f904e67dedb 100644--- a/tests/gateway/test_status.py+++ b/tests/gateway/test_status.py@@ -584,7 +584,7 @@ class TestGetProcessStartTime:class TestTerminatePid:- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_force_uses_taskkill_on_windows(self, monkeypatch):# Faking _IS_WINDOWS on POSIX could not reproduce the real# CREATE_NO_WINDOW creationflags value that windows_hide_flags()@@ -609,7 +609,7 @@ class TestTerminatePid:(["taskkill", "/PID", "123", "/T", "/F"], True, True, 10, windows_hide_flags())]- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_windows_force_refuses_pid_without_start_time_guard(self, monkeypatch):calls = []monkeypatch.setattr(status.subprocess, "run", lambda *args, **kwargs: calls.append(args))@@ -619,7 +619,7 @@ class TestTerminatePid:assert calls == []- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_windows_force_refuses_reused_pid(self, monkeypatch):monkeypatch.setattr(status, "_get_process_start_time", lambda pid: 999)calls = []@@ -649,7 +649,7 @@ class TestPidExistsZombieProbe:monkeypatch.setattr(psutil.Process, "status", spy)return calls- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_windows_skips_zombie_status_probe(self, monkeypatch):# Faking os.name on POSIX proves nothing about the cost on the real host; the wine2e# runner receipt (red on main, green on the fix) is the live repro for this test.@@ -657,7 +657,7 @@ class TestPidExistsZombieProbe:assert status._pid_exists(os.getpid()) is Trueassert calls == []- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_posix_still_probes_zombie_status(self, monkeypatch):# Control: on POSIX a zombie still answers pid_exists(), so the probe must survive.calls = self._spy_status(monkeypatch)@@ -666,7 +666,7 @@ class TestPidExistsZombieProbe:class TestScopedLocks:- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_windows_file_lock_uses_high_offset(self, tmp_path, monkeypatch):# Faking _IS_WINDOWS on POSIX could not reproduce the msvcrt# byte-range locking path at all: msvcrt does not exist off Windows,diff --git a/tests/gateway/test_whatsapp_connect.py b/tests/gateway/test_whatsapp_connect.pyindex 587e5e2f097..20837b135e9 100644--- a/tests/gateway/test_whatsapp_connect.py+++ b/tests/gateway/test_whatsapp_connect.py@@ -20,25 +20,13 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom gateway.config import Platform+from gateway.platforms.base import SendResult# ---------------------------------------------------------------------------# Helpers# ----------------------------------------------------------------------------class _AsyncCM:- """Minimal async context manager returning a fixed value."""-- def __init__(self, value):- self.value = value-- async def __aenter__(self):- return self.value-- async def __aexit__(self, *exc):- return False--def _make_adapter():"""Create a WhatsAppAdapter with test attributes (bypass __init__)."""from plugins.platforms.whatsapp.adapter import WhatsAppAdapter@@ -71,27 +59,8 @@ def _make_adapter():return adapter-def _mock_aiohttp(status=200, json_data=None, json_side_effect=None):- """Build a mock ``aiohttp.ClientSession`` returning a fixed response."""- mock_resp = MagicMock()- mock_resp.status = status- if json_side_effect:- mock_resp.json = AsyncMock(side_effect=json_side_effect)- else:- mock_resp.json = AsyncMock(return_value=json_data or {})-- mock_session = MagicMock()- mock_session.get = MagicMock(return_value=_AsyncCM(mock_resp))-- return MagicMock(return_value=_AsyncCM(mock_session))---def _connect_patches(mock_proc, mock_fh, mock_client_cls=None):- """Return a dict of common patches needed to reach the health-check loop."""- patches = {- "plugins.platforms.whatsapp.adapter.check_whatsapp_requirements": True,- "plugins.platforms.whatsapp.adapter.asyncio.create_task": MagicMock(),- }+def _connect_patches(mock_proc, mock_fh):+ """Return common patches needed to reach the health-check loop."""base = [patch("plugins.platforms.whatsapp.adapter.check_whatsapp_requirements", return_value=True),patch.object(Path, "exists", return_value=True),@@ -102,8 +71,6 @@ def _connect_patches(mock_proc, mock_fh, mock_client_cls=None):patch("plugins.platforms.whatsapp.adapter.asyncio.sleep", new_callable=AsyncMock),patch("plugins.platforms.whatsapp.adapter.asyncio.create_task"),]- if mock_client_cls is not None:- base.append(patch("aiohttp.ClientSession", mock_client_cls))return base@@ -118,7 +85,7 @@ def _connect_patches(mock_proc, mock_fh, mock_client_cls=None):# ---------------------------------------------------------------------------class TestDataInitialized:- """Verify ``data = {}`` prevents NameError when resp.json() fails."""+ """Verify an unparseable health response cannot leave polling state unbound."""@pytest.mark.asyncioasync def test_no_name_error_when_json_always_fails(self):@@ -133,22 +100,24 @@ class TestDataInitialized:mock_proc = MagicMock()mock_proc.poll.return_value = None # bridge stays alive- mock_client_cls = _mock_aiohttp(- status=200, json_side_effect=ValueError("bad json"),- )- mock_fh = MagicMock()-- patches = _connect_patches(mock_proc, mock_fh, mock_client_cls)+ adapter._bridge_process = mock_proc- with patches[0], patches[1], patches[2], patches[3], patches[4], \- patches[5], patches[6], patches[7], patches[8], \- patch.object(type(adapter), "_poll_messages", return_value=MagicMock()):- # Must NOT raise NameError- result = await adapter.connect()+ # _probe_bridge_health normalizes an unparseable HTTP 200 body to+ # (True, None). Exercise the polling contract without requiring the+ # optional messaging transport in the base test environment.+ with patch.object(+ adapter,+ "_probe_bridge_health",+ new_callable=AsyncMock,+ return_value=(True, None),+ ), patch(+ "plugins.platforms.whatsapp.adapter.asyncio.sleep",+ new_callable=AsyncMock,+ ):+ result = await adapter._wait_for_bridge()- # connect() returns True (warn-and-proceed path)+ # The bridge HTTP server is up, so timeout uses the warn-and-proceed path.assert result is True- assert adapter._running is True# ---------------------------------------------------------------------------@@ -243,18 +212,22 @@ class TestBridgeRuntimeFailure:adapter._running = Trueadapter._bridge_process = None # unmanaged bridge — skip exit check- mock_resp = MagicMock()- mock_resp.status = 200- mock_resp.json = AsyncMock(return_value={"messageId": "msg-1"})- mock_session = MagicMock()- mock_session.post = MagicMock(return_value=_AsyncCM(mock_resp))- adapter._http_session = mock_session+ adapter._http_session = MagicMock()- result = await adapter.send("+50766715226", "hello")+ with patch.object(+ adapter,+ "_post_bridge_message",+ new_callable=AsyncMock,+ return_value=SendResult(success=True, message_id="msg-1"),+ ) as mock_post:+ result = await adapter.send("+15551234567", "hello")assert result.success is True- payload = mock_session.post.call_args.kwargs["json"]- assert payload["chatId"] == "[email protected]"+ mock_post.assert_awaited_once_with(+ "send",+ {"chatId": "[email protected]", "message": "hello"},+ timeout=30,+ )@pytest.mark.asyncio@@ -273,16 +246,22 @@ class TestBridgeRuntimeFailure:mock_proc.poll.side_effect = poll_side_effectmock_proc.returncode = 1- # Health returns 200 with status != "connected" -> triggers Phase 2- mock_client_cls = _mock_aiohttp(- status=200, json_data={"status": "disconnected"},- )mock_fh = MagicMock()- patches = _connect_patches(mock_proc, mock_fh, mock_client_cls)+ adapter._bridge_process = mock_proc+ adapter._bridge_log_fh = mock_fh- with patches[0], patches[1], patches[2], patches[3], patches[4], \- patches[5], patches[6], patches[7], patches[8]:- result = await adapter.connect()+ # A healthy HTTP endpoint with status != connected exhausts Phase 1.+ # The managed bridge then dies on the first Phase 2 poll.+ with patch.object(+ adapter,+ "_probe_bridge_health",+ new_callable=AsyncMock,+ return_value=(True, {"status": "disconnected"}),+ ), patch(+ "plugins.platforms.whatsapp.adapter.asyncio.sleep",+ new_callable=AsyncMock,+ ):+ result = await adapter._wait_for_bridge()assert result is Falsemock_fh.close.assert_called_once()@@ -296,7 +275,7 @@ class TestBridgeRuntimeFailure:class TestKillPortProcess:"""Verify _kill_port_process uses platform-appropriate commands."""- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_uses_netstat_and_taskkill_on_windows(self):"""``windows_only``: netstat/taskkill are Windows binaries. The old``_IS_WINDOWS`` patch selected this branch on Linux, where neither@@ -333,7 +312,7 @@ class TestKillPortProcess:for call in mock_run.call_args_list)- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_windows_refuses_taskkill_on_non_bridge_pid(self):"""#89614 class: the netstat-scanned PID is a bare number — if thelive process is not a node bridge, taskkill must never fire."""@@ -359,7 +338,7 @@ class TestKillPortProcess:)- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_kills_only_listeners_on_linux(self):"""POSIX path SIGTERMs only LISTENer PIDs (never clients) — the #43846 fix.@@ -385,7 +364,7 @@ class TestKillPortProcess:mock_listeners.assert_called_once_with(3000)assert kills == [(55555, signal.SIGTERM)]- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_non_bridge_listener_is_never_killed(self):"""#89614 class: a listener that is not a node bridge is refused."""from plugins.platforms.whatsapp import adapter as wa@@ -410,7 +389,7 @@ class TestHttpSessionLifecycle:"""Verify persistent aiohttp.ClientSession is created and cleaned up."""@pytest.mark.asyncio- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")async def test_disconnect_uses_taskkill_tree_on_windows(self):"""Windows disconnect should target the bridge process tree, not just the parent PID.diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.pyindex 43587fc3849..62e7843ad25 100644--- a/tests/hermes_cli/test_backup.py+++ b/tests/hermes_cli/test_backup.py@@ -304,7 +304,7 @@ class TestIterBackupFiles:assert "models" in skippedassert "hermes-agent" in skipped- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_skips_unix_sockets(self, tmp_path, monkeypatch):from hermes_cli.backup import _iter_backup_files@@ -1033,7 +1033,7 @@ class TestImportAtomicWrites:assert target.read_text() == "model: restored\n"assert (target.stat().st_mode & 0o777) == 0o644- @pytest.mark.skipif(os.name != "posix", reason="POSIX ownership")+ @pytest.mark.platforms("posix")def test_restore_preserves_existing_file_owner(self, tmp_path, monkeypatch):"""A root-run import must not re-own the user's files to root.@@ -1054,7 +1054,7 @@ class TestImportAtomicWrites:chown_calls: list[tuple[Path, int, int]] = []monkeypatch.setattr(- "hermes_cli.backup._preserve_file_owner",+ "hermes_cli.backup_restore._preserve_file_owner",lambda p: (123, 456) if Path(p).exists() else None,)monkeypatch.setattr(@@ -1070,28 +1070,21 @@ class TestImportAtomicWrites:# state.db is newly created, so there is no prior owner to restore.assert chown_calls == [(target, 123, 456)]- @pytest.mark.skipif(not hasattr(os, "fchmod"), reason="needs fchmod present to remove it")- def test_mode_is_applied_before_the_replace_without_fchmod(self, tmp_path, monkeypatch):- """Covers the Windows branch: no ``fchmod``, so ``chmod`` the temp path.-- Applying the mode only *after* ``atomic_replace`` leaves the published- file at mkstemp's 0600 until that chmod lands (and permanently if the- process dies in between), and ``atomic_replace``'s EXDEV/EBUSY- ``shutil.copystat`` fallback would copy 0600 onto the target. Mirrors- the transit-window fix ``atomic_yaml_write`` already carries.- """+ def test_mode_is_applied_before_the_replace(self, tmp_path, monkeypatch):+ """Publish the correct native permission bits with no permissive window."""hermes_home = tmp_path / ".hermes"hermes_home.mkdir()target = hermes_home / "config.yaml"target.write_text("model: original\n")os.chmod(target, 0o644)+ expected_mode = target.stat().st_mode & 0o777monkeypatch.setenv("HERMES_HOME", str(hermes_home))monkeypatch.setattr(Path, "home", lambda: tmp_path)zip_path = tmp_path / "backup.zip"self._zip(zip_path, {"config.yaml": "model: restored\n", "state.db": ""})- import hermes_cli.backup as backup_mod+ import hermes_cli.backup_restore as backup_modreal_replace = backup_mod.atomic_replacestaged_modes: list[int] = []@@ -1101,17 +1094,15 @@ class TestImportAtomicWrites:staged_modes.append(os.stat(tmp).st_mode & 0o777)return real_replace(tmp, dst)- monkeypatch.delattr(os, "fchmod")monkeypatch.setattr(backup_mod, "atomic_replace", spying_replace)from hermes_cli.backup import run_importrun_import(Namespace(zipfile=str(zip_path), force=True))- # Without the pre-replace chmod this reads 0o600 (mkstemp's mode).- assert staged_modes == [0o644]- assert (target.stat().st_mode & 0o777) == 0o644+ assert staged_modes == [expected_mode]+ assert (target.stat().st_mode & 0o777) == expected_mode- @pytest.mark.skipif(os.name != "posix", reason="POSIX setuid/setgid bits")+ @pytest.mark.platforms("posix")def test_restore_does_not_carry_setuid_onto_archive_content(self, tmp_path, monkeypatch):@@ -1146,7 +1137,7 @@ class TestImportAtomicWrites:{"helper.sh": "#!/bin/sh\necho attacker\n", "state.db": ""},)- import hermes_cli.backup as backup_mod+ import hermes_cli.backup_restore as backup_modreal_replace = backup_mod.atomic_replacestaged_modes: list[int] = []@@ -2327,12 +2318,18 @@ class TestImportLiveSessionDatabase:):"""A refused live-safe restore is a warning, not a counted success."""import hermes_cli.backup as backup_mod+ # _import_db_member (the run_import .db publish path) lives in+ # hermes_cli.backup_restore and resolves _safe_restore_db there.+ import hermes_cli.backup_restore as backup_restore_modhome, live_db, zip_path = self._prepare(tmp_path, monkeypatch)- monkeypatch.setattr(backup_mod, "_safe_restore_db", lambda src, dst: False)+ monkeypatch.setattr(backup_restore_mod, "_safe_restore_db", lambda src, dst: False)backup_mod.run_import(Namespace(zipfile=str(zip_path), force=True))+ out = capsys.readouterr().out+ assert "files skipped" in out+ assert "state.db" in out# The pre-import database is still the one on disk.assert _count_rows(live_db) == (3, 12)diff --git a/tests/hermes_cli/test_cpr_local_leak.py b/tests/hermes_cli/test_cpr_local_leak.pyindex 7cc10de66d3..0fec2fddaae 100644--- a/tests/hermes_cli/test_cpr_local_leak.py+++ b/tests/hermes_cli/test_cpr_local_leak.py@@ -19,12 +19,12 @@ def _clear_cpr_env(monkeypatch):class TestClassicCliOutputSelection:- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_windows_preserves_default_output_selection(self):assert _terminal_may_leak_cpr() is Falseassert _select_classic_cli_pt_output(sys.stdout) is None- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_windows_honors_explicit_no_cpr(self, monkeypatch):monkeypatch.setenv("PROMPT_TOOLKIT_NO_CPR", "1")assert _terminal_may_leak_cpr() is Truediff --git a/tests/hermes_cli/test_gateway_platform_gating.py b/tests/hermes_cli/test_gateway_platform_gating.pyindex 00e6c669dad..707c2a4dd15 100644--- a/tests/hermes_cli/test_gateway_platform_gating.py+++ b/tests/hermes_cli/test_gateway_platform_gating.py@@ -16,7 +16,7 @@ import pytestclass TestMatrixHiddenOnWindows:- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_matrix_absent_on_windows(self):"""The gate itself: matrix must be dropped on a real Windows host.diff --git a/tests/hermes_cli/test_gateway_restart_loop.py b/tests/hermes_cli/test_gateway_restart_loop.pyindex 560fc60f42f..9ea962e3e96 100644--- a/tests/hermes_cli/test_gateway_restart_loop.py+++ b/tests/hermes_cli/test_gateway_restart_loop.py@@ -417,7 +417,7 @@ class TestCronCreateLifecycleBlock:monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))scripts_dir = tmp_path / ".hermes" / "scripts"scripts_dir.mkdir(parents=True)- (scripts_dir / "restart.sh").write_text("#!/bin/bash\nhermes gateway restart\n", encoding="utf-8")+ (scripts_dir / "restart.sh").write_text("#!/usr/bin/env bash\nhermes gateway restart\n", encoding="utf-8")args = Namespace(cron_command="create",schedule="1h",@@ -568,7 +568,7 @@ class TestTerminalToolGatewayLifecycleGuard:import tools.terminal_tool as ttscript = tmp_path / "delayed-ops.sh"- script.write_text("#!/bin/bash\nsleep 45\nhermes gateway restart\n", encoding="utf-8")+ script.write_text("#!/usr/bin/env bash\nsleep 45\nhermes gateway restart\n", encoding="utf-8")self._patch_env(monkeypatch, self._make_fake_env(), inside_gateway=True)result = json.loads(tt.terminal_tool(command=f"/bin/bash {script}"))@@ -689,7 +689,7 @@ class TestTerminalToolGatewayLifecycleGuard:script = tmp_path / "wrapper.sh"script.write_text(- "#!/bin/bash\nlaunchctl submit -l ai.hermes.loop -- /bin/true\n"+ "#!/usr/bin/env bash\nlaunchctl submit -l ai.hermes.loop -- /bin/true\n")self._patch_env(monkeypatch, self._make_fake_env(), inside_gateway=True)@@ -702,7 +702,7 @@ class TestTerminalToolGatewayLifecycleGuard:import tools.terminal_tool as ttscript = tmp_path / "relative.sh"- script.write_text("#!/bin/bash\nhermes gateway restart\n", encoding="utf-8")+ script.write_text("#!/usr/bin/env bash\nhermes gateway restart\n", encoding="utf-8")class _FakeEnv:env = {}@@ -721,7 +721,7 @@ class TestTerminalToolGatewayLifecycleGuard:import tools.terminal_tool as ttscript = tmp_path / "delayed.sh"- script.write_text("#!/bin/bash\nhermes gateway stop\n", encoding="utf-8")+ script.write_text("#!/usr/bin/env bash\nhermes gateway stop\n", encoding="utf-8")script.chmod(0o700)self._patch_env(monkeypatch, self._make_fake_env(), inside_gateway=True)@@ -744,7 +744,7 @@ class TestTerminalToolGatewayLifecycleGuard:import tools.terminal_tool as ttscript = tmp_path / "options.sh"- script.write_text("#!/bin/bash\nhermes gateway restart\n", encoding="utf-8")+ script.write_text("#!/usr/bin/env bash\nhermes gateway restart\n", encoding="utf-8")self._patch_env(monkeypatch, self._make_fake_env(), inside_gateway=True)result = json.loads(tt.terminal_tool(@@ -757,7 +757,7 @@ class TestTerminalToolGatewayLifecycleGuard:import tools.terminal_tool as ttscript = tmp_path / "nested.sh"- script.write_text("#!/bin/bash\nlaunchctl submit -l ai.hermes.loop -- /bin/true\n", encoding="utf-8")+ script.write_text("#!/usr/bin/env bash\nlaunchctl submit -l ai.hermes.loop -- /bin/true\n", encoding="utf-8")class _FakeEnv:env = {}@@ -777,9 +777,9 @@ class TestTerminalToolGatewayLifecycleGuard:import tools.terminal_tool as ttinner = tmp_path / "inner.sh"- inner.write_text("#!/bin/bash\nhermes gateway restart\n", encoding="utf-8")+ inner.write_text("#!/usr/bin/env bash\nhermes gateway restart\n", encoding="utf-8")outer = tmp_path / "outer.sh"- outer.write_text("#!/bin/bash\n/bin/bash inner.sh\n", encoding="utf-8")+ outer.write_text("#!/usr/bin/env bash\n/bin/bash inner.sh\n", encoding="utf-8")class _FakeEnv:env = {}@@ -831,7 +831,7 @@ class TestTerminalToolGatewayLifecycleGuard:calls = []script = tmp_path / "health-check.sh"- script.write_text("#!/bin/bash\nprintf 'healthy\\n'\n", encoding="utf-8")+ script.write_text("#!/usr/bin/env bash\nprintf 'healthy\\n'\n", encoding="utf-8")class _FakeEnv:env = {}@@ -891,7 +891,7 @@ class TestLifecycleGuardModule:contains_gateway_lifecycle_command_or_referenced_script,)script = tmp_path / "padded.sh"- script.write_bytes(b"#!/bin/bash\n# pad\x00\nhermes gateway restart\n")+ script.write_bytes(b"#!/usr/bin/env bash\n# pad\x00\nhermes gateway restart\n")assert (contains_gateway_lifecycle_command_or_referenced_script(f"bash {script}")is True@@ -944,7 +944,7 @@ class TestLifecycleGuardModule:contains_gateway_lifecycle_command_or_referenced_script,)script = tmp_path / "huge.sh"- script.write_bytes(b"#!/bin/bash\n# \x00" + b"x" * (1024 * 1024 + 64) + b"\n")+ script.write_bytes(b"#!/usr/bin/env bash\n# \x00" + b"x" * (1024 * 1024 + 64) + b"\n")assert (contains_gateway_lifecycle_command_or_referenced_script(f"bash {script}")is True@@ -960,7 +960,7 @@ class TestLifecycleGuardModule:def test_script_with_command_raises(self, tmp_path, monkeypatch):from cron.lifecycle_guard import GatewayLifecycleBlocked, check_gateway_lifecyclescript = tmp_path / "restart.sh"- script.write_text("#!/bin/bash\nhermes gateway restart\n", encoding="utf-8")+ script.write_text("#!/usr/bin/env bash\nhermes gateway restart\n", encoding="utf-8")with pytest.raises(GatewayLifecycleBlocked):check_gateway_lifecycle("clean prompt", str(script))@@ -976,7 +976,7 @@ class TestLifecycleGuardModule:):from cron.lifecycle_guard import GatewayLifecycleBlocked, check_gateway_lifecyclescript = tmp_path / "persistent.sh"- script.write_text(f"#!/bin/bash\n{line}\n", encoding="utf-8")+ script.write_text(f"#!/usr/bin/env bash\n{line}\n", encoding="utf-8")with pytest.raises(GatewayLifecycleBlocked):check_gateway_lifecycle("clean prompt", str(script))@@ -1073,8 +1073,8 @@ class TestLifecycleGuardModule:a .sh script that itself invokes a lifecycle command is caught."""from cron.lifecycle_guard import GatewayLifecycleBlocked, check_gateway_lifecyclescript = tmp_path / "wrapper.sh"- script.write_text("#!/bin/bash\n./deploy.sh\n", encoding="utf-8")- (tmp_path / "deploy.sh").write_text("#!/bin/bash\nhermes gateway stop\n", encoding="utf-8")+ script.write_text("#!/usr/bin/env bash\n./deploy.sh\n", encoding="utf-8")+ (tmp_path / "deploy.sh").write_text("#!/usr/bin/env bash\nhermes gateway stop\n", encoding="utf-8")with pytest.raises(GatewayLifecycleBlocked):check_gateway_lifecycle("daily ops", str(script))@@ -1687,7 +1687,7 @@ class TestTerminalToolGatewayLifecycleGuardRemote:def execute(self, command, **kwargs):calls.append(command)if "head -c" in command and "/remote/workspace/remote.sh" in command:- return {"output": "#!/bin/bash\nhermes gateway restart\n", "returncode": 0}+ return {"output": "#!/usr/bin/env bash\nhermes gateway restart\n", "returncode": 0}return {"output": "", "returncode": 0}fake_env = _RemoteEnv()diff --git a/tests/hermes_cli/test_gateway_wsl.py b/tests/hermes_cli/test_gateway_wsl.pyindex 1c9dd059c0f..7413da84863 100644--- a/tests/hermes_cli/test_gateway_wsl.py+++ b/tests/hermes_cli/test_gateway_wsl.py@@ -39,7 +39,7 @@ class TestIsWsl:class TestSupportsSystemdServicesWSL:"""Test that supports_systemd_services() handles WSL correctly."""- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_wsl_with_systemd(self, monkeypatch):"""WSL + working systemd → True.@@ -54,7 +54,7 @@ class TestSupportsSystemdServicesWSL:monkeypatch.setattr(gateway, "_wsl_systemd_operational", lambda: True)assert gateway.supports_systemd_services() is True- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_termux_still_excluded(self, monkeypatch):"""Termux → False regardless of WSL status.@@ -71,7 +71,7 @@ class TestSupportsSystemdServicesWSL:class TestGatewayCommandWSLMessages:"""Test that WSL users see appropriate guidance."""- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_install_wsl_no_systemd(self, monkeypatch, capsys):"""hermes gateway install on WSL without systemd shows guidance.diff --git a/tests/hermes_cli/test_gui_uninstall.py b/tests/hermes_cli/test_gui_uninstall.pyindex c7a044409d0..ab9eb914b2d 100644--- a/tests/hermes_cli/test_gui_uninstall.py+++ b/tests/hermes_cli/test_gui_uninstall.py@@ -51,7 +51,7 @@ def test_gui_install_summary_shape(tmp_path, monkeypatch):assert summary["platform"] == sys.platform[email protected]_only[email protected]("linux")def test_uninstall_removes_launcher_entry_and_refreshes_cache(tmp_path, monkeypatch):monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg"))diff --git a/tests/hermes_cli/test_kanban_core_functionality.py b/tests/hermes_cli/test_kanban_core_functionality.pyindex b8cfa249039..c82d6ff4531 100644--- a/tests/hermes_cli/test_kanban_core_functionality.py+++ b/tests/hermes_cli/test_kanban_core_functionality.py@@ -630,7 +630,7 @@ def test_migration_backfill_idempotent_under_re_run(tmp_path, monkeypatch):# Battle-test findings (May 2026: stress/ suite exposed zombie + id collision)# -------------------------------------------------------------------------[email protected]_only[email protected]("linux")def test_pid_alive_detects_zombie(kanban_home):"""_pid_alive must return False for a zombie process.diff --git a/tests/hermes_cli/test_kanban_db.py b/tests/hermes_cli/test_kanban_db.pyindex c13b0bcbdb2..2668a6e67e4 100644--- a/tests/hermes_cli/test_kanban_db.py+++ b/tests/hermes_cli/test_kanban_db.py@@ -51,7 +51,7 @@ def _init_git_repo(repo: Path) -> None:[email protected]_only[email protected]("windows")def test_cross_process_init_lock_uses_windows_byte_range_lock(tmp_path, monkeypatch):"""Windows must use a real (non-blocking) process lock, not a no-op open.diff --git a/tests/hermes_cli/test_linux_desktop_entry.py b/tests/hermes_cli/test_linux_desktop_entry.pyindex 9799417e161..0250e6eea48 100644--- a/tests/hermes_cli/test_linux_desktop_entry.py+++ b/tests/hermes_cli/test_linux_desktop_entry.py@@ -212,7 +212,7 @@ def test_exec_leaves_shell_wrapper_launchers_alone(tmp_path, xdg_home, monkeypathermes_bin = tmp_path / "bin" / "hermes"hermes_bin.parent.mkdir()hermes_bin.write_text(- '#!/bin/bash\nexec /opt/hermes/venv/bin/python "$@"\n', encoding="utf-8"+ '#!/usr/bin/env bash\nexec /opt/hermes/venv/bin/python "$@"\n', encoding="utf-8")hermes_bin.chmod(0o755)monkeypatch.setattr(@@ -279,7 +279,7 @@ def test_exec_converges_from_repo_script_argv0_to_installed_wrapper(repo_script.chmod(0o755)wrapper = tmp_path / "installed" / "bin" / "hermes"wrapper.parent.mkdir(parents=True)- wrapper.write_text(f'#!/bin/bash\nexec {sys.executable} "$@"\n', encoding="utf-8")+ wrapper.write_text(f'#!/usr/bin/env bash\nexec {sys.executable} "$@"\n', encoding="utf-8")wrapper.chmod(0o755)# argv[0] = repo script; PATH lookup finds the installed wrapper.@@ -306,7 +306,7 @@ def test_exec_never_persists_a_bare_interpreter_command(root = _make_project(tmp_path)wrapper = tmp_path / "installed" / "bin" / "hermes"wrapper.parent.mkdir(parents=True)- wrapper.write_text("#!/bin/bash\nexit 0\n", encoding="utf-8")+ wrapper.write_text("#!/usr/bin/env bash\nexit 0\n", encoding="utf-8")wrapper.chmod(0o755)interpreter = tmp_path / "uv" / "cpython-3.11.15" / "bin" / "python3.11"@@ -399,7 +399,7 @@ def test_exec_uses_known_wrapper_when_path_lookup_misses(known_wrapper = tmp_path / "known-home" / ".local" / "bin" / "hermes"known_wrapper.parent.mkdir(parents=True)known_wrapper.write_text(- f'#!/bin/bash\nexec {root / "venv" / "bin" / "python"} {root / "hermes"} "$@"\n',+ f'#!/usr/bin/env bash\nexec {root / "venv" / "bin" / "python"} {root / "hermes"} "$@"\n',encoding="utf-8",)known_wrapper.chmod(0o755)@@ -440,13 +440,13 @@ def test_exec_never_persists_a_checkout_internal_path_hit(tmp_path, xdg_home, moroot = _make_project(tmp_path)venv_script = root / "venv" / "bin" / "hermes"venv_script.parent.mkdir(parents=True)- venv_script.write_text("#!/bin/bash\nexec true\n", encoding="utf-8")+ venv_script.write_text("#!/usr/bin/env bash\nexec true\n", encoding="utf-8")venv_script.chmod(0o755)known_wrapper = tmp_path / "path-home" / ".local" / "bin" / "hermes"known_wrapper.parent.mkdir(parents=True)known_wrapper.write_text(- f'#!/bin/bash\nexec {root / "venv" / "bin" / "python"} {root / "hermes"} "$@"\n',+ f'#!/usr/bin/env bash\nexec {root / "venv" / "bin" / "python"} {root / "hermes"} "$@"\n',encoding="utf-8",)known_wrapper.chmod(0o755)@@ -497,7 +497,7 @@ def test_exec_finds_known_wrapper_when_resolver_has_no_candidate(known_wrapper = tmp_path / "cold-home" / ".local" / "bin" / "hermes"known_wrapper.parent.mkdir(parents=True)known_wrapper.write_text(- f'#!/bin/bash\nexec {root / "venv" / "bin" / "python"} {root / "hermes"} "$@"\n',+ f'#!/usr/bin/env bash\nexec {root / "venv" / "bin" / "python"} {root / "hermes"} "$@"\n',encoding="utf-8",)known_wrapper.chmod(0o755)@@ -550,7 +550,7 @@ def test_exec_rejects_known_wrapper_from_another_checkout(foreign_wrapper = tmp_path / "known-home" / ".local" / "bin" / "hermes"foreign_wrapper.parent.mkdir(parents=True)foreign_wrapper.write_text(- f"#!/bin/bash\nexec {other_root / 'venv' / 'bin' / 'python'} "+ f"#!/usr/bin/env bash\nexec {other_root / 'venv' / 'bin' / 'python'} "f'{other_root / "hermes"} "$@"\n',encoding="utf-8",)@@ -672,14 +672,14 @@ def test_install_without_source_icon_uses_themed_name(tmp_path, xdg_home, monkeyassert _parse(entry.read_text(encoding="utf-8"))["Icon"] == "hermes"[email protected]_only[email protected]("macos")def test_install_is_a_noop_on_macos(tmp_path):"""Faking darwin only renamed the host — the real macOS runner is theonly place the `sys.platform` guard is exercised against a real host."""assert lde.install_desktop_entry(_make_project(tmp_path)) is None[email protected]_only[email protected]("windows")def test_install_is_a_noop_on_windows(tmp_path):"""As above for Windows: a fake left POSIX paths and a POSIX XDG layoutin place, so the no-op was never proven against a real one."""@@ -834,7 +834,7 @@ def test_wrapper_ownership_rejects_sibling_extensions(suffix, tmp_path):checkout.mkdir()evil = tmp_path / "evil-shim"evil.write_text(- f"#!/bin/bash\n"+ f"#!/usr/bin/env bash\n"f"exec {checkout}{suffix}/venv/bin/python "f'{checkout}{suffix}/hermes "$@"\n',encoding="utf-8",@@ -862,7 +862,7 @@ def test_wrapper_ownership_accepts_shim_via_symlinked_home(tmp_path, monkeypatchshim = home_link / ".local" / "bin" / "hermes"shim.parent.mkdir(parents=True)shim.write_text(- f"#!/bin/bash\n"+ f"#!/usr/bin/env bash\n"f"exec {lexical_checkout}/venv/bin/python "f'{lexical_checkout}/hermes "$@"\n',encoding="utf-8",@@ -1018,7 +1018,7 @@ def test_probe_accepts_shell_launcher_wrapper(tmp_path, xdg_home, monkeypatch):good_wrapper = xdg_home / ".local" / "bin" / "hermes"good_wrapper.parent.mkdir(parents=True)good_wrapper.write_text(- f"#!/bin/bash\nexec {root / 'venv' / 'bin' / 'python'} "+ f"#!/usr/bin/env bash\nexec {root / 'venv' / 'bin' / 'python'} "f'{root / "hermes"} "$@"\n',encoding="utf-8",)diff --git a/tests/hermes_cli/test_linux_sandbox_fixup.py b/tests/hermes_cli/test_linux_sandbox_fixup.pyindex df0acff9c00..a28623bb034 100644--- a/tests/hermes_cli/test_linux_sandbox_fixup.py+++ b/tests/hermes_cli/test_linux_sandbox_fixup.py@@ -20,7 +20,7 @@ import pytestfrom hermes_cli import main_desktop# Linux-only subject: run on the real Linux host instead of faking sys.platform.-pytestmark = pytest.mark.linux_only+pytestmark = pytest.mark.platforms("linux")class TestDesktopLinuxUsernsSandboxAvailable:diff --git a/tests/hermes_cli/test_managed_uv.py b/tests/hermes_cli/test_managed_uv.pydeleted file mode 100644index 771750abbdb..00000000000--- a/tests/hermes_cli/test_managed_uv.py+++ /dev/null@@ -1,1340 +0,0 @@-"""Tests for hermes_cli.managed_uv — one path, no guessing."""--from __future__ import annotations--import os-import stat-import sys-from pathlib import Path-from types import SimpleNamespace-from unittest.mock import MagicMock, patch--import pytest--from hermes_cli.managed_uv import _CandidateStageError--# ----------------------------------------------------------------------------# Helpers-# -----------------------------------------------------------------------------# Host-native managed-uv binary name: managed_uv_path() installs `uv` on-# POSIX and `uv.exe` on Windows. Fixtures must build what the real host-# resolves — no platform fake.-_UV_BINARY_NAME = "uv.exe" if sys.platform == "win32" else "uv"--def _make_executable(path: Path) -> None:- """Create a minimal fake uv binary at *path*."""- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text("#!/bin/sh\necho uv 0.1.2\n", encoding="utf-8")- path.chmod(path.stat().st_mode | stat.S_IEXEC)--def _runtime_info(- executable: Path,- sqlite_version: tuple[int, int, int],-):- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- return SQLiteRuntimeInfo(- executable=executable,- base_prefix=executable.parent.parent,- python_version=(3, 11, 15),- sqlite_version=sqlite_version,- sqlite_version_string=".".join(str(part) for part in sqlite_version),- sqlite_source_id=f"source-{sqlite_version}",- )--def _RRR(status):- """not-applicable RuntimeRepairResult for tests that neutralize the- repair hook. ensure_uv()/update_managed_uv() invoke runtime repair as a- side effect; unmocked, it probes the REAL checkout's venv/.venv — on CI- the repo .venv links vulnerable SQLite, so repair fires for real and- re-invokes _install_uv (uv-refresh retry), breaking call-count asserts.- """- from hermes_cli.managed_uv import RuntimeRepairResult-- return RuntimeRepairResult(status)--def _make_runtime_install(- tmp_path: Path,- *,- windows: bool = False,-) -> tuple[Path, Path, Path]:- root = tmp_path / "checkout"- root.mkdir()- (root / "pyproject.toml").write_text("[project]\n", encoding="utf-8")- live = root / "venv"- bin_dir = live / ("Scripts" if windows else "bin")- bin_dir.mkdir(parents=True)- python = bin_dir / ("python.exe" if windows else "python")- python.write_text("live interpreter", encoding="utf-8")- sentinel = live / "sentinel"- sentinel.write_text("live", encoding="utf-8")- return root, live, sentinel--# ----------------------------------------------------------------------------# managed_uv_path-# -----------------------------------------------------------------------------class TestManagedUvPath:- # POSIX arm of the name mapping; the Windows arm (uv.exe) is exercised- # for real by TestEnsureUvWindowsSafe on the Windows lane.- @pytest.mark.skipif(sys.platform == "win32", reason="POSIX-only: bin/uv name")- def test_posix(self, tmp_path):- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path):- from hermes_cli.managed_uv import managed_uv_path- assert managed_uv_path() == tmp_path / "bin" / "uv"--# ----------------------------------------------------------------------------# resolve_uv-# -----------------------------------------------------------------------------class TestResolveUv:-- def test_existing_executable(self, tmp_path):- uv = tmp_path / "bin" / _UV_BINARY_NAME- _make_executable(uv)- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path):- from hermes_cli.managed_uv import resolve_uv- result = resolve_uv()- assert result == str(uv)-- def test_non_executable_file_returns_none(self, tmp_path):- uv = tmp_path / "bin" / "uv"- uv.parent.mkdir(parents=True)- uv.write_text("not a binary", encoding="utf-8")- # Ensure no execute bit- uv.chmod(0o644)- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path):- from hermes_cli.managed_uv import resolve_uv- assert resolve_uv() is None--class TestPipInstallHint:-- def test_names_the_managed_uv_when_present(self, tmp_path):- uv = tmp_path / "bin" / _UV_BINARY_NAME- _make_executable(uv)- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path):- from hermes_cli.managed_uv import pip_install_hint- assert pip_install_hint("qrcode") == f"{uv} pip install --python {sys.executable} qrcode"-- def test_falls_back_to_bare_uv_when_absent(self, tmp_path):- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path):- from hermes_cli.managed_uv import pip_install_hint- assert pip_install_hint("qrcode") == f"uv pip install --python {sys.executable} qrcode"--# ----------------------------------------------------------------------------# ensure_uv-# -----------------------------------------------------------------------------class TestEnsureUv:-- def test_installs_if_missing(self, tmp_path):- uv = tmp_path / "bin" / _UV_BINARY_NAME- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \- patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")), \- patch("hermes_cli.managed_uv._uv_version", return_value="uv 0.1.2"), \- patch("hermes_cli.managed_uv._install_uv") as mock_install:- # Simulate the installer creating the binary (host-native name:- # uv.exe on Windows, uv on POSIX).- def fake_install(target):- _make_executable(target)- mock_install.side_effect = fake_install-- from hermes_cli.managed_uv import ensure_uv- path = ensure_uv()- assert path == str(uv)- mock_install.assert_called_once()-- def test_dead_managed_launcher_is_reinstalled(self, tmp_path):- """A managed uv that exists, is executable, and exits non-zero (a relocated shim a pre-fix- installer copied in) must be replaced, not handed out."""- uv = tmp_path / "bin" / _UV_BINARY_NAME- uv.parent.mkdir(parents=True)- uv.write_text("#!/bin/sh\necho 'launcher target missing' >&2\nexit 1\n", encoding="utf-8")- uv.chmod(uv.stat().st_mode | stat.S_IEXEC)- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \- patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")), \- patch("hermes_cli.managed_uv._uv_version", return_value="uv 0.1.2"), \- patch("hermes_cli.managed_uv._install_uv", side_effect=_make_executable) as mock_install:- from hermes_cli.managed_uv import ensure_uv- assert ensure_uv() == str(uv)- mock_install.assert_called_once_with(uv)-- def test_install_reports_runtime_repair_to_observer(self, tmp_path):- from hermes_cli.managed_uv import (- RuntimeRepairResult,- ensure_uv,- )-- repair = RuntimeRepairResult(- "repaired",- sqlite_before="3.50.4",- sqlite_after="3.53.1",- )-- def fake_install(target):- _make_executable(target)-- observed = []- with patch(- "hermes_cli.managed_uv.get_hermes_home",- return_value=tmp_path,- ), patch(- "hermes_cli.managed_uv._install_uv",- side_effect=fake_install,- ), patch(- "hermes_cli.managed_uv._uv_version",- return_value="uv 0.1.2",- ), patch(- "hermes_cli.managed_uv.repair_vulnerable_runtime",- return_value=repair,- ):- path = ensure_uv(repair_observer=observed.append)-- assert path == str(tmp_path / "bin" / _UV_BINARY_NAME)- assert observed == [repair]-[email protected](sys.platform == "win32",- reason="POSIX-only: the _UvResult dual contract is not offered on Windows")-class TestEnsureUvUpdateBoundary:- """``ensure_uv()`` must answer to both the single-value and the legacy- ``(path, fresh_bootstrap)`` call conventions — **on POSIX**.-- ``hermes update`` runs the call site from the old, already-imported- ``hermes_cli.main`` against the freshly pulled ``managed_uv``. A release- parked on a ``(path, fresh)`` tuple runs ``uv_bin, fresh = ensure_uv()``- against the single-value module; the path is an iterable ``str`` so the- 2-target unpack walked its characters and raised- ``ValueError: too many values to unpack (expected 2)`` (root cause behind- PR #39763), or ``TypeError`` on the ``None`` failure path. On POSIX the- result must therefore be usable as a bare path *and* unpackable as a- 2-tuple, in both the success and failure cases.-- The dual contract is intentionally **not** offered on Windows — see- ``TestEnsureUvWindowsSafe`` for why — so these tests are POSIX-only: the- host's real ``platform.system()`` selects the wrapper branch, nothing is- faked.- """-- def test_success_usable_as_single_value(self, tmp_path):- _make_executable(tmp_path / "bin" / "uv")- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \- patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")):- from hermes_cli.managed_uv import ensure_uv- uv_bin = ensure_uv()- assert uv_bin == str(tmp_path / "bin" / "uv")- assert bool(uv_bin) is True-- def test_success_unpacks_as_legacy_two_tuple(self, tmp_path):- _make_executable(tmp_path / "bin" / "uv")- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \- patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")):- from hermes_cli.managed_uv import ensure_uv- uv_bin, fresh = ensure_uv() # old: uv_bin, fresh_bootstrap = ensure_uv()- assert uv_bin == str(tmp_path / "bin" / "uv")- assert fresh is False-- def test_failure_unpacks_without_raising(self, tmp_path):- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \- patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")), \- patch("hermes_cli.managed_uv._install_uv", side_effect=RuntimeError("network down")):- from hermes_cli.managed_uv import ensure_uv- uv_bin, fresh = ensure_uv()- assert uv_bin is None- assert fresh is False--class TestEnsureUvWindowsSafe:- """On Windows ``ensure_uv()`` must return a plain ``str``/``None``.-- ``subprocess`` on Windows serializes argv through- ``subprocess.list2cmdline``, which iterates every entry *as a string*- (``for c in arg``). The dependency installer feeds uv straight into the- command list (``[uv_bin, "pip", "install", ...]``). A ``str`` subclass- whose ``__iter__`` yields ``(path, fresh_bootstrap)`` instead of characters- therefore injects the bool into the command line and crashes the install- with ``TypeError: sequence item 1: expected str instance, bool found``- (a real field report on a 10-commits-behind Windows install). A single- return value cannot serve both the legacy 2-tuple unpack and Windows- char-iteration — both use the iterator protocol — so Windows opts out of- the wrapper entirely.- """-- @pytest.mark.windows_only- def test_windows_returns_plain_str_safe_for_subprocess(self, tmp_path):- """``windows_only``: the subject is the real Windows opt-out branch and- ``subprocess.list2cmdline`` — the faked ``platform.system`` only ever- proved the branch existed, not that the field crash was fixed on the- host that reported it."""- import subprocess- # On Windows the managed binary is uv.exe (a shell-script stand-in cannot run there, so the- # launcher probe is answered for it).- _make_executable(tmp_path / "bin" / "uv.exe")- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \- patch("hermes_cli.managed_uv._uv_runs", return_value=True), \- patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")):- from hermes_cli.managed_uv import _UvResult, ensure_uv- uv_bin = ensure_uv()- assert type(uv_bin) is str and not isinstance(uv_bin, _UvResult)- # The exact operation that crashed in the field must now succeed.- cmdline = subprocess.list2cmdline([uv_bin, "pip", "install", "-e", "."])- assert "pip" in cmdline and "install" in cmdline--# ----------------------------------------------------------------------------# update_managed_uv-# -----------------------------------------------------------------------------class TestUpdateManagedUv:-- def test_fresh_stamp_skips_network_self_update_but_not_repair(self, tmp_path):- """A recent success stamp must skip `uv self update` entirely while the- vulnerable-runtime repair probe still runs (CVE repair is never gated)."""- import time-- from hermes_cli.managed_uv import RuntimeRepairResult, update_managed_uv-- uv = tmp_path / "bin" / _UV_BINARY_NAME- _make_executable(uv)- # The stamp reader imports get_hermes_home separately from the binary- # resolver. Give both paths the same explicit test root.- stamp = tmp_path / "cache" / ".uv_self_update_stamp"- stamp.parent.mkdir(parents=True, exist_ok=True)- stamp.touch()- # File timestamps can lead time.time() briefly on Windows. Stay well- # inside the freshness window instead of racing its age >= 0 boundary.- recent = time.time() - 60- os.utime(stamp, (recent, recent))-- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \- patch("hermes_cli.managed_uv._uv_self_update_stamp", return_value=stamp), \- patch("hermes_cli.managed_uv.repair_vulnerable_runtime",- return_value=RuntimeRepairResult("skipped")) as mock_repair, \- patch("hermes_cli.managed_uv.subprocess.run") as mock_run:- result = update_managed_uv()-- assert result == str(uv)- assert mock_run.call_count == 0, "fresh stamp must skip the network self-update"- mock_repair.assert_called_once_with(str(uv))-- def test_stale_stamp_runs_self_update_and_refreshes_stamp(self, tmp_path):- import os as _os- import time as _time-- from hermes_cli.managed_uv import UV_SELF_UPDATE_INTERVAL_SECONDS, update_managed_uv-- uv = tmp_path / "bin" / _UV_BINARY_NAME- _make_executable(uv)- # Keep the stamp and binary resolver in the same test root.- stamp = tmp_path / "cache" / ".uv_self_update_stamp"- stamp.parent.mkdir(parents=True, exist_ok=True)- stamp.touch()- old = _time.time() - UV_SELF_UPDATE_INTERVAL_SECONDS - 60- _os.utime(stamp, (old, old))-- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \- patch("hermes_cli.managed_uv._uv_self_update_stamp", return_value=stamp), \- patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")), \- patch("hermes_cli.managed_uv._uv_version", return_value="uv 0.2.0"), \- patch("hermes_cli.managed_uv.subprocess.run") as mock_run:- mock_run.return_value = MagicMock(returncode=0, stdout="uv 0.2.0")- update_managed_uv()-- assert mock_run.call_args_list[0][0][0] == [str(uv), "self", "update"]- assert stamp.stat().st_mtime > old + 30, "successful self-update must refresh the stamp"--class TestManagedPythonStore:- def test_store_is_checkout_scoped_across_profiles(self, tmp_path, monkeypatch):- from hermes_cli.managed_uv import managed_python_install_dir-- checkout = tmp_path / "checkout"- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "profiles" / "alpha"))- alpha = managed_python_install_dir(checkout)- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "profiles" / "beta"))- beta = managed_python_install_dir(checkout)-- expected = checkout / ".hermes-runtime" / "python"- assert alpha == expected- assert beta == expected-- def test_environment_is_private_and_sanitized(self, tmp_path):- from hermes_cli.managed_uv import managed_python_env-- checkout = tmp_path / "checkout"- base_env = {- "KEEP_ME": "yes",- "CONDA_DEFAULT_ENV": "poison",- "CONDA_PREFIX": "/poison/conda",- "UV_PROJECT_ENVIRONMENT": "/poison/project",- "UV_NO_MANAGED_PYTHON": "1",- "UV_PYTHON": "/poison/python",- "UV_PYTHON_DOWNLOADS": "never",- "UV_SYSTEM_PYTHON": "1",- "VIRTUAL_ENV": "/poison/venv",- "PYTHONHOME": "/poison/home",- "PYTHONPATH": "/poison/path",- }-- env = managed_python_env(checkout, base_env=base_env)-- assert env["KEEP_ME"] == "yes"- assert env["UV_MANAGED_PYTHON"] == "1"- assert env["UV_NO_CONFIG"] == "1"- assert env["UV_PYTHON_INSTALL_BIN"] == "0"- assert env["UV_PYTHON_INSTALL_REGISTRY"] == "0"- assert env["UV_PYTHON_INSTALL_DIR"] == str(- checkout / ".hermes-runtime" / "python"- )- for key in (- "CONDA_DEFAULT_ENV",- "CONDA_PREFIX",- "UV_PROJECT_ENVIRONMENT",- "UV_NO_MANAGED_PYTHON",- "UV_PYTHON",- "UV_PYTHON_DOWNLOADS",- "UV_SYSTEM_PYTHON",- "VIRTUAL_ENV",- "PYTHONHOME",- "PYTHONPATH",- ):- assert key not in env- assert base_env["PYTHONHOME"] == "/poison/home"-[email protected](sys.platform == "win32",- reason="POSIX-only: fixtures build the bin/ (not Scripts/) venv layout")-class TestRuntimeRepair:- def test_safe_runtime_is_a_noop(self, tmp_path):- from hermes_cli.managed_uv import repair_vulnerable_runtime-- root, live, sentinel = _make_runtime_install(tmp_path)- current = _runtime_info(live / "bin" / "python", (3, 53, 1))- with patch(- "hermes_cli.managed_uv.probe_sqlite_runtime",- return_value=current,- ), \- patch(- "hermes_cli.managed_uv._install_safe_python_generation"- ) as mock_install:- result = repair_vulnerable_runtime("uv", project_root=root)-- assert result.status == "safe"- assert result.sqlite_before == "3.53.1"- assert result.sqlite_after == "3.53.1"- assert sentinel.read_text(encoding="utf-8") == "live"- assert not (root / ".hermes-runtime").exists()- mock_install.assert_not_called()-- def test_failed_candidate_preserves_live_venv(self, tmp_path):- from hermes_cli.managed_uv import (- _acquire_repair_lock,- _release_repair_lock,- repair_vulnerable_runtime,- )-- root, live, sentinel = _make_runtime_install(tmp_path)- current = _runtime_info(live / "bin" / "python", (3, 50, 4))- generation = root / ".hermes-runtime" / "python" / "generation-test"- candidate_python = generation / "bin" / "python"- candidate_python.parent.mkdir(parents=True)- candidate_python.write_text("candidate interpreter", encoding="utf-8")- fixed = _runtime_info(candidate_python, (3, 53, 1))-- with patch(- "hermes_cli.managed_uv.probe_sqlite_runtime",- side_effect=[current, current],- ), \- patch(- "hermes_cli.managed_uv._install_safe_python_generation",- return_value=(generation, candidate_python, fixed),- ), \- patch(- "hermes_cli.managed_uv._stage_candidate_venv",- side_effect=_CandidateStageError("replacement environment rejected"),- ):- result = repair_vulnerable_runtime("uv", project_root=root)-- assert result.status == "failed"- assert "replacement environment" in result.detail- assert sentinel.read_text(encoding="utf-8") == "live"- assert (live / "bin" / "python").read_text(encoding="utf-8") == (- "live interpreter"- )- assert not generation.exists()- reacquired = _acquire_repair_lock(root / ".hermes-runtime")- assert reacquired is not None- _release_repair_lock(reacquired)-- def test_safe_runtime_sweeps_old_stale_backups(self, tmp_path):- """A fixed runtime reclaims aged venv.stale.runtime-* leftovers- (issue #73109) but leaves fresh ones (possible in-flight repair)."""- import os- import time as _time-- from hermes_cli.managed_uv import repair_vulnerable_runtime-- root, live, sentinel = _make_runtime_install(tmp_path)- old_backup = root / f"{live.name}.stale.runtime-1-2-aaaa"- (old_backup / "bin").mkdir(parents=True)- (old_backup / "bin" / "python").write_text("old", encoding="utf-8")- stale_mtime = _time.time() - 7200- os.utime(old_backup, (stale_mtime, stale_mtime))-- fresh_backup = root / f"{live.name}.stale.runtime-9-9-bbbb"- (fresh_backup / "bin").mkdir(parents=True)-- current = _runtime_info(live / "bin" / "python", (3, 53, 1))- with patch(- "hermes_cli.managed_uv.probe_sqlite_runtime",- return_value=current,- ):- result = repair_vulnerable_runtime("uv", project_root=root)-- assert result.status == "safe"- assert not old_backup.exists(), "aged stale backup must be reclaimed"- assert fresh_backup.exists(), "fresh backup may be an in-flight repair"- assert sentinel.read_text(encoding="utf-8") == "live"-- def test_successful_repair_removes_parked_backup(self, tmp_path):- """After a successful cutover the parked venv is removed instead of- leaking ~1 GB at the project root forever (issue #73109)."""- from hermes_cli.managed_uv import repair_vulnerable_runtime-- root, live, sentinel = _make_runtime_install(tmp_path)- current = _runtime_info(live / "bin" / "python", (3, 50, 4))- generation = root / ".hermes-runtime" / "python" / "generation-test"- candidate_python = generation / "bin" / "python"- candidate_python.parent.mkdir(parents=True)- candidate_python.write_text("candidate interpreter", encoding="utf-8")- fixed = _runtime_info(candidate_python, (3, 53, 1))- candidate_venv = root / ".hermes-runtime" / "venv-candidate"- (candidate_venv / "bin").mkdir(parents=True)- (candidate_venv / "bin" / "python").write_text(- "candidate venv interpreter", encoding="utf-8"- )-- with patch(- "hermes_cli.managed_uv.probe_sqlite_runtime",- side_effect=[current, current],- ), \- patch(- "hermes_cli.managed_uv._install_safe_python_generation",- return_value=(generation, candidate_python, fixed),- ), \- patch(- "hermes_cli.managed_uv._stage_candidate_venv",- return_value=candidate_venv,- ), \- patch(- "hermes_cli.managed_uv._smoke_candidate_venv",- return_value=(True, "", fixed),- ):- result = repair_vulnerable_runtime("uv", project_root=root)-- assert result.status == "repaired"- assert result.backup_venv is not None- assert not result.backup_venv.exists(), (- "parked venv must be removed after a successful repair"- )- leftovers = list(root.glob(f"{live.name}.stale.runtime-*"))- assert leftovers == [], f"no stale markers may remain: {leftovers}"--def _make_candidate_layout(tmp_path):- """The minimal checkout + pinned generation python `_stage_candidate_venv` needs."""- root = tmp_path / "checkout"- root.mkdir()- (root / "uv.lock").write_text("# lock\n", encoding="utf-8")- generation = root / ".hermes-runtime" / "python" / "gen"- python = generation / "bin" / "python"- python.parent.mkdir(parents=True)- python.write_text("py", encoding="utf-8")- return root, generation, python--def _fake_sync_proc(lines, returncode=0):- """``subprocess.Popen`` stand-in for the candidate sync: text lines on stdout."""- proc = MagicMock()- proc.stdout = iter(lines)- proc.wait.return_value = returncode- return proc--class TestStageCandidateVenvCrossPlatform:- """Candidate sync preserves project config and streams progress on every host."""-- def test_sync_keeps_uv_project_config_and_merges_stderr(self, tmp_path):- import subprocess-- from hermes_cli.managed_uv import _stage_candidate_venv-- root, generation, python = _make_candidate_layout(tmp_path)- created = []- synced = []-- def fake_run(argv, **kwargs):- created.append((list(argv), kwargs))- return MagicMock(returncode=0)-- def fake_popen(argv, **kwargs):- synced.append((list(argv), kwargs))- return _fake_sync_proc([])-- with patch("hermes_cli.managed_uv.subprocess.run", side_effect=fake_run), \- patch("hermes_cli.managed_uv.subprocess.Popen", side_effect=fake_popen), \- patch(- "hermes_cli.managed_uv._smoke_candidate_venv",- return_value=(True, "", None),- ):- candidate = _stage_candidate_venv(- "uv",- project_root=root,- generation=generation,- python=python,- )-- assert candidate is not None- assert len(created) == 1- venv_argv, venv_kwargs = created[0]- assert venv_argv[:2] == ["uv", "venv"]- assert "--no-config" in venv_argv- assert venv_kwargs["env"].get("UV_NO_CONFIG") == "1"- sync_argv, sync_kwargs = synced[0]- assert sync_argv[:2] == ["uv", "sync"]- assert "--locked" in sync_argv- assert "--no-config" not in sync_argv- assert "UV_NO_CONFIG" not in sync_kwargs["env"]- assert sync_kwargs["stderr"] == subprocess.STDOUT-- def test_sync_failure_reports_the_child_reason(self, tmp_path, caplog):- """A rejected candidate must say WHY — the child's own diagnosis, not a bare rc.-- The reason rides the rejection into ``RuntimeRepairResult.detail`` (#111417, #111497).- """- import logging-- from hermes_cli.managed_uv import _stage_candidate_venv-- root, generation, python = _make_candidate_layout(tmp_path)- lock_error = [- "Resolving despite existing lockfile due to addition of exclude newer exclusion\n",- "error: The lockfile at `uv.lock` needs to be updated, but `--locked` was provided.\n",- "\n",- "hint: To update the lockfile, run `uv lock`.\n",- ]-- with caplog.at_level(logging.WARNING), \- patch("hermes_cli.managed_uv.subprocess.run", return_value=MagicMock(returncode=0)), \- patch(- "hermes_cli.managed_uv.subprocess.Popen",- return_value=_fake_sync_proc(lock_error, returncode=1),- ), \- patch(- "hermes_cli.managed_uv._smoke_candidate_venv",- return_value=(True, "", None),- ), \- pytest.raises(_CandidateStageError) as rejected:- _stage_candidate_venv(- "uv",- project_root=root,- generation=generation,- python=python,- )-- # The reason is the child's own diagnosis: the error + hint, without the progress noise- # that precedes them. It reaches the rejection the repair returns AND the log.- reason = str(rejected.value)- assert reason.startswith("candidate dependency sync failed (rc=1): ")- assert "error: The lockfile at `uv.lock` needs to be updated" in reason- assert "hint: To update the lockfile, run `uv lock`." in reason- assert "Resolving despite existing lockfile" not in reason- assert "candidate dependency sync failed (rc=1)" in caplog.text- assert "needs to be updated" in caplog.text- assert not list((root / ".hermes-runtime").glob("venv-candidate-*"))--class TestRuntimeCutover:- def test_os_lock_blocks_concurrent_repair_and_releases(self, tmp_path):- from hermes_cli.managed_uv import _acquire_repair_lock, _release_repair_lock-- runtime_root = tmp_path / ".hermes-runtime"- first = _acquire_repair_lock(runtime_root)- assert first is not None- assert _acquire_repair_lock(runtime_root) is None-- _release_repair_lock(first)- second = _acquire_repair_lock(runtime_root)- assert second is not None- _release_repair_lock(second)-- def test_post_swap_smoke_failure_rolls_back_live_venv(self, tmp_path):- from hermes_cli.managed_uv import _cut_over_candidate-- root, live, sentinel = _make_runtime_install(tmp_path)- runtime_root = root / ".hermes-runtime"- candidate = runtime_root / "venv-candidate-test"- candidate.mkdir(parents=True)- (candidate / "sentinel").write_text("candidate", encoding="utf-8")- rejected_info = _runtime_info(candidate / "bin" / "python", (3, 50, 4))-- with patch(- "hermes_cli.managed_uv._smoke_candidate_venv",- return_value=(False, "core import smoke failed", rejected_info),- ):- ok, backup, info, detail = _cut_over_candidate(- candidate,- project_root=root,- )-- assert ok is False- assert backup is None- assert info == rejected_info- assert "post-cutover smoke failed" in detail- assert sentinel.read_text(encoding="utf-8") == "live"- assert (live / "bin" / "python").read_text(encoding="utf-8") == (- "live interpreter"- )- assert not candidate.exists()- assert not list(runtime_root.glob("venv-rejected-*"))--# ----------------------------------------------------------------------------# _install_uv internals-# -----------------------------------------------------------------------------class TestInstallUvInternals:- def test_installer_uses_host_branch_and_managed_directory(self, tmp_path):- """The native installer receives the managed directory, not a PATH default."""- import hermes_cli.managed_uv as managed_uv-- target = tmp_path / "bin" / _UV_BINARY_NAME- with patch("hermes_cli.managed_uv._install_uv_posix") as mock_posix, \- patch("hermes_cli.managed_uv._install_uv_windows") as mock_windows:- managed_uv._install_uv(target)-- host_installer, other_installer = (- (mock_windows, mock_posix) if sys.platform == "win32"- else (mock_posix, mock_windows))- host_installer.assert_called_once()- other_installer.assert_not_called()- call_env = host_installer.call_args[0][0]- assert call_env["UV_INSTALL_DIR"] == str(tmp_path / "bin")- if sys.platform != "win32":- assert call_env["UV_UNMANAGED_INSTALL"] == str(tmp_path / "bin")--class TestRuntimeRequestMinorLine:- """The repair must request the CPython minor line, not the exact patch.-- Real-world constraint (verified live, July 2026): every published- python-build-standalone artifact for 3.11.14 links vulnerable SQLite- 3.50.4 — even with --reinstall. The fixed SQLite (3.53.1) only exists- from 3.11.15. An exact-patch pin makes the repair permanently- impossible on such installs.- """-- def test_requests_minor_line(self):- from hermes_cli.managed_uv import _runtime_request-- info = _runtime_info(Path("/venv/bin/python"), (3, 50, 4))- assert _runtime_request(info) == "3.11"-- @staticmethod- def _run_generation(tmp_path, monkeypatch, current_version, candidate_version):- """Drive _install_safe_python_generation with fakes; return result."""- import hermes_cli.managed_uv as managed_uv- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- state = {}-- def fake_run(cmd, **kwargs):- if "install" in cmd:- state["generation"] = Path(kwargs["env"]["UV_PYTHON_INSTALL_DIR"])- return SimpleNamespace(returncode=0, stdout="", stderr="")- # uv python find → a path inside the generation dir- python = state["generation"] / "cpython" / "bin" / "python3"- python.parent.mkdir(parents=True, exist_ok=True)- python.touch()- return SimpleNamespace(returncode=0, stdout=str(python), stderr="")-- def fake_probe(python, **kwargs):- return SQLiteRuntimeInfo(- executable=Path(python),- base_prefix=Path(python).parent.parent,- python_version=candidate_version,- sqlite_version=(3, 53, 1),- sqlite_version_string="3.53.1",- sqlite_source_id="fixed",- )-- current = SQLiteRuntimeInfo(- executable=Path("/venv/bin/python"),- base_prefix=Path("/venv"),- python_version=current_version,- sqlite_version=(3, 50, 4),- sqlite_version_string="3.50.4",- sqlite_source_id="old",- )- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)- monkeypatch.setattr(managed_uv, "probe_sqlite_runtime", fake_probe)- return managed_uv._install_safe_python_generation(- "uv", project_root=tmp_path, current=current- )-- def test_accepts_newer_patch_same_minor(self, tmp_path, monkeypatch):- result = self._run_generation(- tmp_path, monkeypatch, (3, 11, 14), (3, 11, 15)- )- assert result is not None- _, _, candidate = result- assert candidate.python_version == (3, 11, 15)--class TestPatchRetryOnVulnerableCandidate:- """Regression tests for issue #71250: when the bare minor-line request- (e.g. "3.11") resolves to a candidate that's still vulnerable -- because- uv's default resolution for that host picked an older cached/indexed- patch even though a newer non-vulnerable one is available -- the- provisioner must query the available patches and retry with explicit- newer versions, rather than giving up after the first attempt.- """-- @staticmethod- def _versioned_probe_run(vulnerable_versions, sqlite_fixed=(3, 53, 1)):- """Build a fake subprocess.run where the install/find/probe cycle- resolves to a DIFFERENT candidate Python version depending on which- exact version string was requested, so retries with explicit- patches can be distinguished from the initial bare-minor attempt."""- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- state = {"requested": None}-- def fake_run(cmd, **kwargs):- if "install" in cmd:- # cmd = [uv, "python", "install", <request>, ...]- state["requested"] = cmd[3]- state["generation"] = Path(kwargs["env"]["UV_PYTHON_INSTALL_DIR"])- return SimpleNamespace(returncode=0, stdout="", stderr="")- if "list" in cmd:- return SimpleNamespace(returncode=0, stdout="", stderr="")- # uv python find → a path inside the generation dir, tagged with- # which request produced it so the probe below can look it up.- python = state["generation"] / "cpython" / "bin" / "python3"- python.parent.mkdir(parents=True, exist_ok=True)- python.write_text(state["requested"] or "", encoding="utf-8")- return SimpleNamespace(returncode=0, stdout=str(python), stderr="")-- def fake_probe(python, **kwargs):- requested = Path(python).read_text(encoding="utf-8")- # Bare minor request ("3.11") always resolves to the FIRST- # (worst-case / already-known-vulnerable) version in the list.- if requested in vulnerable_versions or requested == "3.11":- version = (3, 11, 14) if requested == "3.11" else tuple(- int(p) for p in requested.split(".")- )- return SQLiteRuntimeInfo(- executable=Path(python), base_prefix=Path(python).parent.parent,- python_version=version, sqlite_version=(3, 50, 4),- sqlite_version_string="3.50.4", sqlite_source_id="vulnerable",- )- version = tuple(int(p) for p in requested.split("."))- return SQLiteRuntimeInfo(- executable=Path(python), base_prefix=Path(python).parent.parent,- python_version=version, sqlite_version=sqlite_fixed,- sqlite_version_string=".".join(str(p) for p in sqlite_fixed),- sqlite_source_id="fixed",- )-- return fake_run, fake_probe-- def _run(self, tmp_path, monkeypatch, *, vulnerable_versions, patch_list):- import hermes_cli.managed_uv as managed_uv- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- fake_run, fake_probe = self._versioned_probe_run(vulnerable_versions)- current = SQLiteRuntimeInfo(- executable=Path("/venv/bin/python"), base_prefix=Path("/venv"),- python_version=(3, 11, 14), sqlite_version=(3, 50, 4),- sqlite_version_string="3.50.4", sqlite_source_id="old",- )- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)- monkeypatch.setattr(managed_uv, "probe_sqlite_runtime", fake_probe)- monkeypatch.setattr(- managed_uv, "_list_available_patches", lambda *a, **kw: patch_list- )- return managed_uv._install_safe_python_generation(- "uv", project_root=tmp_path, current=current- )-- def test_retries_and_succeeds_with_explicit_newer_patch(self, tmp_path, monkeypatch):- """The exact #71250 scenario: bare '3.11' resolves to vulnerable- 3.11.14, but 3.11.15 (fixed) is available and gets tried explicitly."""- result = self._run(- tmp_path, monkeypatch,- vulnerable_versions={"3.11"},- patch_list=[(3, 11, 15), (3, 11, 14), (3, 11, 13), (3, 11, 12)],- )- assert result is not None, "Must recover via explicit-patch retry"- _, _, candidate = result- assert candidate.python_version == (3, 11, 15)- assert not candidate.wal_reset_vulnerable-- def test_retry_is_bounded_by_max_retries_constant(self, tmp_path, monkeypatch):- """A very long patch list must not result in unbounded retries -- capped at- _MAX_PATCH_RETRIES attempts. After exhausting same-minor retries the- fallback tries the next minor line, which may succeed."""- import hermes_cli.managed_uv as managed_uv-- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- current = SQLiteRuntimeInfo(- executable=Path("/venv/bin/python"), base_prefix=Path("/venv"),- python_version=(3, 11, 14), sqlite_version=(3, 50, 4),- sqlite_version_string="3.50.4", sqlite_source_id="old",- )- # 20 vulnerable patches -- far more than _MAX_PATCH_RETRIES.- huge_patch_list = [(3, 11, v) for v in range(30, 10, -1)]- all_vulnerable = {f"3.11.{v}" for v in range(30, 10, -1)} | {"3.11"}- fake_run2, fake_probe2 = self._versioned_probe_run(all_vulnerable)-- install_calls = []-- def counting_fake_run(cmd, **kwargs):- if "install" in cmd:- install_calls.append(cmd[3])- return fake_run2(cmd, **kwargs)-- monkeypatch.setattr(managed_uv.subprocess, "run", counting_fake_run)- monkeypatch.setattr(managed_uv, "probe_sqlite_runtime", fake_probe2)- monkeypatch.setattr(- managed_uv, "_list_available_patches", lambda *a, **kw: huge_patch_list- )- result = managed_uv._install_safe_python_generation(- "uv", project_root=tmp_path, current=current- )- # The same-minor retries are bounded, but the minor-line fallback- # (3.11 → 3.12) succeeds because the mock returns a fixed build.- assert result is not None, (- "Minor-line fallback should find a fixed 3.12 build"- )- # 1 initial bare-minor attempt + at most _MAX_PATCH_RETRIES retries.- assert managed_uv._MAX_PATCH_RETRIES <= 5, (- "sanity: constant should stay small since each attempt is a "- "real download+install+probe cycle"- )- same_minor_explicit = [- call for call in install_calls if call.startswith("3.11.")- ]- assert len(same_minor_explicit) <= managed_uv._MAX_PATCH_RETRIES, (- f"same-minor explicit retries must be capped: {same_minor_explicit}"- )- assert install_calls[0] == "3.11"- # The run ends the moment the bare next-minor fallback succeeds.- assert install_calls[-1] == "3.12"- assert install_calls.count("3.12") == 1--class TestMinorLineFallForward:- """Regression tests for issue #76106: when EVERY build on the current- minor line (e.g. all of 3.11 on Windows) links a vulnerable SQLite,- the provisioner must fall forward to the next supported minor line- (3.12, then 3.13) -- first via a bare minor request, then via explicit- patches on that line -- instead of leaving the user stuck on every- `hermes update` with no path to a fixed runtime.- """-- @staticmethod- def _mapped_run(resolutions, fixed_versions, install_calls):- """Fake subprocess.run/probe pair driven by explicit tables:-- - *resolutions*: request string -> python_version tuple the probe- reports for that request (bare minors resolve like uv would).- - *fixed_versions*: set of version tuples that link FIXED SQLite;- everything else probes as vulnerable 3.50.4.- - *install_calls*: list collecting each `uv python install` request,- in order, so tests can assert the actual request sequence.- """- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- state: dict = {"requested": None}-- def fake_run(cmd, **kwargs):- if "install" in cmd:- # cmd = [uv, "python", "install", <request>, ...]- state["requested"] = cmd[3]- state["generation"] = Path(kwargs["env"]["UV_PYTHON_INSTALL_DIR"])- install_calls.append(cmd[3])- return SimpleNamespace(returncode=0, stdout="", stderr="")- if "list" in cmd:- return SimpleNamespace(returncode=0, stdout="", stderr="")- # uv python find → a path inside the generation dir, tagged with- # the request that produced it so the probe can look it up.- python = state["generation"] / "cpython" / "bin" / "python3"- python.parent.mkdir(parents=True, exist_ok=True)- python.write_text(state["requested"] or "", encoding="utf-8")- return SimpleNamespace(returncode=0, stdout=str(python), stderr="")-- def fake_probe(python, **kwargs):- requested = Path(python).read_text(encoding="utf-8")- version = resolutions[requested]- if version in fixed_versions:- return SQLiteRuntimeInfo(- executable=Path(python),- base_prefix=Path(python).parent.parent,- python_version=version, sqlite_version=(3, 53, 1),- sqlite_version_string="3.53.1", sqlite_source_id="fixed",- )- return SQLiteRuntimeInfo(- executable=Path(python),- base_prefix=Path(python).parent.parent,- python_version=version, sqlite_version=(3, 50, 4),- sqlite_version_string="3.50.4", sqlite_source_id="vulnerable",- )-- return fake_run, fake_probe-- @staticmethod- def _current_3_11_14():- from hermes_cli.sqlite_runtime import SQLiteRuntimeInfo-- return SQLiteRuntimeInfo(- executable=Path("/venv/bin/python"), base_prefix=Path("/venv"),- python_version=(3, 11, 14), sqlite_version=(3, 50, 4),- sqlite_version_string="3.50.4", sqlite_source_id="old",- )-- def test_explicit_patch_fallback_when_bare_next_minor_is_vulnerable(- self, tmp_path, monkeypatch- ):- """The review-gap scenario from #76252: the bare '3.12' request- resolves to a VULNERABLE 3.12 build, but an explicit 3.12 patch- links fixed SQLite -- the `_list_available_patches(..., '3.12', ...)`- fallback branch must run, skip the already-tried bare resolution,- and succeed via the explicit patch."""- import hermes_cli.managed_uv as managed_uv-- install_calls = []- fake_run, fake_probe = self._mapped_run(- resolutions={- "3.11": (3, 11, 14), # bare current minor: vulnerable- "3.12": (3, 12, 11), # bare next minor: ALSO vulnerable- "3.12.10": (3, 12, 10), # explicit patch: fixed- },- fixed_versions={(3, 12, 10)},- install_calls=install_calls,- )- patch_lists = {- # No newer 3.11 patch exists (the Windows #76106 reality).- "3.11": [(3, 11, 14), (3, 11, 13)],- # Newest 3.12 is the same build the bare request resolved to.- "3.12": [(3, 12, 11), (3, 12, 10)],- }- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)- monkeypatch.setattr(managed_uv, "probe_sqlite_runtime", fake_probe)- monkeypatch.setattr(- managed_uv, "_list_available_patches",- lambda uv_bin, minor, **kw: patch_lists[minor],- )-- result = managed_uv._install_safe_python_generation(- "uv", project_root=tmp_path, current=self._current_3_11_14()- )- assert result is not None, (- "Explicit-patch fallback on the next minor line must recover"- )- _, _, candidate = result- assert candidate.python_version == (3, 12, 10)- assert not candidate.wal_reset_vulnerable- # The actual uv-install request sequence: bare current minor, then- # bare next minor, then STRAIGHT to the fixed explicit patch --- # 3.12.11 must NOT be re-requested explicitly, because the bare- # '3.12' attempt already resolved to (and rejected) that build.- assert install_calls == ["3.11", "3.12", "3.12.10"]-- def test_returns_none_with_bounded_attempts_when_all_minors_exhausted(- self, tmp_path, monkeypatch- ):- """When every build on every supported minor line (3.11-3.13) is- vulnerable, the provisioner must give up with None -- and the total- install workload must stay bounded by _MAX_PATCH_RETRIES per line."""- import hermes_cli.managed_uv as managed_uv-- install_calls = []- resolutions = {"3.11": (3, 11, 14), "3.12": (3, 12, 30), "3.13": (3, 13, 30)}- patch_lists = {}- for minor in (11, 12, 13):- versions = [(3, minor, v) for v in range(30, 10, -1)] # 20 patches- patch_lists[f"3.{minor}"] = versions- for version in versions:- resolutions[".".join(str(p) for p in version)] = version-- fake_run, fake_probe = self._mapped_run(- resolutions=resolutions, fixed_versions=set(),- install_calls=install_calls,- )- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)- monkeypatch.setattr(managed_uv, "probe_sqlite_runtime", fake_probe)- monkeypatch.setattr(- managed_uv, "_list_available_patches",- lambda uv_bin, minor, **kw: patch_lists[minor],- )-- result = managed_uv._install_safe_python_generation(- "uv", project_root=tmp_path, current=self._current_3_11_14()- )- assert result is None, "Nothing fixed anywhere: must give up cleanly"-- cap = managed_uv._MAX_PATCH_RETRIES- # Per line: one bare request + at most _MAX_PATCH_RETRIES explicit- # patches; three lines total (3.11, 3.12, 3.13) and nothing beyond- # 3.13 (requires-python is <3.14).- assert install_calls.count("3.11") == 1- assert install_calls.count("3.12") == 1- assert install_calls.count("3.13") == 1- assert not any(call.startswith("3.14") for call in install_calls)- for minor in (11, 12, 13):- explicit = [- call for call in install_calls- if call.startswith(f"3.{minor}.")- ]- assert len(explicit) <= cap, (- f"3.{minor} explicit retries must be capped at {cap}: {explicit}"- )- assert len(install_calls) <= 3 * (1 + cap)--class TestListAvailablePatches:- """Direct unit tests for _list_available_patches()'s JSON parsing,- against realistic `uv python list --all-versions --output-format json`- output (captured from a real uv 0.11.7 invocation)."""-- SAMPLE_OUTPUT = (- '[{"key":"cpython-3.11.15-linux-x86_64-gnu","version":"3.11.15",'- '"version_parts":{"major":3,"minor":11,"patch":15},"path":null,'- '"symlink":null,"url":"https://example/cpython-3.11.15.tar.gz",'- '"os":"linux","variant":"default","implementation":"cpython",'- '"arch":"x86_64","libc":"gnu"},'- '{"key":"cpython-3.11.14-linux-x86_64-gnu","version":"3.11.14",'- '"version_parts":{"major":3,"minor":11,"patch":14},"path":null,'- '"symlink":null,"url":"https://example/cpython-3.11.14.tar.gz",'- '"os":"linux","variant":"default","implementation":"cpython",'- '"arch":"x86_64","libc":"gnu"},'- '{"key":"pypy-3.11.15-linux-x86_64-gnu","version":"3.11.15",'- '"version_parts":{"major":3,"minor":11,"patch":15},"path":null,'- '"symlink":null,"url":"https://example/pypy-3.11.15.tar.gz",'- '"os":"linux","variant":"default","implementation":"pypy",'- '"arch":"x86_64","libc":"gnu"}]'- )-- def test_parses_and_sorts_newest_first(self, tmp_path, monkeypatch):- import hermes_cli.managed_uv as managed_uv-- def fake_run(cmd, **kwargs):- return SimpleNamespace(returncode=0, stdout=self.SAMPLE_OUTPUT, stderr="")-- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)- result = managed_uv._list_available_patches(- "uv", "3.11", cwd=tmp_path, env={}- )- assert result == [(3, 11, 15), (3, 11, 14)]-- def test_subprocess_exception_returns_empty_list(self, tmp_path, monkeypatch):- import hermes_cli.managed_uv as managed_uv-- def fake_run(cmd, **kwargs):- raise OSError("uv binary not found")-- monkeypatch.setattr(managed_uv.subprocess, "run", fake_run)- assert managed_uv._list_available_patches("uv", "3.11", cwd=tmp_path, env={}) == []--# ----------------------------------------------------------------------------# _refresh_managed_uv_catalog + provisioning retry (issue #72093)-# -----------------------------------------------------------------------------class TestRefreshManagedUvCatalog:- """The managed uv is UV_UNMANAGED_INSTALL'd, so `uv self update` is- disabled and its python-build-standalone catalog freezes at bootstrap- age. python-build-standalone re-releases the same patch versions with- fixed SQLite, so a stale catalog makes provisioning fail forever with- no newer patch number to retry (issue #72093)."""-- def test_version_change_reports_true(self, tmp_path):- import hermes_cli.managed_uv as managed_uv-- versions = iter(["uv 0.1.0", "uv 0.2.0"])- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \- patch("hermes_cli.managed_uv._install_uv"), \- patch(- "hermes_cli.managed_uv._uv_version_string",- side_effect=lambda _uv: next(versions),- ):- # Host-native path: the refresh only acts on the managed binary,- # so the fixture must live at the real host's managed_uv_path()- # (uv on POSIX, uv.exe on Windows) — no platform fake needed.- uv_path = managed_uv.managed_uv_path()- _make_executable(uv_path)- assert managed_uv._refresh_managed_uv_catalog(str(uv_path)) is True-- def test_installer_failure_reports_false(self, tmp_path):- import hermes_cli.managed_uv as managed_uv-- with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \- patch(- "hermes_cli.managed_uv._install_uv",- side_effect=RuntimeError("network down"),- ):- uv_path = managed_uv.managed_uv_path()- _make_executable(uv_path)- assert managed_uv._refresh_managed_uv_catalog(str(uv_path)) is False-[email protected](sys.platform == "win32",- reason="POSIX-only: fixtures build the bin/ (not Scripts/) venv layout")-class TestRepairRetriesAfterUvRefresh:- def _run_repair(self, tmp_path, *, refresh_result, second_attempt):- """Drive repair with the first provisioning attempt failing."""- from hermes_cli.managed_uv import repair_vulnerable_runtime-- root, live, sentinel = _make_runtime_install(tmp_path)- current = _runtime_info(live / "bin" / "python", (3, 50, 4))-- attempts = []-- def fake_install(uv_bin, *, project_root, current):- attempts.append(uv_bin)- if len(attempts) == 1:- return None- return second_attempt(project_root)-- with patch(- "hermes_cli.managed_uv.probe_sqlite_runtime",- return_value=current,- ), \- patch(- "hermes_cli.managed_uv._install_safe_python_generation",- side_effect=fake_install,- ), \- patch(- "hermes_cli.managed_uv._refresh_managed_uv_catalog",- return_value=refresh_result,- ) as mock_refresh, \- patch(- "hermes_cli.managed_uv._stage_candidate_venv",- side_effect=_CandidateStageError("candidate dependency sync failed (rc=1)"),- ):- result = repair_vulnerable_runtime("uv", project_root=root)- return result, attempts, mock_refresh, sentinel-- def test_no_retry_when_refresh_did_not_change_uv(self, tmp_path):- result, attempts, mock_refresh, sentinel = self._run_repair(- tmp_path,- refresh_result=False,- second_attempt=lambda root: None,- )- assert result.status == "failed"- assert len(attempts) == 1- mock_refresh.assert_called_once_with("uv")- assert sentinel.read_text(encoding="utf-8") == "live"-- def test_retries_once_after_successful_refresh(self, tmp_path):- result, attempts, mock_refresh, sentinel = self._run_repair(- tmp_path,- refresh_result=True,- second_attempt=lambda root: None,- )- # Second attempt ran (and also failed) — exactly one retry, no loop.- assert result.status == "failed"- assert len(attempts) == 2- mock_refresh.assert_called_once_with("uv")- assert sentinel.read_text(encoding="utf-8") == "live"-- def test_retry_success_proceeds_to_staging(self, tmp_path):- def second_attempt(root):- generation = root / ".hermes-runtime" / "python" / "generation-retry"- candidate_python = generation / "bin" / "python"- candidate_python.parent.mkdir(parents=True)- candidate_python.write_text("candidate", encoding="utf-8")- return generation, candidate_python, _runtime_info(- candidate_python, (3, 53, 1)- )-- result, attempts, mock_refresh, sentinel = self._run_repair(- tmp_path,- refresh_result=True,- second_attempt=second_attempt,- )- # Provisioning succeeded on retry; staging rejects the candidate,- # proving the retry result flows into the normal pipeline.- assert result.status == "failed"- assert result.detail == "candidate dependency sync failed (rc=1)"- assert len(attempts) == 2- assert sentinel.read_text(encoding="utf-8") == "live"--class TestDefaultLiveVenv:- """_default_live_venv() must cover BOTH install layouts (venv/ and .venv/).-- Historically repair hardcoded venv/, so uv-default/.venv checkouts got- 'not-applicable' on every hermes update and stayed on journal_mode=DELETE- (2,600x slower state.db appends) while the WAL warning promised repair.- """-- def _checkout(self, tmp_path, *dirs):- root = tmp_path / "checkout"- root.mkdir()- (root / "pyproject.toml").write_text("[project]\n", encoding="utf-8")- # Host-native venv layout: bin/python on POSIX, Scripts/python.exe on- # Windows — what _venv_python() resolves on the real host.- if sys.platform == "win32":- bin_dir_name, python_name = "Scripts", "python.exe"- else:- bin_dir_name, python_name = "bin", "python"- for d in dirs:- bin_dir = root / d / bin_dir_name- bin_dir.mkdir(parents=True)- (bin_dir / python_name).write_text("py", encoding="utf-8")- return root-- def test_dot_venv_only_is_targeted(self, tmp_path):- from hermes_cli.managed_uv import _default_live_venv-- root = self._checkout(tmp_path, ".venv")- assert _default_live_venv(root) == root / ".venv"-- def test_managed_venv_takes_precedence(self, tmp_path):- from hermes_cli.managed_uv import _default_live_venv-- root = self._checkout(tmp_path, "venv", ".venv")- assert _default_live_venv(root) == root / "venv"-- def test_neither_layout_keeps_not_applicable(self, tmp_path):- from hermes_cli.managed_uv import (- _default_live_venv,- repair_vulnerable_runtime,- )-- root = self._checkout(tmp_path)- # Neither venv nor .venv has an interpreter -> repair is not applicable.- assert _default_live_venv(root) == root / "venv"- result = repair_vulnerable_runtime("uv", project_root=root)- assert result.status == "not-applicable"--class TestVenvPythonUpdateBoundary:- """``_venv_python`` must survive a hermes_constants predating its symbol.-- ``hermes update`` imports hermes_constants from the OLD checkout, ``git- pull`` replaces that file, and the freshly-pulled managed_uv then runs its- lazy ``from hermes_constants import venv_python_path`` against the module- object already cached in ``sys.modules``. That cached module has no such- symbol, so the import raises — while naming the NEW file on disk, which- plainly contains it, which is what made the error so confusing:-- cannot import name 'venv_python_path' from 'hermes_constants'- (~/.hermes/hermes-agent/hermes_constants.py)-- It aborted the managed-Python runtime repair on the first update from any- release older than the symbol. Same class as the ``ensure_uv()`` arity skew- documented on ``_UvResult``.- """-- def test_recovers_when_the_cached_module_predates_the_symbol(self, monkeypatch):- import hermes_constants-- from hermes_cli.managed_uv import _venv_python-- # The stale in-memory module: the symbol the new code wants is absent,- # exactly as on an install that booted the pre-upgrade checkout. The- # file on disk is the current one, so a reload recovers the real helper.- monkeypatch.delattr(hermes_constants, "venv_python_path", raising=False)-- # Host-native: the subject is the reload-recovery seam, not the- # bin/Scripts mapping — assert whatever layout the real host resolves.- expected = Path("/opt/hermes/venv/Scripts/python.exe") \- if sys.platform == "win32" else Path("/opt/hermes/venv/bin/python")- assert _venv_python(Path("/opt/hermes/venv")) == expecteddiff --git a/tests/hermes_cli/test_slash_confirm_windows.py b/tests/hermes_cli/test_slash_confirm_windows.pyindex cb4a3f72f42..a88301feeac 100644--- a/tests/hermes_cli/test_slash_confirm_windows.py+++ b/tests/hermes_cli/test_slash_confirm_windows.py@@ -198,7 +198,7 @@ class TestConfirmDestructiveSlash:assert outcome["result"] == expected[email protected]_only[email protected]("windows")class TestNativeWindowsNoRawInputDeadlock:"""Anti-regression guard exercising the REAL ``_prompt_text_input``.diff --git a/tests/hermes_cli/test_update_launchd_unloaded_gateway.py b/tests/hermes_cli/test_update_launchd_unloaded_gateway.pyindex e55dc7b9564..e62e05eeaed 100644--- a/tests/hermes_cli/test_update_launchd_unloaded_gateway.py+++ b/tests/hermes_cli/test_update_launchd_unloaded_gateway.py@@ -131,7 +131,7 @@ ai.hermes.gateway = {"""[email protected]_only[email protected]("macos")class TestServicePidSweepExclusion:"""Regression for the PR #75021 review: `_get_service_pids()` must notrely on `launchctl list` alone.diff --git a/tests/hermes_cli/test_update_self_lock.py b/tests/hermes_cli/test_update_self_lock.pydeleted file mode 100644index cb91cd40617..00000000000--- a/tests/hermes_cli/test_update_self_lock.py+++ /dev/null@@ -1,251 +0,0 @@-"""Regression coverage for the updater self-lock deferral (#83569, #86735).--``_detect_venv_python_processes`` excludes the calling process and its-ancestors by design — a CLI ``hermes update`` IS the venv python. Before-this guard, an updater that had already imported a native venv extension-(e.g. ``cryptography.hazmat.bindings._rust``) died mid-sync with-``os error 5`` when ``uv`` tried to replace the mapped ``.pyd``, stranding-the venv half-updated (#83569).--The first version of the guard (#86687) fired as a PRE-FETCH preflight and-keyed on nothing but "is the module in sys.modules" — which was ALWAYS true-while ``bitwarden.py`` imported cryptography at module level, so every-Windows ``hermes update`` exited 2 before even fetching and the update-looped forever (#86735 / #86780 / #86781). The guard is now honest:--* it only reports a loaded module when the dependency sync would actually- REWRITE that distribution (``_dependency_sync_would_rewrite`` — installed- version vs the on-disk pyproject pins);-* it runs AFTER the code swap, immediately before the venv rewrite- (``_abort_dependency_sync_if_self_locked``), so a deferral leaves the- user on NEW code with only the dependency install pending.-"""--from __future__ import annotations--import subprocess-import sys-import textwrap-from pathlib import Path-from unittest.mock import MagicMock, patch--import pytest--import hermes_cli.main as cli_main-from hermes_cli import _early_recovery--ROOT = Path(__file__).resolve().parents[2]--# ----------------------------------------------------------------------------# _dependency_sync_would_rewrite-# -----------------------------------------------------------------------------class TestDependencySyncWouldRewrite:- def _with_pyproject(self, tmp_path, body: str):- (tmp_path / "pyproject.toml").write_text(body, encoding="utf-8")- return patch.object(cli_main, "PROJECT_ROOT", tmp_path)-- def test_satisfied_pin_means_no_rewrite(self, tmp_path):- with self._with_pyproject(- tmp_path,- '[project]\nname = "x"\ndependencies = ["cryptography==1.2.3"]\n',- ), patch("importlib.metadata.version", return_value="1.2.3"):- assert cli_main._dependency_sync_would_rewrite("cryptography") is False-- def test_stale_pin_means_rewrite(self, tmp_path):- with self._with_pyproject(- tmp_path,- '[project]\nname = "x"\ndependencies = ["cryptography==2.0.0"]\n',- ), patch("importlib.metadata.version", return_value="1.2.3"):- assert cli_main._dependency_sync_would_rewrite("cryptography") is True-- def test_missing_distribution_means_rewrite(self, tmp_path):- with self._with_pyproject(- tmp_path,- '[project]\nname = "x"\ndependencies = ["cryptography==2.0.0"]\n',- ), patch(- "importlib.metadata.version",- side_effect=Exception("not installed"),- ):- assert cli_main._dependency_sync_would_rewrite("cryptography") is True-- def test_pin_in_optional_extra_is_honored(self, tmp_path):- body = textwrap.dedent(- """- [project]- name = "x"- dependencies = []- [project.optional-dependencies]- all = ["cryptography>=2,<3"]- """- )- with self._with_pyproject(tmp_path, body), patch(- "importlib.metadata.version", return_value="2.5.0"- ):- assert cli_main._dependency_sync_would_rewrite("cryptography") is False- with self._with_pyproject(tmp_path, body), patch(- "importlib.metadata.version", return_value="1.0.0"- ):- assert cli_main._dependency_sync_would_rewrite("cryptography") is True-- def test_unpinned_distribution_is_unknown(self, tmp_path):- with self._with_pyproject(- tmp_path, '[project]\nname = "x"\ndependencies = ["requests"]\n'- ), patch("importlib.metadata.version", return_value="1.0.0"):- assert cli_main._dependency_sync_would_rewrite("pyyaml") is None-- def test_broken_pyproject_is_unknown_never_raises(self, tmp_path):- with self._with_pyproject(tmp_path, "not [valid toml"), patch(- "importlib.metadata.version", return_value="1.0.0"- ):- assert cli_main._dependency_sync_would_rewrite("cryptography") is None--# ----------------------------------------------------------------------------# _detect_self_loaded_native_modules — version-gated detection-# ----------------------------------------------------------------------------[email protected]_only-def test_self_lock_detection_is_noop_off_windows():- with patch.dict(sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}):- assert cli_main._detect_self_loaded_native_modules() == []-[email protected]_only-def test_loaded_module_with_pending_version_change_is_flagged():- with patch.dict(- sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}- ), patch.object(cli_main, "_dependency_sync_would_rewrite", return_value=True):- assert "cryptography (_rust.pyd)" in cli_main._detect_self_loaded_native_modules()-[email protected]_only-def test_loaded_module_already_at_target_version_is_not_flagged():- """#86735 core fix: loaded-but-not-changing must NOT trip the deferral.-- Installed cryptography already satisfies the on-disk pins → the sync- will not touch ``_rust.pyd`` → no lock risk → the update must proceed.- """- with patch.dict(- sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}- ), patch.object(cli_main, "_dependency_sync_would_rewrite", return_value=False):- assert cli_main._detect_self_loaded_native_modules() == []-[email protected]_only-def test_unknown_rewrite_risk_fails_open():- """Uncertain rewrite risk must NOT defer (None → proceed).-- PyYAML is loaded by every CLI process; deferring on an unparseable- pyproject would recreate the #86735 always-firing loop. The missed-- deferral downside is the pre-existing mid-sync failure, which the- marker recovery already handles.- """- with patch.dict(- sys.modules, {"cryptography.hazmat.bindings._rust": MagicMock()}- ), patch.object(cli_main, "_dependency_sync_would_rewrite", return_value=None):- assert cli_main._detect_self_loaded_native_modules() == []--def test_recovered_update_retry_builds_parser_without_native_secret_modules(- monkeypatch,-):- """Parser registration must not re-lock a freshly recovered updater."""- called = []- monkeypatch.setattr(_early_recovery, "_UPDATE_RETRY_RECOVERED", True)- monkeypatch.setattr(cli_main, "cmd_update", lambda args: called.append(args))- monkeypatch.setattr(sys, "argv", ["hermes", "update", "--yes"])- sys.modules.pop("cryptography.hazmat.bindings._rust", None)-- cli_main.main()-- assert len(called) == 1- assert "cryptography.hazmat.bindings._rust" not in sys.modules--# ----------------------------------------------------------------------------# _abort_dependency_sync_if_self_locked — deferral wiring-# -----------------------------------------------------------------------------def test_abort_helper_noop_when_nothing_at_risk():- with patch.object(- cli_main, "_detect_self_loaded_native_modules", return_value=[]- ), patch.object(cli_main, "_defer_update_for_self_lock") as defer:- cli_main._abort_dependency_sync_if_self_locked()- defer.assert_not_called()--def test_abort_helper_defers_and_exits_2(capsys):- marker_writes = []- with patch.object(- cli_main,- "_detect_self_loaded_native_modules",- return_value=["cryptography (_rust.pyd)"],- ), patch.object(- cli_main,- "_write_update_incomplete_marker",- side_effect=lambda: marker_writes.append("written"),- ), pytest.raises(SystemExit) as exc:- cli_main._abort_dependency_sync_if_self_locked()- assert exc.value.code == 2- # Deferral contract: marker dropped so the next fresh launch completes- # the dependency install (the code swap has already happened by now).- assert marker_writes == ["written"]- assert "cryptography (_rust.pyd)" in capsys.readouterr().out--def test_abort_helper_resumes_paused_gateways_before_exit():- resume_calls = []- sentinel = object()- with patch.object(- cli_main,- "_detect_self_loaded_native_modules",- return_value=["cryptography (_rust.pyd)"],- ), patch.object(cli_main, "_write_update_incomplete_marker"), patch.object(- cli_main,- "_resume_windows_gateways_after_update",- side_effect=lambda token: resume_calls.append(token),- ), pytest.raises(SystemExit):- cli_main._abort_dependency_sync_if_self_locked(sentinel)- assert resume_calls == [sentinel]--# ----------------------------------------------------------------------------# Placement: the deferral must NOT fire before the fetch (#86735 / #86780)-# -----------------------------------------------------------------------------# ----------------------------------------------------------------------------# Import hygiene: the update entrypoint must not load cryptography at all-# -----------------------------------------------------------------------------class TestUpdateEntrypointImportHygiene:- """Subprocess-verified: the CLI/update path never eagerly loads crypto.-- Empirical sys.modules assertions in a clean interpreter — the technique- that pinned #86735's root cause. If any future module-level import of- cryptography (or another self-locking native module) creeps back into- the startup path, these fail before a Windows user ever hits the loop.- """-- def _run(self, code: str) -> subprocess.CompletedProcess[str]:- return subprocess.run(- [sys.executable, "-c", code],- capture_output=True,- text=True,- cwd=str(ROOT),- timeout=120,- )-- def test_import_main_does_not_load_self_locking_modules(self):- result = self._run(- textwrap.dedent(- """- import sys- import hermes_cli.main- from hermes_cli.update_cmd import _SELF_LOCKING_NATIVE_MODULES- loaded = [- p for p in _SELF_LOCKING_NATIVE_MODULES- if p in sys.modules and not p.startswith("yaml")- ]- # PyYAML is a base dep every CLI process needs (config parsing);- # it is version-gated instead of import-gated. Everything else- # in the registry must stay lazy.- assert not loaded, f"eagerly loaded self-locking modules: {loaded}"- assert "cryptography.hazmat.bindings._rust" not in sys.modules- print("OK")- """- )- )- assert result.returncode == 0, result.stdout + result.stderr- assert "OK" in result.stdoutdiff --git a/tests/hermes_cli/test_update_shim_fail_closed.py b/tests/hermes_cli/test_update_shim_fail_closed.pydeleted file mode 100644index ad88119ed0a..00000000000--- a/tests/hermes_cli/test_update_shim_fail_closed.py+++ /dev/null@@ -1,186 +0,0 @@-"""Fail-closed shim quarantine (#87331): a contended venv is never mutated.--The bug class: on Windows, when `hermes.exe`/sibling shims could not be-renamed aside (another process holds them without FILE_SHARE_DELETE), the-updater printed a warning and ran the installer anyway — which then died-partway on the same locks and stranded the venv between versions (3x field-reports on one machine, #87331).--Contract pinned here:-- `_run_quarantined_install(strict_quarantine=True)` raises- ShimQuarantineError BEFORE running any install command, and rolls back the- renames that did succeed.-- Non-strict callers keep the old warn-and-try behavior.-- The recovery installer's `_run_install_cmd` is strict unconditionally.-- The update boundary turns the error into a refusal (exit 2) + marker,- never a ZIP fallback.-"""--import os-from pathlib import Path-from unittest import mock--import pytest--from hermes_cli import main_install_repair-import hermes_cli._install_repair as ir-import hermes_cli.update_cmd as update_cmd---def _make_shims(scripts_dir: Path, names=("hermes", "hermes-gateway")) -> list[Path]:- scripts_dir.mkdir(parents=True, exist_ok=True)- shims = []- for name in names:- p = scripts_dir / f"{name}.exe"- p.write_bytes(b"MZ fake")- shims.append(p)- return shims---# ----------------------------------------------------------------------------# main.py: _run_quarantined_install strict mode-# ----------------------------------------------------------------------------[email protected]_only-def test_strict_quarantine_refuses_before_install(tmp_path, monkeypatch):- scripts = tmp_path / "venv" / "Scripts"- shims = _make_shims(scripts)- # hermes.exe cannot be renamed; hermes-gateway.exe can- real_rename = Path.rename-- def deny_hermes(self, target):- if self.name == "hermes.exe":- raise PermissionError(13, "held open")- return real_rename(self, target)-- monkeypatch.setattr(Path, "rename", deny_hermes)- monkeypatch.setattr(main_install_repair, "_hermes_exe_shims", lambda d: shims)-- install_ran = []- monkeypatch.setattr(- main_install_repair, "_run_install_with_heartbeat",- lambda cmd, env=None: install_ran.append(cmd),- )-- with pytest.raises(main_install_repair.ShimQuarantineError) as exc_info:- main_install_repair._run_quarantined_install(- ["uv", "pip", "install", "-e", "."],- scripts_dir=scripts,- strict_quarantine=True,- )-- # The installer NEVER ran — that is the whole fix.- assert install_ran == []- assert "hermes.exe" in exc_info.value.failed_shims- # The successful rename (hermes-gateway.exe) was rolled back.- assert (scripts / "hermes-gateway.exe").exists()- assert not list(scripts.glob("hermes-gateway.exe.old.*"))--[email protected]_only-def test_non_strict_keeps_warn_and_try(tmp_path, monkeypatch):- scripts = tmp_path / "venv" / "Scripts"- shims = _make_shims(scripts, names=("hermes",))- monkeypatch.setattr(- Path, "rename",- mock.Mock(side_effect=PermissionError(13, "held open")),- )- monkeypatch.setattr(main_install_repair, "_hermes_exe_shims", lambda d: shims)-- install_ran = []- monkeypatch.setattr(- main_install_repair, "_run_install_with_heartbeat",- lambda cmd, env=None: install_ran.append(cmd),- )-- # Default (non-strict): installer still runs — old behavior for repair- # paths whose venv is already mutated.- main_install_repair._run_quarantined_install(["fake"], scripts_dir=scripts)- assert install_ran == [["fake"]]--[email protected]_only-def test_strict_all_renames_ok_runs_install(tmp_path, monkeypatch):- scripts = tmp_path / "venv" / "Scripts"- shims = _make_shims(scripts)- monkeypatch.setattr(main_install_repair, "_hermes_exe_shims", lambda d: shims)-- install_ran = []- monkeypatch.setattr(- main_install_repair, "_run_install_with_heartbeat",- lambda cmd, env=None: install_ran.append(cmd),- )- main_install_repair._run_quarantined_install(- ["fake"], scripts_dir=scripts, strict_quarantine=True- )- assert install_ran == [["fake"]]-----# ----------------------------------------------------------------------------# _install_repair.py: recovery installer is strict unconditionally-# ----------------------------------------------------------------------------[email protected]_only-def test_recovery_install_cmd_fail_closed(tmp_path, monkeypatch):- root = tmp_path- scripts = root / "venv" / "Scripts"- _make_shims(scripts, names=("hermes",))-- monkeypatch.setattr(ir, "_venv_scripts_dir", lambda r: scripts)- monkeypatch.setattr(- Path.__module__ and os, "rename",- mock.Mock(side_effect=PermissionError(13, "held open")),- )-- run_calls = []- monkeypatch.setattr(- ir.subprocess, "run", lambda *a, **k: run_calls.append(a)- )-- with pytest.raises(ir.ShimQuarantineError):- ir._run_install_cmd(["fake"], env=None, root=root)- assert run_calls == [] # contended venv never mutated--[email protected]_only-def test_recovery_install_cmd_ok_when_uncontended(tmp_path, monkeypatch):- root = tmp_path- scripts = root / "venv" / "Scripts"- _make_shims(scripts, names=("hermes",))- monkeypatch.setattr(ir, "_venv_scripts_dir", lambda r: scripts)-- run_calls = []- monkeypatch.setattr(- ir.subprocess, "run",- lambda *a, **k: run_calls.append(a) or mock.Mock(returncode=0),- )- ir._run_install_cmd(["fake"], env=None, root=root)- assert len(run_calls) == 1---# ----------------------------------------------------------------------------# update_cmd.py: boundary refusal — marker + exit 2, no ZIP fallback-# -----------------------------------------------------------------------------def test_refusal_writes_marker_and_exits_2(monkeypatch, capsys):- wrote = []- monkeypatch.setattr(- update_cmd, "_write_update_incomplete_marker", lambda: wrote.append(1)- )- exc = main_install_repair.ShimQuarantineError(["hermes.exe"])- with pytest.raises(SystemExit) as exit_info:- update_cmd._refuse_update_for_contended_shims(exc)- assert exit_info.value.code == 2- assert wrote == [1]- assert "hermes.exe" in capsys.readouterr().out---def test_shim_error_type_resolves_real_class():- assert update_cmd._shim_quarantine_error_type() is main_install_repair.ShimQuarantineError---def test_shim_error_is_not_a_zip_fallback_trigger():- exc = main_install_repair.ShimQuarantineError(["hermes.exe"])- assert update_cmd._should_zip_fallback_on_update_error(exc) is Falsediff --git a/tests/hermes_cli/test_update_stale_dashboard.py b/tests/hermes_cli/test_update_stale_dashboard.pyindex 5246a37df61..344116bc69e 100644--- a/tests/hermes_cli/test_update_stale_dashboard.py+++ b/tests/hermes_cli/test_update_stale_dashboard.py@@ -24,8 +24,7 @@ from hermes_cli.main_dashboard import _find_stale_dashboard_pidsfrom hermes_cli.dashboard_procs import _kill_stale_dashboard_processesfrom hermes_cli import dashboard_procsfrom hermes_cli import main_dashboard-from hermes_cli import update_cmd-from hermes_cli.update_cmd import _finish_dashboard_update_cleanup+from hermes_cli import update_cmd_maint@pytest.fixture(autouse=True)@@ -38,12 +37,10 @@ def _refresh_bindings_against_live_module():patches the *new* one, so every patch becomes a no-op and the kill pathsilently returns early. Refreshing the bindings keeps them consistent."""- global _finish_dashboard_update_cleanupglobal _find_stale_dashboard_pidsglobal _kill_stale_dashboard_processesglobal _restart_managed_dashboard_service- _finish_dashboard_update_cleanup = update_cmd._finish_dashboard_update_cleanup_find_stale_dashboard_pids = main_dashboard._find_stale_dashboard_pids_kill_stale_dashboard_processes = dashboard_procs._kill_stale_dashboard_processes_restart_managed_dashboard_service = main_dashboard._restart_managed_dashboard_service@@ -166,11 +163,11 @@ class TestFindStaleDashboardPids:with patch("subprocess.run", side_effect=sp.TimeoutExpired("ps", 10)):assert _find_stale_dashboard_pids() == []- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_ps_timeout_returns_empty_linux(self):self._assert_ps_timeout_returns_empty()- @pytest.mark.macos_only+ @pytest.mark.platforms("macos")def test_ps_timeout_returns_empty_macos(self):self._assert_ps_timeout_returns_empty()@@ -254,7 +251,7 @@ class TestKillStaleDashboardPosix:class TestKillStaleDashboardWindows:"""Kill path on Windows: taskkill /F."""- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_taskkill_invoked_for_each_pid(self, capsys):"""``windows_only``: ``taskkill.exe`` only exists on Windows, and thefaked platform also silently skipped the POSIX-only cgroup/argv@@ -295,7 +292,7 @@ class TestDashboardUpdateCleanup:return_value={"matched": [12345], "killed": [], "failed": [(12345, "denied")],"unrecovered": []},) as kill:- _finish_dashboard_update_cleanup([])+ update_cmd_maint._refresh_dashboard_after_update()# The sweep only touches this home's backends (#113978).assert kill.call_args.kwargs["scope_home"] == str(own_home)@@ -717,7 +714,7 @@ class TestCmdlineCapture:assert argv == ["hermes", "serve", "--port", "8300"]- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_returns_none_on_windows(self):"""``windows_only``: the contract is "no graceful-argv capture on areal Windows host" — asserting it against a faked platform only@@ -734,9 +731,8 @@ class TestPostUpdateDashboardCleanupIsolation:tail (matrix, reconciliation, inner receipt finalize): contained, visible, recorded asa failed step on the open receipt."""import hermes_cli.update_receipt as ur- from hermes_cli import update_cmd- ur._current = None+ ur._current.set(None)try:ur.begin_update_receipt()with patch(@@ -745,11 +741,11 @@ class TestPostUpdateDashboardCleanupIsolation:"module 'hermes_cli.main_dashboard' has no attribute '_loaded_launchd_backend_jobs'"),):- update_cmd._finish_dashboard_update_cleanup([]) # must not raise+ update_cmd_maint._refresh_dashboard_after_update() # must not raise- steps = {s["name"]: s for s in ur._current.data["steps"]}+ steps = {s["name"]: s for s in ur._current.get().data["steps"]}finally:- ur._current = None+ ur._current.set(None)assert steps["dashboard_cleanup"]["ok"] is Falseassert "_loaded_launchd_backend_jobs" in steps["dashboard_cleanup"]["detail"]diff --git a/tests/hermes_cli/test_web_server_ws_ping.py b/tests/hermes_cli/test_web_server_ws_ping.pyindex 2dbdf24b474..54ad2bac881 100644--- a/tests/hermes_cli/test_web_server_ws_ping.py+++ b/tests/hermes_cli/test_web_server_ws_ping.py@@ -148,7 +148,7 @@ def test_start_server_enables_ws_ping_for_half_open_detection(monkeypatch):assert captured["ws_ping_timeout"] >= captured["ws_ping_interval"][email protected]_only[email protected]("windows")def test_start_server_runs_on_uvicorns_loop_factory(monkeypatch):"""The dashboard/desktop backend must serve uvicorn on the loop *uvicorn*selects, not the interpreter default.@@ -236,7 +236,7 @@ def test_start_server_treats_posix_keyboardinterrupt_as_clean_shutdown(monkeypat)[email protected]_only[email protected]("windows")def test_start_server_treats_windows_keyboardinterrupt_as_clean_shutdown(monkeypatch):"""Console Ctrl+C on the Windows loop-factory branch is a clean exit too.@@ -269,7 +269,7 @@ def test_start_server_treats_windows_keyboardinterrupt_as_clean_shutdown(monkeyp)[email protected]_only[email protected]("windows")def test_start_server_treats_windows_fallback_keyboardinterrupt_as_clean_shutdown(monkeypatch,):diff --git a/tests/hermes_state/test_state_db_write_durability.py b/tests/hermes_state/test_state_db_write_durability.pyindex b1b1ca0afc9..dcdbe44f508 100644--- a/tests/hermes_state/test_state_db_write_durability.py+++ b/tests/hermes_state/test_state_db_write_durability.py@@ -53,7 +53,7 @@ def _make_db(tmp_path: Path) -> Path:# ── Repair-path write durability ────────────────────────────────────────[email protected]_only[email protected]("macos")def test_connect_repair_durable_sets_macos_barriers(tmp_path: Path) -> None:"""The repair connection must carry both macOS durability barriers."""db = _make_db(tmp_path)diff --git a/tests/hermes_state/test_state_synchronous_pragma.py b/tests/hermes_state/test_state_synchronous_pragma.pyindex caa5350cf67..c059471d680 100644--- a/tests/hermes_state/test_state_synchronous_pragma.py+++ b/tests/hermes_state/test_state_synchronous_pragma.py@@ -97,7 +97,7 @@ class TestResolveSynchronousLevel:class TestAppliedFromConfig:- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_configured_level_reaches_the_connection(self, tmp_path, monkeypatch):_config(monkeypatch, {"synchronous": "NORMAL"})conn = _wal_conn(tmp_path)@@ -172,7 +172,7 @@ class TestMacOSFloor:floor the config value would simply win by running last."""- @pytest.mark.macos_only+ @pytest.mark.platforms("macos")def test_lowering_below_full_is_refused_on_darwin(self, tmp_path, monkeypatch, caplog):@@ -187,7 +187,7 @@ class TestMacOSFloor:finally:conn.close()- @pytest.mark.macos_only+ @pytest.mark.platforms("macos")def test_raising_above_full_is_allowed_on_darwin(self, tmp_path, monkeypatch):"""The floor is a floor, not a pin -- EXTRA is strictly safer."""_config(monkeypatch, {"synchronous": "EXTRA"})diff --git a/tests/scripts/install/test_install_sh_uv_lock_config.py b/tests/scripts/install/test_install_sh_uv_lock_config.pydeleted file mode 100644index 5c6da1d765e..00000000000--- a/tests/scripts/install/test_install_sh_uv_lock_config.py+++ /dev/null@@ -1,90 +0,0 @@-"""Regression coverage for project-aware locked syncs in Unix installers."""--from __future__ import annotations--import os-from pathlib import Path-import shutil-import subprocess--import pytest--REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent-INSTALL_SCRIPTS = (- REPO_ROOT / "scripts" / "install.sh",- REPO_ROOT / "setup-hermes.sh",-)-_HELPER_START = "run_locked_uv_sync() {\n"--def _locked_sync_helper(path: Path) -> str:- text = path.read_text(encoding="utf-8")- _, marker, rest = text.partition(_HELPER_START)- assert marker, f"{path.name} is missing run_locked_uv_sync()"- body, end, _ = rest.partition("\n}\n")- assert end, f"{path.name} has an unterminated run_locked_uv_sync()"- return marker + body + end--def _bash_path(path: Path) -> str:- if os.name != "nt":- return str(path)- drive = path.drive.rstrip(":").lower()- tail = path.as_posix().split(":", 1)[1].lstrip("/")- return f"/mnt/{drive}/{tail}"--def test_locked_sync_helper_sanitizes_only_its_subprocess(tmp_path: Path) -> None:- bash = shutil.which("bash")- if bash is None:- pytest.skip("bash is unavailable")-- record = tmp_path / "uv-args.txt"- fake_uv = tmp_path / "uv"- fake_uv.write_text(- """#!/bin/sh-test -z "${UV_NO_CONFIG+x}" || exit 10-test -z "${UV_CONFIG_FILE+x}" || exit 11-test -d "$XDG_CONFIG_HOME" || exit 12-test "$XDG_CONFIG_HOME" = "$XDG_CONFIG_DIRS" || exit 13-printf '%s\n' "$@" > "$RECORD"-""",- encoding="utf-8",- newline="\n",- )-- harness = tmp_path / "harness.sh"- harness.write_text(- """#!/bin/bash-set -eu-UV_CMD="sh $1"-RECORD="$2"-export UV_CMD RECORD-export UV_NO_CONFIG=1-export UV_CONFIG_FILE=/poison/uv.toml-export XDG_CONFIG_HOME=/poison/user-export XDG_CONFIG_DIRS=/poison/system-"""- + _locked_sync_helper(INSTALL_SCRIPTS[0])- + """-run_locked_uv_sync /tmp/hermes-venv-test "$UV_NO_CONFIG" = 1-test "$UV_CONFIG_FILE" = /poison/uv.toml-test "$XDG_CONFIG_HOME" = /poison/user-test "$XDG_CONFIG_DIRS" = /poison/system-""",- encoding="utf-8",- newline="\n",- )-- result = subprocess.run(- [bash, _bash_path(harness), _bash_path(fake_uv), _bash_path(record)],- capture_output=True,- text=True,- check=False,- )-- assert result.returncode == 0, result.stderr- assert record.read_text(encoding="utf-8").splitlines() == [- "sync",- "--extra",- "all",- "--locked",- ]diff --git a/tests/test_atomic_replace_symlinks.py b/tests/test_atomic_replace_symlinks.pyindex e78ce49695b..9fcdf9c16c9 100644--- a/tests/test_atomic_replace_symlinks.py+++ b/tests/test_atomic_replace_symlinks.py@@ -313,7 +313,7 @@ def fast_replace_retries(monkeypatch: pytest.MonkeyPatch) -> None:# ── cross-platform: the retry/fallback state machine ──────────────────────[email protected]_only[email protected]("windows")@pytest.mark.parametrize("winerror", [5, 32, 33])def test_contended_rename_retries_then_rewrites_in_place(tmp_path: Path,@@ -347,7 +347,7 @@ def test_contended_rename_retries_then_rewrites_in_place(assert not tmp.exists()[email protected]_only[email protected]("windows")def test_contended_rename_retry_wins_keeps_write_atomic(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fast_replace_retries: None) -> None:@@ -379,7 +379,7 @@ def test_contended_rename_retry_wins_keeps_write_atomic(assert not tmp.exists()[email protected]_only[email protected]("windows")def test_genuine_denial_propagates_after_budget(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fast_replace_retries: None) -> None:@@ -409,7 +409,7 @@ def test_genuine_denial_propagates_after_budget(assert tmp.exists(), "the pending write must survive for the caller"[email protected]_only[email protected]("windows")def test_contended_retry_switching_to_exdev_uses_copy_fallback(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fast_replace_retries: None) -> None:@@ -506,7 +506,7 @@ def test_in_place_rewrite_never_exposes_a_truncated_file(assert observed == [5000][email protected]_only[email protected]("windows")@pytest.mark.require_symlinksdef test_symlinked_target_survives_a_contended_rename(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fast_replace_retries: Nonediff --git a/tests/test_hermes_constants.py b/tests/test_hermes_constants.pyindex 6254802a320..f6e41166230 100644--- a/tests/test_hermes_constants.py+++ b/tests/test_hermes_constants.py@@ -3,39 +3,30 @@import osimport sysfrom pathlib import Path-from types import SimpleNamespaceimport pytestimport hermes_constantsfrom hermes_platform.host import runtime as host_runtime-from hermes_platform.host import facts as host_factsfrom hermes_constants import (agent_browser_runnable,- find_hermes_node_executable,- find_node_executable,- find_node_executable_on_path,get_default_hermes_root,get_hermes_dir,get_hermes_home,get_process_hermes_home,- heal_hermes_managed_node,- hermes_managed_node_tree_present,- iter_hermes_node_dirs,is_container,node_tool_runnable,parse_reasoning_effort,reset_hermes_home_override,secure_parent_dir,set_hermes_home_override,- with_hermes_node_path,)class TestGetDefaultHermesRoot:"""Tests for get_default_hermes_root() — Docker/custom deployment awareness."""- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_no_hermes_home_returns_native(self, tmp_path, monkeypatch):"""When HERMES_HOME is not set, returns ~/.hermes."""monkeypatch.delenv("HERMES_HOME", raising=False)@@ -68,7 +59,7 @@ class TestGetDefaultHermesRoot:assert get_default_hermes_root() == custom_root- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_no_hermes_home_returns_localappdata_root_on_windows(self, tmp_path, monkeypatch):"""Native Windows falls back to %LOCALAPPDATA%\\hermes, not ~/.hermes."""local_appdata = tmp_path / "LocalAppData"@@ -86,7 +77,7 @@ class TestGetDefaultHermesRoot:class TestGetHermesHome:"""Tests for get_hermes_home() platform-aware fallback."""- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_windows_fallback_uses_localappdata(self, tmp_path, monkeypatch):"""When HERMES_HOME is unset on Windows, use %LOCALAPPDATA%\\hermes."""local_appdata = tmp_path / "LocalAppData"@@ -134,189 +125,15 @@ class TestGetProcessHermesHome:-class TestHermesManagedNode:- @pytest.mark.windows_only- def test_windows_node_dir_prefers_portable_root(self, tmp_path, monkeypatch):- home = tmp_path / "hermes"- node_dir = home / "node"- bin_dir = node_dir / "bin"- node_dir.mkdir(parents=True)- bin_dir.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))-- assert iter_hermes_node_dirs() == [node_dir, bin_dir]-- @pytest.mark.windows_only- def test_windows_finds_npm_cmd_before_path(self, tmp_path, monkeypatch):- home = tmp_path / "hermes"- node_dir = home / "node"- node_dir.mkdir(parents=True)- npm_cmd = node_dir / "npm.cmd"- npm_cmd.write_text("@echo off\n")- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setattr(hermes_constants, "node_tool_runnable", lambda path: True)-- assert find_hermes_node_executable("npm") == str(npm_cmd)---- @pytest.mark.windows_only- def test_windows_skips_broken_managed_npm_without_path_fallback(self, tmp_path, monkeypatch):- home = tmp_path / "hermes"- managed_npm = home / "node" / "npm.cmd"- managed_npm.parent.mkdir(parents=True)- managed_npm.write_text("@echo off\n")- bin_dir = tmp_path / "nodejs"- bin_dir.mkdir()- path_npm = bin_dir / "npm.cmd"- path_npm.write_text("@echo off\n")- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setenv("PATH", str(bin_dir))- monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)- monkeypatch.setattr(hermes_constants, "heal_hermes_managed_node", lambda: False)- monkeypatch.setattr(- hermes_constants,- "node_tool_runnable",- lambda path: False,- )-- assert hermes_managed_node_tree_present() is True- assert find_node_executable("npm") is None- assert find_node_executable("npm") != str(path_npm)--[email protected](os.name == "nt", reason="POSIX shell stubs; Windows uses .cmd shims")class TestNodeToolRunnable:- """node_tool_runnable() rejects broken Hermes-managed npm/node wrappers."""-- def _stub(self, tmp_path, name, body, mode=0o755):- path = tmp_path / name- path.write_text(body)- path.chmod(mode)- return path+ """Empty executable paths cannot be probed."""def test_none_and_empty_rejected(self):assert node_tool_runnable(None) is Falseassert node_tool_runnable("") is False-- def test_broken_managed_npm_heals_when_node_still_runs(self, tmp_path, monkeypatch):- """npm can fail while node --version still succeeds (missing lib/cli.js)."""- profile_home = tmp_path / "profiles" / "assistant"- managed_bin = profile_home / "node" / "bin"- managed_bin.mkdir(parents=True)- self._stub(managed_bin, "node", "#!/bin/sh\necho '22.0.0'\nexit 0\n")- broken_npm = self._stub(managed_bin, "npm", "#!/bin/sh\nexit 1\n")- heal_called = {"value": False}-- system_bin = tmp_path / "system-bin"- system_bin.mkdir()- self._stub(system_bin, "npm", "#!/bin/sh\necho '11.10.0'\nexit 0\n")-- monkeypatch.setenv("HERMES_HOME", str(profile_home))- monkeypatch.setenv("PATH", str(system_bin))- monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)-- def _heal():- heal_called["value"] = True- broken_npm.write_text("#!/bin/sh\necho '22.0.0'\nexit 0\n")- broken_npm.chmod(0o755)- return True-- monkeypatch.setattr(hermes_constants, "heal_hermes_managed_node", _heal)-- resolved = find_node_executable("npm")- assert heal_called["value"] is True- assert resolved == str(broken_npm)- assert resolved != str(system_bin / "npm")--- def test_broken_managed_npm_returns_none_when_heal_fails(self, tmp_path, monkeypatch):- profile_home = tmp_path / "profiles" / "assistant"- managed_bin = profile_home / "node" / "bin"- managed_bin.mkdir(parents=True)- self._stub(managed_bin, "npm", "#!/bin/sh\nexit 1\n")-- system_bin = tmp_path / "system-bin"- system_bin.mkdir()- self._stub(system_bin, "npm", "#!/bin/sh\necho '11.10.0'\nexit 0\n")-- monkeypatch.setenv("HERMES_HOME", str(profile_home))- monkeypatch.setenv("PATH", str(system_bin))- monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)- monkeypatch.setattr(hermes_constants, "heal_hermes_managed_node", lambda: False)-- assert find_node_executable("npm") is None-- def test_outdated_managed_node_heals_to_target_major(self, tmp_path, monkeypatch):- """A healthy managed tree below the target major upgrades on next resolve."""- target = hermes_constants._HERMES_NODE_TARGET_MAJOR- profile_home = tmp_path / "profiles" / "assistant"- managed_bin = profile_home / "node" / "bin"- managed_bin.mkdir(parents=True)- old_node = self._stub(- managed_bin, "node", f"#!/bin/sh\necho 'v{target - 1}.20.0'\nexit 0\n"- )- heal_called = {"value": False}-- monkeypatch.setenv("HERMES_HOME", str(profile_home))- monkeypatch.setenv("PATH", "")- monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)-- def _heal():- heal_called["value"] = True- old_node.write_text(f"#!/bin/sh\necho 'v{target}.5.1'\nexit 0\n")- old_node.chmod(0o755)- return True-- monkeypatch.setattr(hermes_constants, "heal_hermes_managed_node", _heal)-- resolved = hermes_constants.find_hermes_node_executable("node")- assert heal_called["value"] is True- assert resolved == str(old_node)-- def test_outdated_managed_node_survives_failed_heal(self, tmp_path, monkeypatch):- """Offline heal failure keeps serving the old tree — old Node beats no Node."""- target = hermes_constants._HERMES_NODE_TARGET_MAJOR- profile_home = tmp_path / "profiles" / "assistant"- managed_bin = profile_home / "node" / "bin"- managed_bin.mkdir(parents=True)- old_node = self._stub(- managed_bin, "node", f"#!/bin/sh\necho 'v{target - 1}.20.0'\nexit 0\n"- )-- monkeypatch.setenv("HERMES_HOME", str(profile_home))- monkeypatch.setenv("PATH", "")- monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)- monkeypatch.setattr(hermes_constants, "heal_hermes_managed_node", lambda: False)-- assert hermes_constants.find_hermes_node_executable("node") == str(old_node)-- def test_target_major_managed_node_does_not_heal(self, tmp_path, monkeypatch):- """A tree already at the target major never triggers the heal."""- target = hermes_constants._HERMES_NODE_TARGET_MAJOR- profile_home = tmp_path / "profiles" / "assistant"- managed_bin = profile_home / "node" / "bin"- managed_bin.mkdir(parents=True)- node = self._stub(- managed_bin, "node", f"#!/bin/sh\necho 'v{target}.5.1'\nexit 0\n"- )-- monkeypatch.setenv("HERMES_HOME", str(profile_home))- monkeypatch.setenv("PATH", "")- monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)-- def _heal():- raise AssertionError("heal must not run for an up-to-date tree")-- monkeypatch.setattr(hermes_constants, "heal_hermes_managed_node", _heal)-- assert hermes_constants.find_hermes_node_executable("node") == str(node)---class TestIsContainer:"""Tests for is_container() — Docker/Podman detection."""@@ -650,7 +467,7 @@ class TestSecureParentDir:assert called_with[0] == (str(real_dir), 0o700)[email protected](os.name == "nt", reason="POSIX shell stubs; Windows uses .cmd shims")[email protected]("posix") # POSIX shell stubs; Windows uses .cmd shimsclass TestAgentBrowserRunnable:"""agent_browser_runnable() validates the resolved CLI actually runs.@@ -775,380 +592,7 @@ class TestWslPathTranslation:assert hermes_constants.translate_cwd_for_wsl_backend("/home/alex") == "/home/alex"[email protected]_only-class TestManagedNodeTreeInUse:- """managed_node_tree_in_use() detects processes executing from the tree."""-- def _install_fake_psutil(self, monkeypatch, procs):- import sys-- fake = SimpleNamespace(- process_iter=lambda fields: [- SimpleNamespace(info=info) for info in procs- ]- )- monkeypatch.setitem(sys.modules, "psutil", fake)-- def test_exe_under_node_dir_counts(self, tmp_path, monkeypatch):- home = tmp_path / "hermes"- (home / "node").mkdir(parents=True)- monkeypatch.setenv("HERMES_HOME", str(home))- self._install_fake_psutil(- monkeypatch,- [{"exe": str(home / "node" / "node.exe"), "cmdline": None}],- )- assert hermes_constants.managed_node_tree_in_use() is True-- def test_cmdline_arg_under_node_dir_counts(self, tmp_path, monkeypatch):- home = tmp_path / "hermes"- (home / "node").mkdir(parents=True)- monkeypatch.setenv("HERMES_HOME", str(home))- self._install_fake_psutil(- monkeypatch,- [- {- "exe": r"C:\Windows\System32\cmd.exe",- "cmdline": [r"C:\Windows\System32\cmd.exe", "/d", "/s", "/c", str(home / "node" / "npm.cmd")],- }- ],- )- assert hermes_constants.managed_node_tree_in_use() is True-- def test_unrelated_process_does_not_count(self, tmp_path, monkeypatch):- home = tmp_path / "hermes"- (home / "node").mkdir(parents=True)- monkeypatch.setenv("HERMES_HOME", str(home))- self._install_fake_psutil(- monkeypatch,- [{"exe": r"C:\Program Files\nodejs\node.exe", "cmdline": None}],- )- assert hermes_constants.managed_node_tree_in_use() is False-- def test_missing_psutil_is_false(self, tmp_path, monkeypatch):- import sys-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- # None in sys.modules makes `import psutil` raise ImportError.- monkeypatch.setitem(sys.modules, "psutil", None)- assert hermes_constants.managed_node_tree_in_use() is False--[email protected]_only-def test_managed_node_tree_never_in_use_off_windows(tmp_path, monkeypatch):- """The psutil scan is Windows-only; POSIX hosts can swap the tree freely."""- (tmp_path / "node").mkdir()- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- assert hermes_constants.managed_node_tree_in_use() is False---class _FakeUrlResponse:- def __init__(self, payload: bytes):- self._payload = payload-- def __enter__(self):- return self-- def __exit__(self, *exc):- return False-- def read(self):- return self._payload---def _make_node_zip(major: int) -> tuple[str, bytes]:- import io- import zipfile-- name = f"node-v{major}.5.1-win-x64.zip"- buf = io.BytesIO()- with zipfile.ZipFile(buf, "w") as archive:- root = f"node-v{major}.5.1-win-x64"- archive.writestr(f"{root}/node.exe", b"fake-node")- archive.writestr(f"{root}/npm.cmd", "@echo off\r\n")- return name, buf.getvalue()--[email protected]_only-class TestWindowsHealStageSwap:- """_heal_managed_node_windows() must never destroy the live tree before- its replacement is fully staged, and must defer (return None) when the- tree is in use instead of forcing the write (#80926)."""-- def _stub_env(- self, monkeypatch, home, zip_name, zip_bytes, *, in_use=False- ):- import urllib.request-- # Pin the native architecture to the x64 archive served by the fake index.- monkeypatch.setattr(host_facts, "native_arch", lambda: "amd64")- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setenv(- "HERMES_NODE_TARGET_MAJOR",- str(hermes_constants._HERMES_NODE_TARGET_MAJOR),- )- monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)- monkeypatch.setattr(- hermes_constants, "_managed_node_in_use_notice_printed", False- )- monkeypatch.setattr(- hermes_constants,- "managed_node_tree_in_use",- lambda _home=None: in_use,- )- monkeypatch.setattr(- hermes_constants, "node_tool_runnable", lambda path: True- )-- index_html = f'<a href="./{zip_name}">{zip_name}</a>'.encode()-- def fake_urlopen(url, timeout=0):- if str(url).endswith(".zip"):- return _FakeUrlResponse(zip_bytes)- return _FakeUrlResponse(index_html)-- monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)-- def test_in_use_defers_without_touching_tree(self, tmp_path, monkeypatch):- import urllib.request-- home = tmp_path / "hermes"- old = home / "node"- old.mkdir(parents=True)- (old / "node.exe").write_text("old", encoding="utf-8")- (old / "npm.cmd").write_text("@echo off", encoding="utf-8")- zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)- self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=True)-- def forbidden_urlopen(url, timeout=0):- raise AssertionError(f"no download may start while the tree is in use: {url}")-- monkeypatch.setattr(urllib.request, "urlopen", forbidden_urlopen)-- result = hermes_constants._heal_managed_node_windows()-- assert result is None- # The live tree is untouched, and no staging litter remains.- assert (old / "node.exe").read_text(encoding="utf-8") == "old"- assert list(home.glob("node.new-*")) == []- assert list(home.glob("node.old-*")) == []-- def test_swap_replaces_tree_and_cleans_up(self, tmp_path, monkeypatch):- home = tmp_path / "hermes"- old = home / "node"- old.mkdir(parents=True)- (old / "node.exe").write_text("old", encoding="utf-8")- (old / "old-marker").write_text("stale", encoding="utf-8")- zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)- self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)-- result = hermes_constants._heal_managed_node_windows()-- assert result is True- assert (home / "node" / "node.exe").exists()- assert not (home / "node" / "old-marker").exists()- assert list(home.glob("node.new-*")) == []- assert list(home.glob("node.old-*")) == []-- def test_creates_tree_when_absent(self, tmp_path, monkeypatch):- home = tmp_path / "hermes"- home.mkdir()- zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)- self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)-- result = hermes_constants._heal_managed_node_windows()-- assert result is True- assert (home / "node" / "node.exe").exists()- assert list(home.glob("node.new-*")) == []-- def test_rename_refusal_defers_and_preserves_tree(self, tmp_path, monkeypatch):- import os as _os-- home = tmp_path / "hermes"- old = home / "node"- old.mkdir(parents=True)- (old / "node.exe").write_text("old", encoding="utf-8")- zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)- self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)-- real_replace = _os.replace- state = {"calls": 0}-- def flaky_replace(src, dst):- state["calls"] += 1- if state["calls"] == 1:- raise PermissionError(13, "Access is denied", str(src))- return real_replace(src, dst)-- monkeypatch.setattr(_os, "replace", flaky_replace)-- result = hermes_constants._heal_managed_node_windows()-- assert result is None- # The OS refused the swap — the live tree must survive intact.- assert (old / "node.exe").read_text(encoding="utf-8") == "old"- assert list(home.glob("node.new-*")) == []- assert list(home.glob("node.old-*")) == []--- def test_touch_failure_does_not_abort_swap(self, tmp_path, monkeypatch):- """The post-rename mtime touch is best-effort: a touch failure must- not abort a swap that already succeeded."""- import os as _os-- home = tmp_path / "hermes"- old = home / "node"- old.mkdir(parents=True)- (old / "node.exe").write_text("old", encoding="utf-8")- zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)- self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)-- calls = {"n": 0}-- def failing_utime(path, times=None):- calls["n"] += 1- raise PermissionError(13, "Access is denied", str(path))-- monkeypatch.setattr(_os, "utime", failing_utime)- result = hermes_constants._heal_managed_node_windows()-- assert result is True- assert calls["n"] >= 1- # The new tree is in place despite the touch failure.- assert (home / "node" / "node.exe").exists()- assert list(home.glob("node.new-*")) == []- # The old tree was swapped aside and then removed.- assert list(home.glob("node.old-*")) == []-- def test_second_rename_failure_rolls_back(self, tmp_path, monkeypatch):- """The staged->live rename failing must restore the live tree and- remove the staged copy, reporting a genuine failure (not a deferral)."""- import os as _os-- home = tmp_path / "hermes"- old = home / "node"- old.mkdir(parents=True)- (old / "node.exe").write_text("old", encoding="utf-8")- zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)- self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)-- real_replace = _os.replace- state = {"calls": 0}-- def flaky_replace(src, dst):- state["calls"] += 1- if state["calls"] == 2:- raise PermissionError(13, "Access is denied", str(src))- return real_replace(src, dst)-- monkeypatch.setattr(_os, "replace", flaky_replace)-- result = hermes_constants._heal_managed_node_windows()-- assert result is False- # The live tree was rolled back into place; the staged copy is gone.- assert (old / "node.exe").read_text(encoding="utf-8") == "old"- assert list(home.glob("node.new-*")) == []- assert list(home.glob("node.old-*")) == []-- def test_stale_staging_litter_is_swept(self, tmp_path, monkeypatch):- import os as _os- import time as _time-- home = tmp_path / "hermes"- (home / "node").mkdir(parents=True)- (home / "node" / "node.exe").write_text("old", encoding="utf-8")- stale_backup = home / "node.old-deadbeef"- stale_backup.mkdir()- (stale_backup / "node.exe").write_text("stale", encoding="utf-8")- stale_staged = home / "node.new-deadbeef"- stale_staged.mkdir()- (stale_staged / "node.exe").write_text("stale", encoding="utf-8")- # The sweep only removes litter older than 10 minutes, so backdate.- old_ts = _time.time() - 3600- _os.utime(stale_backup, (old_ts, old_ts))- _os.utime(stale_staged, (old_ts, old_ts))- zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)- self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)-- result = hermes_constants._heal_managed_node_windows()-- assert result is True- assert not stale_backup.exists()- assert not stale_staged.exists()- assert (home / "node" / "node.exe").exists()-- def test_fresh_staging_dirs_are_not_swept(self, tmp_path, monkeypatch):- """A concurrent heal's in-flight backup must survive the sweep even- when it was renamed from a long-lived tree (rename preserves mtime —- the production code touches it after the rename, and the sweep must- respect that)."""- import os as _os- import time as _time-- home = tmp_path / "hermes"- (home / "node").mkdir(parents=True)- (home / "node" / "node.exe").write_text("old", encoding="utf-8")- # Simulate a long-lived tree being renamed aside mid-swap: backdate- # it, rename, then touch exactly like the production swap does.- old_ts = _time.time() - 3600- _os.utime(home / "node", (old_ts, old_ts))- fresh_backup = home / "node.old-deadbeef"- _os.replace(str(home / "node"), str(fresh_backup))- _os.utime(fresh_backup, None)- zip_name, zip_bytes = _make_node_zip(hermes_constants._HERMES_NODE_TARGET_MAJOR)- self._stub_env(monkeypatch, home, zip_name, zip_bytes, in_use=False)-- result = hermes_constants._heal_managed_node_windows()-- assert result is True- assert fresh_backup.exists()--[email protected]_only-class TestHealAttemptFlagSemantics:- """An in-use deferral must not record the once-per-process heal attempt,- so a later call can retry once the tree is free (#80926)."""-- def test_deferral_keeps_flag_clear_and_retries(self, tmp_path, monkeypatch):- home = tmp_path / "hermes"- (home / "node").mkdir(parents=True)- (home / "node" / "node.exe").write_text("x", encoding="utf-8")- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)- calls = {"n": 0}-- def fake_heal():- calls["n"] += 1- return None-- monkeypatch.setattr(hermes_constants, "_heal_managed_node_windows", fake_heal)-- assert heal_hermes_managed_node() is False- assert hermes_constants._managed_node_heal_attempted is False- # The flag stayed clear, so the next call retries the heal.- assert heal_hermes_managed_node() is False- assert calls["n"] == 2-- def test_real_failure_records_attempt(self, tmp_path, monkeypatch):- home = tmp_path / "hermes"- (home / "node").mkdir(parents=True)- (home / "node" / "node.exe").write_text("x", encoding="utf-8")- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setattr(hermes_constants, "_managed_node_heal_attempted", False)- calls = {"n": 0}-- def fake_heal():- calls["n"] += 1- return False-- monkeypatch.setattr(hermes_constants, "_heal_managed_node_windows", fake_heal)- assert heal_hermes_managed_node() is False- assert hermes_constants._managed_node_heal_attempted is True- # The flag is set, so the once-per-process budget is spent.- assert heal_hermes_managed_node() is False- assert calls["n"] == 1class TestProjectVenvDirOutOfTree:"""#116148: a checkout with no in-tree venv whose interpreter lives in ``$HERMES_HOME/venvs/<name>``diff --git a/tests/tools/test_clipboard.py b/tests/tools/test_clipboard.pyindex 155c3d19def..271ad882392 100644--- a/tests/tools/test_clipboard.py+++ b/tests/tools/test_clipboard.py@@ -403,7 +403,7 @@ class TestHasClipboardImage:def setup_method(self):host_runtime._wsl_detected = None- @pytest.mark.macos_only+ @pytest.mark.platforms("macos")def test_macos_dispatch(self):"""Faking darwin selected the branch but left `_macos_has_image`'s realfacility (osascript) absent — only a real macOS host has it."""@@ -411,7 +411,7 @@ class TestHasClipboardImage:assert has_clipboard_image() is Truem.assert_called_once()- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_wsl_falls_through_to_wayland_when_windows_path_empty(self):"""WSLg often bridges images to wl-paste even when powershell.exe check fails.diff --git a/tests/tools/test_computer_use_cua_0_10_permissions.py b/tests/tools/test_computer_use_cua_0_10_permissions.pyindex fe75f9c83bc..9df9e561604 100644--- a/tests/tools/test_computer_use_cua_0_10_permissions.py+++ b/tests/tools/test_computer_use_cua_0_10_permissions.py@@ -136,7 +136,7 @@ def test_mode_change_is_rechecked_after_stale_backend_stops():][email protected]_only[email protected]("linux")def test_unrestricted_embedded_daemon_uses_private_socket_and_two_part_ack():from tools.computer_use import cua_backenddiff --git a/tests/tools/test_computer_use_native_platform.py b/tests/tools/test_computer_use_native_platform.pyindex 194e006b2f3..37a6fcd6805 100644--- a/tests/tools/test_computer_use_native_platform.py+++ b/tests/tools/test_computer_use_native_platform.py@@ -21,8 +21,8 @@ def backend(monkeypatch):@pytest.mark.parametrize("host_platform", [- pytest.param("win32", marks=pytest.mark.windows_only),- pytest.param("darwin", marks=pytest.mark.macos_only),+ pytest.param("win32", marks=pytest.mark.platforms("windows")),+ pytest.param("darwin", marks=pytest.mark.platforms("macos")),])@pytest.mark.parametrize("args, expected_call", [({"action": "capture", "mode": "ax"}, "capture"),diff --git a/tests/tools/test_file_operations.py b/tests/tools/test_file_operations.pyindex 1e73a978dd8..3ed3936730d 100644--- a/tests/tools/test_file_operations.py+++ b/tests/tools/test_file_operations.py@@ -248,7 +248,7 @@ class TestShellFileOpsHelpers:- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_escape_shell_arg_rewrites_forward_slash_native_paths(self, file_ops):"""Windows-only: ``_bash_safe_path`` only rewrites drive paths to theGit Bash form on Windows, where the MSYS path mangling it works around@@ -751,19 +751,19 @@ class TestEscapeNativeToolArg:def _ops(self, mock_env):return ShellFileOperations(mock_env)- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_windows_native_path_kept_native(self, mock_env):ops = self._ops(mock_env)out = ops._escape_native_tool_arg(r"C:\Users\alice\project")assert out == "'C:/Users/alice/project'"- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_msys_path_translated_back_to_native(self, mock_env):ops = self._ops(mock_env)out = ops._escape_native_tool_arg("/c/Users/alice/project")assert out == "'C:/Users/alice/project'"- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_posix_path_untouched_on_windows(self, mock_env):"""Multi-segment POSIX paths (/home/x, /tmp/y) are not drive paths."""ops = self._ops(mock_env)diff --git a/tests/tools/test_file_tools.py b/tests/tools/test_file_tools.pyindex 9cbd07912f6..0662e2a1663 100644--- a/tests/tools/test_file_tools.py+++ b/tests/tools/test_file_tools.py@@ -251,7 +251,7 @@ class TestSearchHandler:class TestWindowsMsysPathResolution:"""File tools must translate Git Bash drive paths before Path resolution."""- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_absolute_msys_path_normalized_before_windows_resolve(self, monkeypatch):"""Windows-only: ``_resolve_path_for_task`` hands the translated pathto ``ntpath``/``Path``, and only a real Windows ``Path`` renders@@ -264,7 +264,7 @@ class TestWindowsMsysPathResolution:assert str(resolved) == r"C:\Users\Mark\project\app.py"- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_container_paths_skip_msys_translation(self, monkeypatch):"""WSL/docker Linux paths must not be rewritten as Windows drives.diff --git a/tests/tools/test_macos_protected_search.py b/tests/tools/test_macos_protected_search.pyindex dc1a897638d..fff6fffc151 100644--- a/tests/tools/test_macos_protected_search.py+++ b/tests/tools/test_macos_protected_search.py@@ -69,7 +69,7 @@ def test_non_macos_search_has_no_implicit_exclusions(tmp_path):assert exclusions == [][email protected]_only[email protected]("macos")def test_grep_pruned_search_still_finds_nested_protected_names(tmp_path, monkeypatch):"""A repo-internal directory literally named 'Downloads' must still besearched by the pruned grep path — the exact regression --exclude-dir had."""@@ -91,7 +91,7 @@ def test_grep_pruned_search_still_finds_nested_protected_names(tmp_path, monkeypassert not any(str(protected / "secret.txt") in p for p in matched_paths)[email protected]_only[email protected]("macos")def test_remote_backend_never_prunes(tmp_path, monkeypatch):"""Non-local environments get no exclusions: platform facts describe thecontroller, not the execution host (macOS controller + Linux SSH backend@@ -110,7 +110,7 @@ def test_remote_backend_never_prunes(tmp_path, monkeypatch):assert result.warning is None[email protected]_only[email protected]("macos")def test_rg_multi_root_scopes_protected_globs_and_restores_absolute_paths(monkeypatch):env = RecordingEnvironment("/")ops = ShellFileOperations(env)@@ -151,7 +151,7 @@ def test_rg_multi_root_scopes_protected_globs_and_restores_absolute_paths(monkey][email protected]_only[email protected]("macos")def test_rg_scoped_multi_root_terminates_options_before_dash_prefixed_root(monkeypatch):env = RecordingEnvironment("/Users/alice")ops = ShellFileOperations(env)@@ -177,7 +177,7 @@ def test_rg_scoped_multi_root_terminates_options_before_dash_prefixed_root(monkeassert result.error is None[email protected]_only[email protected]("macos")def test_real_ripgrep_does_not_descend_into_protected_folder(tmp_path, monkeypatch):home = tmp_path / "Users" / "alice"safe = home / "safe"diff --git a/tests/tools/test_process_registry.py b/tests/tools/test_process_registry.pyindex 1b4fad80875..68ec0e9a833 100644--- a/tests/tools/test_process_registry.py+++ b/tests/tools/test_process_registry.py@@ -120,7 +120,7 @@ def _wait_until(predicate, timeout: float = 5.0, interval: float = 0.05) -> boolreturn False[email protected]_only[email protected]("windows")def test_write_stdin_uses_str_for_windows_pty(registry):"""pywinpty expects str input; bytes raises a PyString conversion error.@@ -144,7 +144,7 @@ def test_write_stdin_uses_str_for_windows_pty(registry):assert isinstance(written[0], str)[email protected]_only[email protected]("linux")def test_write_stdin_uses_bytes_for_posix_pty(registry):"""The POSIX counterpart: ptyprocess expects bytes, not str."""written = []@@ -163,7 +163,7 @@ def test_write_stdin_uses_bytes_for_posix_pty(registry):assert written == [b"hello\n"][email protected]_only[email protected]("windows")def test_submit_stdin_uses_crlf_for_windows_pty(registry):"""Enter on a Windows PTY is a carriage return, not a bare LF.@@ -189,7 +189,7 @@ def test_submit_stdin_uses_crlf_for_windows_pty(registry):assert written == ["Y\r\n"][email protected]_only[email protected]("windows")def test_submit_stdin_keeps_lf_for_windows_pipe(registry):"""Non-PTY (Popen pipe) sessions keep the plain LF on Windows."""session = _make_session(sid="pipe-win-submit")@@ -617,8 +617,9 @@ class TestStdinHelpers:lockout (#17959). For interactive stdin → PTY mode is now the onlysupported path."""+ command = f'{shlex.quote(sys.executable)} -c "import sys; print(sys.stdin.read().strip())"'session = registry.spawn_local(- 'python3 -c "import sys; print(sys.stdin.read().strip())"',+ command,cwd=str(tmp_path),use_pty=True,)@@ -1584,7 +1585,7 @@ class TestTerminateHostPidWindows:target handle only, not the tree."""- @pytest.mark.windows_only+ @pytest.mark.platforms("windows")def test_windows_invokes_taskkill_with_tree_and_force_flags(self, monkeypatch):"""The Windows branch must shell out to ``taskkill /PID N /T /F``.@@ -1669,11 +1670,11 @@ class TestTerminateHostPidPosix:# Child logs a registry-delivered TERM; the parent kills it with KILL# (logs nothing) and reaps it, then exits 0 — like a browser reaping its zygote.child_sh.write_text(- "#!/bin/bash\n"+ "#!/usr/bin/env bash\n"f"trap 'echo child-TERM >> {log}; exit 0' TERM\n"f"echo up >> {log}\nwhile :; do sleep 0.1; done\n")parent_sh.write_text(- "#!/bin/bash\n"+ "#!/usr/bin/env bash\n"f"bash {child_sh} & kid=$!\n"f"trap 'echo parent-TERM >> {log}; kill -KILL $kid; wait $kid; exit 0' TERM\n""while :; do sleep 0.1; done\n")@@ -2156,7 +2157,7 @@ class TestSystemdCgroupIsolation:return fake_popen, captured- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_wraps_in_systemd_scope_when_supervisor_and_available(self, registry, monkeypatch, _gateway_identity):@@ -2374,7 +2375,7 @@ class TestSystemdCgroupIsolation:assert session.systemd_unit == ""- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_systemd_post_spawn_failure_never_kills_gateway_process_group(self, registry, monkeypatch, _gateway_identity):@@ -2409,7 +2410,7 @@ class TestSystemdCgroupIsolation:assert stop_unit.call_args.args[0].endswith(".scope")killpg.assert_not_called()- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_pty_spawn_is_wrapped_in_systemd_scope(self, registry, monkeypatch, _gateway_identity):"""Interactive executors receive the same sibling-cgroup isolation."""from ptyprocess import PtyProcess@@ -2441,7 +2442,7 @@ class TestSystemdCgroupIsolation:assert argv[-3:] == ["/bin/bash", "-lic", "set +m; codex"]assert session.systemd_unit == f"hermes-worker-{session.id}.scope"- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_pty_spawn_failure_reaps_scope_before_distinct_pipe_fallback(self, registry, monkeypatch, _gateway_identity):@@ -2497,7 +2498,7 @@ class TestSystemdCgroupIsolation:f"hermes-worker-{session.id}-pipe-fallback.scope")- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_pty_spawn_failure_does_not_fallback_when_scope_reap_fails(self, registry, monkeypatch, _gateway_identity):@@ -2590,7 +2591,7 @@ class TestSystemdCgroupIsolation:assert session.id in registry._finishedassert session.id not in registry._running- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_systemd_run_user_scope_available_caches_after_probe(self, registry, monkeypatch):@@ -2621,7 +2622,7 @@ class TestSystemdCgroupIsolation:value.startswith("OOMPolicy=") for value in probe_argv if isinstance(value, str)), probe_argv- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_successful_systemd_probe_revalidates_after_cache_ttl(self, monkeypatch):"""A vanished user bus invalidates a formerly successful scope verdict."""import tools.process_registry as pr@@ -2647,7 +2648,7 @@ class TestSystemdCgroupIsolation:assert pr._systemd_run_user_scope_available() is Falseassert len(probe_calls) == 2- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_systemd_probe_derives_owned_user_bus_env_for_system_gateway(self, registry, monkeypatch, request):@@ -2696,7 +2697,7 @@ class TestSystemdCgroupIsolation:assert "XDG_RUNTIME_DIR" not in os.environassert "DBUS_SESSION_BUS_ADDRESS" not in os.environ- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_scoped_spawn_lost_user_bus_honours_configured_runtime_dir(self, monkeypatch, request):"""The lost-bus check must derive from the env the worker was spawned with: when the buslives under a configured ``XDG_RUNTIME_DIR`` (not ``/run/user/<uid>``), an unrelated wrapper@@ -2734,7 +2735,7 @@ class TestSystemdCgroupIsolation:assert pr.scoped_spawn_lost_user_bus(spawn_env) is Trueassert pr._SYSTEMD_SCOPE_AVAILABLE is False- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_probe_succeeds_without_bin_true(self, monkeypatch):"""An absent ``/bin/true`` must not make a usable scope fail its probe."""import tools.process_registry as pr@@ -2758,7 +2759,7 @@ class TestSystemdCgroupIsolation:assert pr._systemd_run_user_scope_available() is Trueassert len(executed) == 1, "payload must really run (exit 0) on the host, not just be spelled right"- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_systemd_scope_first_probe_is_serialized(self, monkeypatch):"""Concurrent first-use callers must wait for one definitive probe.@@ -2806,7 +2807,7 @@ class TestSystemdCgroupIsolation:assert results == [True, True]assert len(probe_calls) == 1- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_failed_systemd_probe_retries_after_cache_ttl(self, monkeypatch):import tools.process_registry as prdiff --git a/ui-tui/src/__tests__/textInputFastEcho.test.ts b/ui-tui/src/__tests__/textInputFastEcho.test.tsindex 4bc00f35ae0..ab4a31933f6 100644--- a/ui-tui/src/__tests__/textInputFastEcho.test.ts+++ b/ui-tui/src/__tests__/textInputFastEcho.test.ts@@ -204,6 +204,16 @@ describe('supportsFastEchoTerminal', () => {expect(supportsFastEchoTerminal({ TMUX: '/private/tmp/tmux-501/default' } as NodeJS.ProcessEnv)).toBe(false)})+ it('tmux wins over Termux fast-echo opt-in', () => {+ expect(+ supportsFastEchoTerminal({+ TMUX: '/tmp/tmux-1000/default,1234,0',+ HERMES_TUI_TERMUX_FAST_ECHO: '1',+ TERMUX_VERSION: '0.118.0'+ })+ ).toBe(false)+ })+it('keeps fast-echo enabled when TMUX is empty or unset', () => {expect(supportsFastEchoTerminal({ TMUX: '' } as NodeJS.ProcessEnv)).toBe(true)expect(supportsFastEchoTerminal({ TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv)).toBe(true)@@ -226,6 +236,24 @@ describe('supportsFastEchoTerminal', () => {expect(supportsFastEchoTerminal({ TERM: 'xterm-256color' } as NodeJS.ProcessEnv)).toBe(true)})+ it('disables fast-echo by default in Termux mode', () => {+ expect(+ supportsFastEchoTerminal({+ TERMUX_VERSION: '0.118.0',+ PREFIX: '/data/data/com.termux/files/usr'+ })+ ).toBe(false)+ })++ it('allows explicit Termux fast-echo opt-in via env override', () => {+ expect(+ supportsFastEchoTerminal({+ HERMES_TUI_TERMUX_FAST_ECHO: '1',+ TERMUX_VERSION: '0.118.0'+ })+ ).toBe(true)+ })+it('keeps fast-echo enabled in VS Code and unknown terminals', () => {expect(supportsFastEchoTerminal({ TERM_PROGRAM: 'vscode' } as NodeJS.ProcessEnv)).toBe(true)expect(supportsFastEchoTerminal({ TERM: 'xterm-256color' } as NodeJS.ProcessEnv)).toBe(true)diff --git a/ui-tui/src/components/appLayout.tsx b/ui-tui/src/components/appLayout.tsxindex d46008ea799..276c794965d 100644--- a/ui-tui/src/components/appLayout.tsx+++ b/ui-tui/src/components/appLayout.tsx@@ -11,7 +11,7 @@ import { $isBlocked, $overlayState, patchOverlayState } from '../app/overlayStorimport { $petBox } from '../app/petFlashStore.js'import { $uiState } from '../app/uiStore.js'import { usePet } from '../app/usePet.js'-import { INLINE_MODE, SHOW_FPS } from '../config/env.js'+import { INLINE_MODE, SHOW_FPS, TERMUX_TUI_MODE } from '../config/env.js'import { PLACEHOLDER } from '../content/placeholders.js'import { prevRenderedMsg } from '../domain/blockLayout.js'import {@@ -284,11 +284,17 @@ const ComposerPane = memo(function ComposerPane({const isBlocked = useStore($isBlocked)const sh = (composer.inputBuf[0] ?? composer.input).startsWith('!')- const promptText = composerPromptText(ui.theme.brand.prompt, ui.info?.profile_name, sh)+ const promptText = composerPromptText(+ ui.theme.brand.prompt,+ ui.info?.profile_name,+ sh,+ TERMUX_TUI_MODE,+ composer.cols+ )const promptWidth = composerPromptWidth(promptText)const promptBlank = ' '.repeat(promptWidth)- const inputColumns = stableComposerColumns(composer.cols, promptWidth)+ const inputColumns = stableComposerColumns(composer.cols, promptWidth, TERMUX_TUI_MODE)const inputHeight = inputVisualHeight(composer.input, inputColumns)const inputMouseRef = useRef<null | TextInputMouseApi>(null)diff --git a/ui-tui/src/components/messageLine.tsx b/ui-tui/src/components/messageLine.tsxindex 12b4d207499..fb64a9d6929 100644--- a/ui-tui/src/components/messageLine.tsx+++ b/ui-tui/src/components/messageLine.tsx@@ -2,6 +2,7 @@ import { Ansi, Box, NoSelect, Text } from '@hermes/ink'import { hasAnsi, sanitizeAnsiForRender, stripAnsi } from '@hermes/shared/ansi'import { memo, useState } from 'react'+import { TERMUX_TUI_MODE } from '../config/env.js'import { LONG_MSG } from '../config/limits.js'import { hasLeadGap } from '../domain/blockLayout.js'import { splitComposerHighlights } from '../domain/composerHighlights.js'@@ -197,7 +198,7 @@ export const MessageLine = memo(function MessageLine({}if (msg.role === 'assistant') {- const bodyWidth = transcriptBodyWidth(cols, msg.role, t.brand.prompt)+ const bodyWidth = transcriptBodyWidth(cols, msg.role, t.brand.prompt, TERMUX_TUI_MODE)return isStreaming ? (// Incremental markdown: split at the last stable block boundary so@@ -310,7 +311,7 @@ export const MessageLine = memo(function MessageLine({</Text></NoSelect>- <Box width={transcriptBodyWidth(cols, msg.role, t.brand.prompt)}>{content}</Box>+ <Box width={transcriptBodyWidth(cols, msg.role, t.brand.prompt, TERMUX_TUI_MODE)}>{content}</Box></Box></Box>)diff --git a/ui-tui/src/components/textInput.tsx b/ui-tui/src/components/textInput.tsxindex e6907b2ec41..172795a4f66 100644--- a/ui-tui/src/components/textInput.tsx+++ b/ui-tui/src/components/textInput.tsx@@ -14,6 +14,7 @@ import {isVoiceToggleKey,type ParsedVoiceRecordKey} from '../lib/platform.js'+import { isTermuxTuiMode } from '../lib/termux.js'type InkExt = typeof Ink & {colorize: (str: string, color: string | undefined, type: 'foreground' | 'background') => string@@ -664,6 +665,21 @@ export function supportsFastEchoTerminal(env: NodeJS.ProcessEnv = process.env):return false}+ // Termux terminals are especially sensitive to bypass-path cursor drift and+ // stale paints at soft-wrap boundaries on tall/narrow viewports. Keep this+ // off by default in Termux mode; allow explicit opt-in for local debugging.+ if (isTermuxTuiMode(env)) {+ const override = String(env.HERMES_TUI_TERMUX_FAST_ECHO ?? '')+ .trim()+ .toLowerCase()++ if (override) {+ return /^(?:1|true|yes|on)$/i.test(override)+ }++ return false+ }+return true}diff --git a/ui-tui/src/config/env.ts b/ui-tui/src/config/env.tsindex 591c5fce7f5..90c2f168667 100644--- a/ui-tui/src/config/env.ts+++ b/ui-tui/src/config/env.ts@@ -1,5 +1,7 @@import type { MouseTrackingMode } from '@hermes/ink'+import { isTermuxTuiMode } from '../lib/termux.js'+const truthy = (v?: string) => /^(?:1|true|yes|on)$/i.test((v ?? '').trim())const falsy = (v?: string) => /^(?:0|false|no|off)$/i.test((v ?? '').trim())@@ -21,6 +23,8 @@ const parseToggle = (v?: string): boolean | null => {return null}+export const TERMUX_TUI_MODE: boolean = isTermuxTuiMode()+export const STARTUP_RESUME_ID = (process.env.HERMES_TUI_RESUME ?? '').trim()export const STARTUP_QUERY = (process.env.HERMES_TUI_QUERY ?? '').trim()export const STARTUP_IMAGE = (process.env.HERMES_TUI_IMAGE ?? '').trim()@@ -36,13 +40,15 @@ export const STARTUP_WORKSPACE_CWD = (process.env.HERMES_TUI_CWD ?? '').trim()//// - HERMES_TUI_MOUSE_TRACKING (truthy/falsy) explicitly overrides everything.// This is the "force a value" knob and intentionally beats the legacy-// kill-switch.+// kill-switch and the Termux default.// - HERMES_TUI_DISABLE_MOUSE=1 forces mouse off — the legacy kill switch.-// - Otherwise mouse tracking defaults to 'all'.+// - On Termux the default is mouse off so touch selection isn't intercepted+// by terminal mouse protocols. Desktop defaults to 'all' to preserve prior+// behavior.const mouseTrackingOverride = parseToggle(process.env.HERMES_TUI_MOUSE_TRACKING)const mouseTrackingDisabledLegacy = truthy(process.env.HERMES_TUI_DISABLE_MOUSE)-const resolvedBootMouseEnabled = mouseTrackingOverride ?? !mouseTrackingDisabledLegacy+const resolvedBootMouseEnabled = mouseTrackingOverride ?? (TERMUX_TUI_MODE ? false : !mouseTrackingDisabledLegacy)export const MOUSE_TRACKING: MouseTrackingMode = resolvedBootMouseEnabled ? 'all' : 'off'@@ -61,8 +67,11 @@ const inlineOverride = parseToggle(process.env.HERMES_TUI_INLINE)// Skip AlternateScreen — TUI renders into the primary buffer so the host// terminal's native scrollback captures whatever scrolls off the top.-// Off by default; opt in with HERMES_TUI_INLINE=1.-export const INLINE_MODE = inlineOverride ?? false+//+// On Termux we default this on: users often background/foreground the app,+// and primary-buffer rendering makes long-thread review and copy/paste much+// less fragile. Override explicitly with HERMES_TUI_INLINE=0/1.+export const INLINE_MODE: boolean = inlineOverride ?? TERMUX_TUI_MODE// Live FPS counter overlay, fed by ink's onFrame (real render rate, not a// synthetic timer).diff --git a/ui-tui/src/entry.tsx b/ui-tui/src/entry.tsxindex 8b699f22874..79bc67daf58 100644--- a/ui-tui/src/entry.tsx+++ b/ui-tui/src/entry.tsx@@ -6,7 +6,7 @@ import './lib/forceTruecolor.js'import type { FrameEvent } from '@hermes/ink'import { setRpcErrorLogSink } from './app/userMessages.js'-import { DASHBOARD_TUI_MODE } from './config/env.js'+import { DASHBOARD_TUI_MODE, TERMUX_TUI_MODE } from './config/env.js'import { GatewayClient } from './gatewayClient.js'import { setupGracefulExit } from './lib/gracefulExit.js'import { formatBytes, type HeapDumpResult, performHeapDump } from './lib/memory.js'@@ -40,9 +40,14 @@ process.on('exit', () => {resetTerminalModes()})-// Terminals benefit from a clean startup slate because the TUI usually runs-// in AlternateScreen.-process.stdout.write('\x1b[2J\x1b[H\x1b[3J')+// Desktop terminals benefit from a clean startup slate because the TUI usually+// runs in AlternateScreen. On Termux we keep prior output intact so users can+// review/copy earlier assistant replies after reopening the app.+if (TERMUX_TUI_MODE) {+ process.stdout.write('\n')+} else {+ process.stdout.write('\x1b[2J\x1b[H\x1b[3J')+}const gw = new GatewayClient()diff --git a/ui-tui/src/lib/inputMetrics.ts b/ui-tui/src/lib/inputMetrics.tsindex 08d51e2de75..cf5df27c63a 100644--- a/ui-tui/src/lib/inputMetrics.ts+++ b/ui-tui/src/lib/inputMetrics.ts@@ -178,19 +178,26 @@ export function transcriptGutterWidth(role: Role, userPrompt: string) {return role === 'user' ? composerPromptWidth(userPrompt) : 3}-export function transcriptBodyWidth(totalCols: number, role: Role, userPrompt: string) {- const available = Math.max(1, totalCols - transcriptGutterWidth(role, userPrompt) - 4)+export function transcriptBodyWidth(totalCols: number, role: Role, userPrompt: string, termuxMode = false): number {+ const horizontalReserve = termuxMode ? 2 : 4+ const available = Math.max(1, totalCols - transcriptGutterWidth(role, userPrompt) - horizontalReserve)++ if (termuxMode) {+ // On narrow / unusual aspect-ratio mobile panes, forcing a wide minimum+ // width causes right-edge clipping and chopped words.+ return available+ }return Math.max(20, available)}-export function stableComposerColumns(totalCols: number, promptWidth: number) {+export function stableComposerColumns(totalCols: number, promptWidth: number, termuxMode = false): number {// Physical render/wrap width. Always reserve outer composer padding and// prompt prefix. Only reserve the transcript scrollbar gutter when the// terminal is wide enough; on narrow panes, preserving input columns beats// keeping gutters visually aligned.const afterPrompt = totalCols - promptWidth- const reserveScrollbar = afterPrompt >= 24 ? 2 : 0+ const reserveScrollbar = afterPrompt >= (termuxMode ? 36 : 24) ? 2 : 0return Math.max(1, totalCols - promptWidth - 2 - reserveScrollbar)}diff --git a/ui-tui/src/lib/prompt.ts b/ui-tui/src/lib/prompt.tsindex aaf3559dc82..491d0e4c4d7 100644--- a/ui-tui/src/lib/prompt.ts+++ b/ui-tui/src/lib/prompt.ts@@ -1,12 +1,33 @@+const TERMUX_SAFE_PROMPT: string = '>'+export function composerPromptText(prompt: string,profileName?: null | string,- shellMode = false+ shellMode = false,+ termuxMode = false,+ totalCols?: number): string {if (shellMode) {return '$'}+ if (termuxMode) {+ // Termux fonts/terminal backends can render decorative prompt glyphs with+ // ambiguous width; keep the live composer marker strictly single-cell ASCII+ // so we never leave stale arrow artifacts while typing.+ const basePrompt = TERMUX_SAFE_PROMPT++ // On very wide panes we can still include profile context. On narrow/mobile+ // panes this burns precious columns and increases wrap/clipping risk.+ const wideEnoughForProfile = (totalCols ?? 0) >= 90++ if (wideEnoughForProfile && profileName && !['default', 'custom'].includes(profileName)) {+ return `${profileName} ${basePrompt}`+ }++ return basePrompt+ }+if (profileName && !['default', 'custom'].includes(profileName)) {return `${profileName} ${prompt}`}diff --git a/ui-tui/src/lib/termux.ts b/ui-tui/src/lib/termux.tsnew file mode 100644index 00000000000..c2cfe915c13--- /dev/null+++ b/ui-tui/src/lib/termux.ts@@ -0,0 +1,31 @@+const TERMUX_PREFIX = '/data/data/com.termux/files/usr'++const truthy = (value?: string): boolean => /^(?:1|true|yes|on)$/i.test(String(value ?? '').trim())++export const isTermuxEnv = (env: NodeJS.ProcessEnv = process.env): boolean => {+ const prefix = String(env.PREFIX ?? '')++ return Boolean(env.TERMUX_VERSION) || prefix.includes(TERMUX_PREFIX)+}++/**+ * Return true when Hermes should enable Termux-focused TUI defaults.+ *+ * Defaults to on in Termux, with an explicit opt-out for debugging:+ * HERMES_TUI_TERMUX_MODE=0+ */+export const isTermuxTuiMode = (env: NodeJS.ProcessEnv = process.env): boolean => {+ if (!isTermuxEnv(env)) {+ return false+ }++ const override = String(env.HERMES_TUI_TERMUX_MODE ?? '')+ .trim()+ .toLowerCase()++ if (override) {+ return truthy(override)+ }++ return true+}\ No newline at end of filediff --git a/ui-tui/src/lib/virtualHeights.ts b/ui-tui/src/lib/virtualHeights.tsindex f6dc3eb541d..cf1ebd95d7f 100644--- a/ui-tui/src/lib/virtualHeights.ts+++ b/ui-tui/src/lib/virtualHeights.ts@@ -1,3 +1,4 @@+import { TERMUX_TUI_MODE } from '../config/env.js'import type { Msg } from '../types.js'import { transcriptBodyWidth } from './inputMetrics.js'@@ -104,7 +105,7 @@ export const estimatedMsgHeight = (return Math.max(2, msg.todos.length + 2)}- const bodyWidth = transcriptBodyWidth(cols, msg.role, userPrompt)+ const bodyWidth = transcriptBodyWidth(cols, msg.role, userPrompt, TERMUX_TUI_MODE)const text = msg.textlet h = wrappedLines(text || ' ', bodyWidth)