The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge branch 'ethie/windows-tests' into ethie/pm-clean
ethernete97de8d8c33c
diff --cc .gitignoreindex 2d5279bca4c,383effcc7dc..aa9b7f8f638--- a/.gitignore+++ b/.gitignore@@@ -48,141 -177,6 +177,142 @@@ resulrun_datagen_kimik2-thinking.shrun_datagen_megascience_glm4-6.shrun_datagen_sonnet.sh+source-data/*+run_datagen_megascience_glm4-6.sh+data/*+# No trailing slash: also matches node_modules SYMLINKS (worktrees often+# symlink node_modules to the main checkout; the dir-only pattern let one+# slip into a commit and break `npm ci` on CI with ENOTDIR).+node_modules+browser-use/+agent-browser/+# Private keys+*.ppk+*.pem+privvy*+images/+__pycache__/+hermes_agent.egg-info/+wandb/+testlogs+playwright-report/+test-results/+# Playwright visual regression baselines — cached from main in CI, not committed+*-snapshots/++# CLI config (may contain sensitive SSH paths)+cli-config.yaml++# Skills Hub state (lives in ~/.hermes/skills/.hub/ at runtime, but just in case)+skills/.hub/+ignored/+.worktrees/+environments/benchmarks/evals/++# Web UI build output+hermes_cli/web_dist/+# Cross-process web UI build lock (flock target, always empty)+.web_ui_build.lock+apps/desktop/build/+apps/desktop/dist/++# tsc-emitted artifacts (a stray `tsc -b` compiles into src/, and vite then+# resolves the stale .js OVER the .tsx — never track these)+apps/desktop/src/**/*.js+apps/desktop/src/**/*.js.map+apps/desktop/src/**/*.d.ts+# EXCEPT bundled plain-ESM plugin entries (adopted SDK-consumer plugins,+# e.g. hermes-bots): plugin.js IS the source, not tsc output. No .tsx+# sibling exists, so the stale-shadow hazard above cannot apply.+!apps/desktop/src/plugins/*/plugin.js+!apps/desktop/src/global.d.ts+!apps/desktop/src/vite-env.d.ts++# Build/debug artifacts that must never be committed+/log.txt+/sqlite_leak_fix.png+/*.png.bak+*.tar.gz+*.tgz+apps/shared/src/**/*.js+apps/shared/src/**/*.js.map+apps/shared/src/**/*.d.ts+apps/desktop/release/+*.tsbuildinfo++# Web UI assets — synced from @nous-research/ui at build time via+# `npm run sync-assets` (see web/package.json).+web/public/fonts/+web/public/ds-assets/++# Release script temp files+.release_notes.md+mini-swe-agent/++# Nix+.direnv/+.nix-stamps/+result+website/static/api/skills-index.json+# skills.json + skills-meta.json are build artifacts emitted by+# website/scripts/extract-skills.py during prebuild — keep them out of+# git for the same reason as skills-index.json (large, generated, change+# every build).+website/static/api/skills.json+website/static/api/skills-meta.json+# automation-blueprints-index.json is a build artifact emitted by+# website/scripts/extract-automation-blueprints.py during prebuild.+website/static/api/automation-blueprints-index.json+models-dev-upstream/++# Local editor / agent tooling (machine-specific; keep in global config, not the repo)+.codex/+.cursor/+.gemini/+.zed/+.mcp.json+opencode.json+config/mcporter.json++hermes_cli/tui_dist/*+hermes_cli/scripts/+docs/superpowers/*+# Working directory for the Hermes Agent's session state (~/.hermes/ at runtime;+# also created in-repo when an agent operates in this checkout). Plans, audit+# logs, and per-session caches are never artifacts of the codebase.+.hermes/++# Desktop/bootstrap install marker written into the managed checkout root by the+# bootstrap installer. It is Hermes-managed runtime state, never a code change —+# ignore it so `hermes update`'s `git stash push --include-untracked` does not+# treat it as a local edit and autostash it on every run (#38529).+.hermes-bootstrap-complete++# Persistent dev sandbox dir (scripts/dev-sandbox.sh --persistent)+.hermes-sandbox/+# Sandbox dirs used by the install/update E2E (tests/install/). The suffix is+# the route name, so each route gets its own tree and two can run at once.+.hermes-sandbox-e2e*/++# Interrupted-update breadcrumb + recovery lock written next to the shared venv+# by `hermes update` / launch-time self-heal. Runtime state, never a code change+# — ignore so `git status` stays clean and update's autostash skips them.+.update-incomplete+.update-incomplete.lock++# Checkout fingerprint the __pycache__ tree was last validated against+# (launch-time stale-bytecode sweep). Runtime state, never a code change.+.bytecode-fingerprint+.bytecode-fingerprint.tmp++# Installer-written method stamp in the managed checkout root (scripts/install.sh).+# Runtime metadata only — never a code change. Ignore so `git status` stays clean+# and `hermes update`'s untracked autostash does not treat it as a local edit (#66189 / #54855).+/.install_method++# Tool Search live-test harness output — non-deterministic model transcripts,+# regenerated by scripts/tool_search_livetest.py. Never an artifact of the repo.++scripts/out/# Per-release changelog drafts. These exist only transiently during a releasediff --cc agent/deadline.pyindex 92e5e74a385,6b4a753614c..98a908d58c3--- a/agent/deadline.py+++ b/agent/deadline.py@@@ -90,21 -90,23 +90,22 @@@ __all__ =# Upper bound for any timeout handed to platform wait primitives.## CPython converts ``threading.Lock.acquire(timeout=...)`` /-# ``Thread.join(timeout=...)`` deadlines through the platform wait primitive;-# a value too large for that primitive's conversion limit raises-# ``OverflowError``. The ceilings differ per host:-#-# * POSIX — ``time_t`` on macOS (32-bit in #83220) overflows on absurd-# relative timeouts. One year is semantically "unbounded" for every wait-# in this codebase while staying far below ``time_t``.-# * Windows — ``WaitForSingleObject`` takes a DWORD of milliseconds-# (2**32 - 1 ms ≈ 49.7 days), so 365 days would overflow it.-if sys.platform == "win32":- # Leave headroom for consumers that add a small margin on top (e.g. the- # 60s human-wait margin): MAX + margin must stay under the DWORD-millisecond- # ceiling (4294967.295s), so 4_294_907 + 60 rounds to exactly 4_294_967s.- MAX_SAFE_TIMEOUT_S = 4_294_907.0-else:- MAX_SAFE_TIMEOUT_S = 31_536_000.0 # 365 days+# ``Thread.join(timeout=...)`` deadlines to an absolute timestamp; very large+# relative timeouts overflow ``time_t`` on macOS and raise+# ``OverflowError: timestamp out of range for platform time_t`` (#83220).+# On Windows the binding constraint is narrower: the underlying+# ``WaitForSingleObject`` takes a DWORD *milliseconds* argument, so any+# wait above ~49.7 days (0xFFFFFFFF ms) raises OverflowError rather than+# waiting (verified live: 4294967.0s ok, 4294967.3s overflows). One year+# is the semantic "unbounded" on platforms that can express it; Windows+# takes the DWORD-ms cap, which is still semantically "unbounded" for+# every wait in this codebase.+_WINDOWS_MAX_WAIT_S = (0xFFFFFFFF - 1000) / 1000.0 # DWORD ms, minus a 1s rounding guard+MAX_SAFE_TIMEOUT_S = (+ _WINDOWS_MAX_WAIT_S if sys.platform == "win32" else 31_536_000.0+) # 365 days off-Windows++# Grace period after a deadline fires before concluding the event loop thread# is blocked in a synchronous call and dumping stacks (family A diagnostics)._LOOP_BLOCKED_DUMP_GRACE_S = 5.0diff --cc pyproject.tomlindex 679e13b2316,8c21ee1ef2a..93383bd33df--- a/pyproject.toml+++ b/pyproject.toml@@@ -205,7 -196,7 +205,8 @@@ modal = ["modal==1.3.4"daytona = ["daytona==0.155.0"]vercel = ["vercel==0.7.2"]hindsight = ["hindsight-client==0.6.1"]- dev = ["debugpy==1.8.20", "pytest==9.1.1", "pytest-asyncio==1.3.0", "mcp==2.0.0", "httpx2==2.7.0", "starlette==1.3.1", "ty==0.0.21", "ruff==0.15.10", "setuptools==83.0.0", "resvg-py==0.4.0"] # starlette: CVE-2026-48710; setuptools: 83 (torch >=2.13 requires setuptools 83)-dev = ["debugpy==1.8.20", "pytest==9.1.1", "pytest-asyncio==1.3.0", "pytest-xdist==3.8.0", "mcp==2.0.0", "httpx2==2.7.0", "starlette==1.3.1", "ty==0.0.21", "ruff==0.15.10", "setuptools==83.0.0"] # starlette: CVE-2026-48710; setuptools: 83 (torch >=2.13 requires setuptools 83)++dev = ["debugpy==1.8.20", "pytest==9.1.1", "pytest-asyncio==1.3.0", "pytest-xdist==3.8.0", "mcp==2.0.0", "httpx2==2.7.0", "starlette==1.3.1", "ty==0.0.21", "ruff==0.15.10", "resvg-py==0.4.0", "setuptools==83.0.0"] # starlette: CVE-2026-48710; setuptools: 83 (torch >=2.13 requires setuptools 83)++messaging = ["python-telegram-bot[webhooks]==22.8", "discord.py[voice]==2.7.1", "aiohttp==3.14.3", "brotlicffi==1.2.0.1", "slack-bolt==1.30.0", "slack-sdk==3.43.0", "qrcode==7.4.2"] # aiohttp 3.14.3: prior CVEs + GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7cron = [] # croniter is now a core dependency; this extra kept for back-compatslack = ["slack-bolt==1.30.0", "slack-sdk==3.43.0", "aiohttp==3.14.3"]diff --cc scripts/run_tests.shindex 9e32af19698,3a529390b7e..bb6a84d6efa--- a/scripts/run_tests.sh+++ b/scripts/run_tests.sh@@@ -123,19 -106,43 +106,49 @@@ for _win_var in USERPROFILE HOMEDRIVE Hfidone- # ── Test-runner knobs (computed before we drop env) ────────────────────────- # The runner's own documented environment knobs must survive the hermetic- # `env -i` below, or they are silent no-ops for anyone invoking this script:- #- # * HERMES_TEST_WORKERS / PATHS / FILE_TIMEOUT / FILE_RETRIES / SLICE are- # read by run_tests_parallel.py at argparse-default time — inside the- # stripped environment.+ # ── Live-gateway plugin (computed before we drop env) ───────────────────────+ EXTRA_PYTHONPATH=""+ EXTRA_PYTEST_PLUGINS=""+ if [ -f "$HOME/.hermes/pytest_live_guard.py" ]; then+ EXTRA_PYTHONPATH="$HOME/.hermes"+ EXTRA_PYTEST_PLUGINS="pytest_live_guard"+ fi++ # ── Our -j/--jobs flag: consumed here, forwarded via HERMES_TEST_WORKERS ────+ # (both backends read that env knob: run_tests_parallel.py as its worker cap,+ # the xdist path as -n).+ JOBS="${HERMES_TEST_WORKERS:-}"+ PASS_THROUGH=()+ while [ $# -gt 0 ]; do+ case "$1" in+ -j|--jobs)+ JOBS="$2"; shift 2 ;;+ -j*)+ JOBS="${1#-j}"; shift ;;+ --jobs=*)+ JOBS="${1#--jobs=}"; shift ;;+ *)+ PASS_THROUGH+=("$1"); shift ;;+ esac+ done+ set -- ${PASS_THROUGH[@]+"${PASS_THROUGH[@]}"}+ if [ -n "$JOBS" ]; then+ export HERMES_TEST_WORKERS="$JOBS"+ TEST_ENV_KNOB="HERMES_TEST_WORKERS"+ fi++ # ── Test-runner knobs (computed before we drop env) ──────────────────────────# * HERMES_TEST_IMAGE is read by tests/docker/conftest.py to skip its-# session-scoped `docker build`.+# session-scoped `docker build`. CI's docker.yml sets it to the image+# the build step just loaded; stripping it made every per-file pytest+# subprocess rebuild the 5GB image from a cold builder cache instead+# (~4 min per worker per run, and the rebuilt image lacked the+# install stamp the workflow bakes in).++# * session-scoped `docker build`.+ # * POSIX per-file path: HERMES_TEST_WORKERS / PATHS / FILE_TIMEOUT /+ # FILE_RETRIES / SLICE are read by run_tests_parallel.py at argparse-+ # default time — inside the stripped environment.++## These are test-infrastructure knobs, not credentials — same class as the# HERMES_RUN_SLOW_PET_TESTS / HERMES_E2E_BROWSER opt-ins already forwarded.@@@ -152,45 -159,35 +165,53 @@@ don# ── Run in hermetic env ──────────────────────────────────────────────────────# env -i: start with empty environment, opt-in only what we need.# No credential var can leak — you'd have to explicitly add it here.+#+# __NIXOS_SET_ENVIRONMENT_DONE is a NixOS platform guard, not a credential:+# without it, every login shell (bash -l) that a test spawns re-runs+# /etc/set-environment and rebuilds PATH from the system profile — which+# evicts the dev shell's python3/rg and makes terminal, process-registry,+# and ripgrep-backed search tests fail with exit 127 on NixOS hosts.+#+# HERMES_PYTHON_SRC_ROOT is the Nix dev shell's editable-install root: the+# venv's editable finder reads it at runtime to locate first-party modules.+# Stripping it breaks "import tools" in every test subprocess whose cwd is+# not the repo root (the import-guard probe runs from a tempdir).+echo "▶ running per-file parallel test suite via run_tests_parallel.py"+echo " (TZ=UTC LANG=C.UTF-8 PYTHONHASHSEED=0; clean env)"+++cd "$REPO_ROOT"- # ── Pre-compile .pyc bytecode cache ─────────────────────────────────────────- # Each test file runs in its own subprocess via run_tests_parallel.py.- # Pre-building the bytecode cache once here (instead of each subprocess- # compiling on first import) avoids redundant work across ~2000 processes.- # Uses git to list tracked .py files (skips venv, node_modules, etc).echo "▶ pre-compiling bytecode cache""$PYTHON" -m compileall -q -j 0 -- $(git ls-files '*.py') >/dev/null 2>&1 || true- echo "▶ launching test runner"- exec env -i \- PATH="$PATH" \- HOME="$HOME" \- ${WIN_ENV[@]+"${WIN_ENV[@]}"} \- ${TEST_ENV[@]+"${TEST_ENV[@]}"} \- TZ=UTC \- LANG=C.UTF-8 \- LC_ALL=C.UTF-8 \- PYTHONHASHSEED=0 \- PYTHONUTF8=1 \- ${HERMES_RUN_SLOW_PET_TESTS:+HERMES_RUN_SLOW_PET_TESTS="$HERMES_RUN_SLOW_PET_TESTS"} \- ${HERMES_E2E_BROWSER:+HERMES_E2E_BROWSER="$HERMES_E2E_BROWSER"} \- ${__NIXOS_SET_ENVIRONMENT_DONE:+__NIXOS_SET_ENVIRONMENT_DONE="$__NIXOS_SET_ENVIRONMENT_DONE"} \- ${HERMES_PYTHON_SRC_ROOT:+HERMES_PYTHON_SRC_ROOT="$HERMES_PYTHON_SRC_ROOT"} \- ${EXTRA_PYTHONPATH:+PYTHONPATH="$EXTRA_PYTHONPATH"} \- ${EXTRA_PYTEST_PLUGINS:+PYTEST_PLUGINS="$EXTRA_PYTEST_PLUGINS"} \+ HERMETIC_ENV=(+ PATH="$PATH"+ HOME="$HOME"+ ${WIN_ENV[@]+"${WIN_ENV[@]}"}+ ${TEST_ENV[@]+"${TEST_ENV[@]}"}+ TZ=UTC+ LANG=C.UTF-8+ LC_ALL=C.UTF-8+ PYTHONHASHSEED=0+ PYTHONUTF8=1+ ${HERMES_RUN_SLOW_PET_TESTS:+HERMES_RUN_SLOW_PET_TESTS="$HERMES_RUN_SLOW_PET_TESTS"}+ ${HERMES_E2E_BROWSER:+HERMES_E2E_BROWSER="$HERMES_E2E_BROWSER"}++ ${__NIXOS_SET_ENVIRONMENT_DONE:+__NIXOS_SET_ENVIRONMENT_DONE="$__NIXOS_SET_ENVIRONMENT_DONE"}++ ${HERMES_PYTHON_SRC_ROOT:+HERMES_PYTHON_SRC_ROOT="$HERMES_PYTHON_SRC_ROOT"}+ ${EXTRA_PYTHONPATH:+PYTHONPATH="$EXTRA_PYTHONPATH"}+ ${EXTRA_PYTEST_PLUGINS:+PYTEST_PLUGINS="$EXTRA_PYTEST_PLUGINS"}+ )++ if [ "$IS_WINDOWS" -eq 1 ]; then+ echo "▶ windows: pytest-xdist (-n ${HERMES_TEST_WORKERS:-auto} --dist loadfile)"+ exec env -i "${HERMETIC_ENV[@]}" \+ "$PYTHON" -m pytest -n "${HERMES_TEST_WORKERS:-auto}" --dist loadfile \+ -p no:cacheprovider -m "not integration" -q --tb=line "$@"+ fi++ echo "▶ posix: per-file parallel suite via run_tests_parallel.py"+ echo " (TZ=UTC LANG=C.UTF-8 PYTHONHASHSEED=0; clean env)"+ exec env -i "${HERMETIC_ENV[@]}" \++"$PYTHON" "$SCRIPT_DIR/run_tests_parallel.py" "$@"diff --cc scripts/run_tests_parallel.pyindex 7c760696cae,ea989635d91..dd1092d5f68mode 100755,100644..100644--- a/scripts/run_tests_parallel.py+++ b/scripts/run_tests_parallel.pydiff --cc tests/agent/lsp/test_workspace.pyindex 3943e3f287c,9e075b9d006..a59d9976ca6--- a/tests/agent/lsp/test_workspace.py+++ b/tests/agent/lsp/test_workspace.py@@@ -70,15 -69,8 +70,16 @@@ def test_resolve_workspace_for_file_use+ @pytest.mark.platforms("linux")def test_normalize_path_expands_tilde(monkeypatch):- monkeypatch.setenv("HOME", "/home/user")+ # expanduser keys off USERPROFILE on native Windows, HOME elsewhere —+ # set the var the running host actually consults (host-native rule:+ # never fake the platform).+ if sys.platform == "win32":+ monkeypatch.setenv("USERPROFILE", r"C:\Users\fakeuser")+ expected_base = r"C:\Users\fakeuser"+ else:+ monkeypatch.setenv("HOME", "/home/user")+ expected_base = "/home/user"p = normalize_path("~/x.py")- assert p == os.path.abspath("/home/user/x.py")+ assert p == os.path.abspath(os.path.join(expected_base, "x.py"))diff --cc tests/cron/test_cron_script.pyindex 0688e0a8483,c5ff375ce35..d371c7e47b6--- a/tests/cron/test_cron_script.py+++ b/tests/cron/test_cron_script.py@@@ -133,11 -133,11 +133,11 @@@ class TestRunJobScriptassert 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_WINDOW- # creationflags this branch exists for.+ # Windows-only: the real ``Scripts/python.exe`` launcher layout and+ # CREATE_NO_WINDOW creationflags this branch exists for cannot be+ # reproduced with a patched ``sys.platform``.from cron import scheduler as sched_modfrom cron.scheduler import _run_job_scriptdiff --cc tests/cron/test_cron_workdir.pyindex 3985706e21c,5eb4c0a8140..8c189f17fce--- a/tests/cron/test_cron_workdir.py+++ b/tests/cron/test_cron_workdir.py@@@ -46,11 -45,10 +46,12 @@@ class TestNormalizeWorkdirresult = _normalize_workdir(str(tmp_path))assert result == str(tmp_path.resolve())+ @pytest.mark.platforms("linux")def test_tilde_expands(self, tmp_path, monkeypatch):from cron.jobs import _normalize_workdir- monkeypatch.setenv("HOME", str(tmp_path))+ # expanduser keys off USERPROFILE on native Windows, HOME elsewhere.+ home_var = "USERPROFILE" if sys.platform == "win32" else "HOME"+ monkeypatch.setenv(home_var, str(tmp_path))result = _normalize_workdir("~")assert result == str(tmp_path.resolve())diff --cc tests/cron/test_script_claim_heartbeat.pyindex 0b91e1934a3,b9fb0ca0728..7b001d8bdbf--- a/tests/cron/test_script_claim_heartbeat.py+++ b/tests/cron/test_script_claim_heartbeat.py@@@ -10,42 -10,7 +10,41 @@@ from unittest.mock import MagicMock, paimport pytest+_SPAWNABLE_PY: "str | None" = None+++def _spawnable_python() -> str:+ global _SPAWNABLE_PY+ if _SPAWNABLE_PY is not None:+ return _SPAWNABLE_PY++ """An interpreter that can actually CreateProcess children. The hermetic+ runner's sys.executable can be an emulated x64 binary on an arm64 host+ (WinError 5 on every spawn); the WindowsApps packaged python works by+ full path. Falls back to sys.executable."""+ import os+ import subprocess as sp++ for cand in (os.environ.get("HERMES_TEST_PYTHON"), sys.executable):+ if not cand:+ continue+ try:+ # The candidate must run AND spawn its own child — these tests+ # execute scripts that Popen grandchildren, and an emulated+ # interpreter can run -c while its own subprocess.Popen fails.+ r = sp.run(+ [cand, "-c", "import subprocess; subprocess.run(['cmd','/c','exit 0'] if __import__('os').name=='nt' else ['true'])"],+ capture_output=True, timeout=30,+ )+ if r.returncode == 0:+ _SPAWNABLE_PY = cand+ return cand+ except Exception:+ continue+ _SPAWNABLE_PY = sys.executable+ return _SPAWNABLE_PY+--+ @pytest.mark.platforms("linux")def test_cancel_event_terminates_script_process_tree(tmp_path, monkeypatch):"""Losing a fire claim must stop both the script and its descendants."""import cron.scheduler as scheduler@@@ -596,11 -541,9 +595,15 @@@ def test_repeated_heartbeat_errors_canc}monkeypatch.setattr(scheduler, "heartbeat_fire_claim", heartbeat)monkeypatch.setattr(scheduler, "_run_one_job_body", run_body)+ monkeypatch.setattr(scheduler, "_RUN_CLAIM_HEARTBEAT_SECONDS", 0.01)+ # Generous grace (30x the interval, not 3x): the heartbeat thread competes+ # with 36-way parallel test workers for the GIL/CPU; a couple of slow+ # ticks must not cancel before the run body's 0.5s wait completes+ # (loose-bounds rule for timing-sensitive tests).+++ # Intervals well above Windows' ~15ms timer resolution so the grace window+ # reliably spans 3+ heartbeat ticks (10ms/30ms left only ~2 on win32).+ monkeypatch.setattr(scheduler, "_RUN_CLAIM_HEARTBEAT_SECONDS", 0.05)monkeypatch.setattr(scheduler, "_FIRE_CLAIM_HEARTBEAT_GRACE_SECONDS", 0.3)assert scheduler.run_one_job(job) is Truediff --cc tests/hermes_cli/test_dep_ensure.pyindex bbf5df939ed,21afa8f1c79..cd32d408881--- a/tests/hermes_cli/test_dep_ensure.py+++ b/tests/hermes_cli/test_dep_ensure.py@@@ -6,62 -3,123 +6,104 @@@ from unittest.mock import patcimport pytest+def test_unknown_dep_refused():+ from hermes_cli.dep_ensure import ensure_dependency++ assert ensure_dependency("not-a-dep") is False++ @pytest.mark.platforms("linux")+ def test_find_install_script_from_checkout(tmp_path):+ """_find_install_script finds scripts/install.sh in a git checkout.++ ``platforms("linux")``: the POSIX arm picks ``install.sh`` + ``bash``, which is+ already what ``_IS_WINDOWS`` reports here — nothing needs faking.+ """+ from hermes_cli.dep_ensure import _find_install_script+ scripts_dir = tmp_path / "scripts"+ scripts_dir.mkdir()+ (scripts_dir / "install.sh").write_text("#!/bin/bash", encoding="utf-8")+ path, shell = _find_install_script(package_dir=tmp_path / "hermes_cli", repo_root=tmp_path)+ assert path is not None+ assert path.name == "install.sh"+ assert shell == "bash"++def test_available_dep_short_circuits(monkeypatch):+ from hermes_cli import dep_ensure+ monkeypatch.setitem(+ dep_ensure._DEPS, "node", (lambda: True, ("node",))+ )+ called = []+ with patch("pm.ensure", side_effect=lambda *a, **k: called.append(a)):+ assert dep_ensure.ensure_dependency("node") is True+ assert called == []+def test_missing_dep_installs_through_pm(monkeypatch):+ from hermes_cli import dep_ensure+ state = {"installed": False}+ monkeypatch.setitem(+ dep_ensure._DEPS, "node", (lambda: state["installed"], ("node",))+ )+ def fake_ensure(name, **kw):+ assert name == "node"+ state["installed"] = True-def test_has_npx_agent_browser_true_when_npx_resolves():- """agent-browser resolves lazily via npx on the default install (#43564)- — _has_npx_agent_browser mirrors the runtime cascade so the "browser" dep- check doesn't wrongly report it missing."""- from hermes_cli.dep_ensure import _has_npx_agent_browser- import tools.browser_tool as bt-- with patch.object(bt, "_find_agent_browser", return_value="npx agent-browser"), \- patch.object(bt, "_requires_real_termux_browser_install", return_value=False):- assert _has_npx_agent_browser() is True---def test_has_npx_agent_browser_false_on_termux_local_bare_npx():- from hermes_cli.dep_ensure import _has_npx_agent_browser- import tools.browser_tool as bt-- with patch.object(bt, "_find_agent_browser", return_value="npx agent-browser"), \- patch.object(bt, "_requires_real_termux_browser_install", return_value=True):- assert _has_npx_agent_browser() is False---def test_has_npx_agent_browser_false_when_nothing_resolves():- from hermes_cli.dep_ensure import _has_npx_agent_browser- import tools.browser_tool as bt-- def _raise(**_kw):- raise FileNotFoundError("agent-browser CLI not found")-- with patch.object(bt, "_find_agent_browser", _raise):- assert _has_npx_agent_browser() is False+ with patch("pm.ensure", side_effect=fake_ensure):+ assert dep_ensure.ensure_dependency("node") is True-def test_find_agent_browser_lazy_install_cycle_terminates(monkeypatch):- """tools.browser_tool._find_agent_browser's "nothing found" branch calls- ensure_dependency("browser"), whose "browser" check now includes- _has_npx_agent_browser() -> _find_agent_browser(validate=False) again.- That nested call must NOT be able to trigger another ensure_dependency- call (only validate=True does that) — verifying the cycle is bounded to- one extra rescan, not unbounded recursion, using the real functions on- both sides rather than mocking the cycle away."""- import shutil- import tools.browser_tool as bt+def test_pm_refusal_reports_and_returns_false(monkeypatch, capsys):from hermes_cli import dep_ensure- monkeypatch.setattr(bt, "_cached_agent_browser", None)- monkeypatch.setattr(bt, "_agent_browser_resolved", False)- monkeypatch.setattr(shutil, "which", lambda *a, **k: None)- monkeypatch.setattr(bt, "_resolve_npx_bin", lambda: None)- monkeypatch.setattr(dep_ensure, "_has_system_browser", lambda: False)- monkeypatch.setattr(dep_ensure, "_has_hermes_agent_browser", lambda: False)- monkeypatch.setattr(dep_ensure, "_find_install_script", lambda *a, **k: (None, None))+ monkeypatch.setitem(+ dep_ensure._DEPS, "node", (lambda: False, ("node",))+ )+ import pm as pm_mod- real_find_agent_browser = bt._find_agent_browser- validate_calls = []+ def refuse(name, **kw):+ raise pm_mod.InstallError(name, "lazy installs are disabled", "run `hermes pm install`")- def counting_find_agent_browser(*, validate=True):- validate_calls.append(validate)- return real_find_agent_browser(validate=validate)+ with patch("pm.ensure", side_effect=refuse):+ assert dep_ensure.ensure_dependency("node", interactive=True) is False+ out = capsys.readouterr().out+ assert "hermes pm install" in out- monkeypatch.setattr(bt, "_find_agent_browser", counting_find_agent_browser)- with pytest.raises(FileNotFoundError):- bt._find_agent_browser(validate=True)-- # One outer validate=True call, plus exactly one bounded nested- # validate=False rescan from _has_npx_agent_browser inside- # ensure_dependency's "browser" check — not unbounded recursion, and not- # a second ensure_dependency("browser") call (which would show up as a- # second `True` in this list).- assert validate_calls == [True, False]+def test_browser_check_consults_pm(monkeypatch):+ from hermes_cli import dep_ensure+ monkeypatch.setattr("shutil.which", lambda *a, **k: None)+ with patch("pm.is_installed", return_value=True):+ assert dep_ensure._browser_available() is True+ with patch("pm.is_installed", return_value=False):+ assert dep_ensure._browser_available() is False++ @pytest.mark.platforms("windows")+ def test_ensure_dependency_uses_powershell_on_windows(tmp_path):+ """``platforms("windows")``: the assertion is that we shell out to a real+ PowerShell. Faking ``_IS_WINDOWS`` on Linux also required faking+ ``shutil.which`` into inventing a powershell.exe that isn't there."""+ from hermes_cli.dep_ensure import ensure_dependency+ scripts_dir = tmp_path / "scripts"+ scripts_dir.mkdir(parents=True)+ (scripts_dir / "install.ps1").write_text("# fake")+ with patch("hermes_cli.dep_ensure._DEP_CHECKS", {"node": lambda: False}), \+ patch("hermes_cli.dep_ensure._find_install_script", return_value=(scripts_dir / "install.ps1", "powershell")), \+ patch("hermes_cli.dep_ensure.shutil") as mock_shutil, \+ patch("hermes_constants.get_hermes_home", return_value=tmp_path / "fakehome"), \+ patch("subprocess.run") as mock_run, \+ patch("sys.stdin") as mock_stdin:+ mock_shutil.which.side_effect = lambda name: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" if name == "powershell" else None+ mock_stdin.isatty.return_value = False+ mock_run.return_value = type("R", (), {"returncode": 0})()+ ensure_dependency("node", interactive=False)+ cmd = mock_run.call_args[0][0]+ assert "powershell" in cmd[0].lower()+ assert "-Ensure" in cmd+ assert cmd[cmd.index("-Ensure") + 1] == "node"+ assert "-HermesHome" in cmd+ assert str(tmp_path / "fakehome") in cmddiff --cc tests/hermes_cli/test_gui_command.pyindex 32eea9f3fe8,0649f36d2c7..80fc10dd037--- a/tests/hermes_cli/test_gui_command.py+++ b/tests/hermes_cli/test_gui_command.py@@@ -1000,14 -971,10 +1003,14 @@@ def test_gui_launches_even_when_desktopcli_main.cmd_gui(_ns())assert exc.value.code == 0- assert mock_run.call_args.args[0] == [str(packaged_exe)]+ launched = mock_run.call_args.args[0]+ if sys.platform.startswith("linux"):+ assert launched == [str(packaged_exe), "--disable-setuid-sandbox"]+ else:+ assert launched == [str(packaged_exe)]- @pytest.mark.macos_only+ @pytest.mark.platforms("macos")def test_gui_skips_desktop_entry_off_linux(tmp_path, monkeypatch):root = _make_desktop_tree(tmp_path)monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)diff --cc tests/hermes_cli/test_linux_desktop_entry.pyindex 6b638fcd539,bbdb384965f..3371c1f1001--- a/tests/hermes_cli/test_linux_desktop_entry.py+++ b/tests/hermes_cli/test_linux_desktop_entry.py@@@ -35,7 -41,10 +36,9 @@@ def _parse(entry_text: str) -> dictreturn values- def test_install_writes_entry_with_absolute_exec_and_icon(tmp_path, xdg_home, monkeypatch):[email protected]("linux")+ def test_install_writes_entry_with_absolute_exec_and_icon(+ tmp_path, xdg_home, monkeypatch+ ):root = _make_project(tmp_path)hermes_bin = tmp_path / "bin" / "hermes"hermes_bin.parent.mkdir()@@@ -59,16 -71,74 +62,74 @@@icon_path = Path(values["Icon"])assert icon_path.is_absolute()assert icon_path == lde.icon_path(root)+ assert icon_path.read_bytes() == b"\x89PNG fake"++ @pytest.mark.platforms("linux")+++ def test_install_prefers_themed_icon_from_hicolor(tmp_path, xdg_home, monkeypatch):+ """When the icon installs into hicolor, the entry uses the themed name.++ The themed name survives a moved/archived checkout; an absolute+ Icon= path does not (the same durability class the Exec line was+ fixed for).+ """+ root = _make_project(tmp_path)+ hermes_bin = tmp_path / "bin" / "hermes"+ hermes_bin.parent.mkdir()+ hermes_bin.write_text("", encoding="utf-8")+ monkeypatch.setattr(+ "hermes_cli.relaunch.resolve_hermes_bin", lambda: str(hermes_bin)+ )+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ entry = lde.install_desktop_entry(root)++ values = _parse(entry.read_text(encoding="utf-8"))+ assert values["Icon"] == "hermes"++ # And the icon really landed in the hicolor tree: the fixture icon is+ # a fake PNG (no valid IHDR), so the size is unknown and the icon+ # lands under scalable/.+ dest = xdg_home / "icons" / "hicolor" / "scalable" / "apps" / "hermes.png"+ assert dest.is_file()+ assert dest.read_bytes() == lde.icon_path(root).read_bytes()+ @pytest.mark.platforms("linux")+++ def test_install_icon_copy_failure_falls_back_to_absolute(+ tmp_path, xdg_home, monkeypatch+ ):+ """An impossible icon copy keeps the absolute path (never breaks)."""+ root = _make_project(tmp_path)+ hermes_bin = tmp_path / "bin" / "hermes"+ hermes_bin.parent.mkdir()+ hermes_bin.write_text("", encoding="utf-8")+ monkeypatch.setattr(+ "hermes_cli.relaunch.resolve_hermes_bin", lambda: str(hermes_bin)+ )+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ def _boom(src, dst):+ raise OSError("read-only tree")++ monkeypatch.setattr(lde.shutil, "copyfile", _boom)++ entry = lde.install_desktop_entry(root)+ values = _parse(entry.read_text(encoding="utf-8"))+ # The real helper catches the copy OSError and returns False, so the+ # caller falls back to the absolute path without raising.+ assert values["Icon"] == str(lde.icon_path(root))+assert values["Type"] == "Application"assert values["Name"] == "Hermes"assert values["Terminal"] == "false"+ @pytest.mark.platforms("linux")def test_installed_entry_is_executable(tmp_path, xdg_home, monkeypatch):root = _make_project(tmp_path)- monkeypatch.setattr(- "hermes_cli.relaunch.resolve_hermes_bin", lambda: "/usr/bin/hermes"- )+ monkeypatch.setattr("hermes_cli.relaunch.resolve_hermes_bin", lambda: "/usr/bin/hermes")monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])entry = lde.install_desktop_entry(root)@@@ -157,11 -235,311 +224,309 @@@ def test_exec_leaves_venv_shebang_scripassert exec_line == f"{hermes_bin} desktop"+++++ # The persisted entry must be launch-context independent: whatever process+ # writes it, the next launch reads and rewrites the same bytes. argv[0]+ # differs per launch path (wrapper / repo script / python -m), so a+ # checkout-internal argv[0] must not be persisted — the resolver falls+ # through to PATH, where the installer's durable wrapper lives.+ def _argv0_context(monkeypatch, argv0: str) -> None:+ import sys++ monkeypatch.setattr(sys, "argv", [argv0, "desktop"])+ @pytest.mark.platforms("linux")+++ def test_exec_converges_from_repo_script_argv0_to_installed_wrapper(+ tmp_path, xdg_home, monkeypatch+ ):+ """A broken interpreter-form entry must self-heal to the wrapper form.++ Launching with argv[0] = <checkout>/hermes (what the broken entry+ itself spawns) previously re-persisted the same broken form forever —+ the bootstrap loop that kept #90492 from repairing existing installs.+ """+ import sys++ root = _make_project(tmp_path)+ repo_script = root / "hermes" # checkout-internal launcher candidate+ repo_script.write_text(+ "#!/usr/bin/env python3\nimport hermes_cli\n", encoding="utf-8"+ )+ 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.chmod(0o755)++ # argv[0] = repo script; PATH lookup finds the installed wrapper.+ _argv0_context(monkeypatch, str(repo_script))+ monkeypatch.setattr(+ "shutil.which", lambda name: str(wrapper) if name == "hermes" else None+ )+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ entry = lde.install_desktop_entry(root)+ exec_line = _parse(entry.read_text(encoding="utf-8"))["Exec"]++ # Converged on the durable wrapper — NOT the repo script, and NOT an+ # interpreter-prefixed form pinning sys.executable.+ assert exec_line == f"{wrapper} desktop"+ @pytest.mark.platforms("linux")+++ def test_exec_never_persists_a_bare_interpreter_command(+ tmp_path, xdg_home, monkeypatch+ ):+ """The `python -m hermes_cli.main` relaunch context must not write+ `Exec=<python> desktop` — a command line no DE can run."""+ import sys++ 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.chmod(0o755)++ interpreter = tmp_path / "uv" / "cpython-3.11.15" / "bin" / "python3.11"+ interpreter.parent.mkdir(parents=True)+ interpreter.write_bytes(b"\x7fELF fake")+ interpreter.chmod(0o755)++ # argv[0] IS the interpreter (python -m context); PATH has the wrapper.+ _argv0_context(monkeypatch, str(interpreter))+ monkeypatch.setattr(+ "shutil.which", lambda name: str(wrapper) if name == "hermes" else None+ )+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ entry = lde.install_desktop_entry(root)+ exec_line = _parse(entry.read_text(encoding="utf-8"))["Exec"]++ first_token = exec_line.split(" ")[0].strip('"')+ assert Path(first_token) != interpreter+ assert not (+ Path(first_token).name.startswith("python")+ and "desktop" in exec_line.split(" ", 1)[1]+ ), f"persisted an unrunnable bare-interpreter Exec: {exec_line}"+ assert exec_line == f"{wrapper} desktop"+ @pytest.mark.platforms("linux")+++ def test_exec_keeps_resolver_fallback_when_no_wrapper_on_path(+ tmp_path, xdg_home, monkeypatch+ ):+ """No wrapper anywhere → #90492's runnable fallback, never a dead Exec.++ With argv[0] checkout-internal and PATH + known locations both empty,+ the resolver returns None and resolve_exec_command emits the runnable+ `sys.executable -m hermes_cli.main desktop` fallback. Persisting the+ interpreter itself (`<python> desktop`) would be unrunnable by any DE;+ persisting the repo script alone dies on its env shebang.+ """+ import sys++ root = _make_project(tmp_path)+ repo_script = root / "hermes"+ repo_script.write_text(+ "#!/usr/bin/env python3\nimport hermes_cli\n", encoding="utf-8"+ )+ repo_script.chmod(0o755)++ _argv0_context(monkeypatch, str(repo_script))+ monkeypatch.setattr("shutil.which", lambda name: None)+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ def fake_resolve():+ # Mirror resolve_hermes_bin's chain: argv[0] → relative → PATH → None.+ return sys.argv[0] if sys.argv[0] else None++ monkeypatch.setattr("hermes_cli.relaunch.resolve_hermes_bin", fake_resolve)++ entry = lde.install_desktop_entry(root)+ exec_line = _parse(entry.read_text(encoding="utf-8"))["Exec"]++ # The runnable module fallback — NOT the bare repo script (its env+ # shebang would escape the venv under a DE) and NOT `<python> desktop`.+ assert exec_line.endswith("-m hermes_cli.main desktop")+ assert Path(exec_line.split(" ")[0].strip('"')).is_absolute()+ assert str(repo_script) not in exec_line+ @pytest.mark.platforms("linux")+++ def test_exec_uses_known_wrapper_when_path_lookup_misses(+ tmp_path, xdg_home, monkeypatch+ ):+ """Stripped-PATH session + wrapper at the known installer location.++ systemd user sessions and autostart relaunches often run without+ ~/.local/bin on PATH. When shutil.which finds nothing, the resolver+ must probe the known durable locations directly instead of silently+ persisting a checkout-internal Exec line.+ """+ import sys++ root = _make_project(tmp_path)+ repo_script = root / "hermes"+ repo_script.write_text(+ "#!/usr/bin/env python3\nimport hermes_cli\n", encoding="utf-8"+ )+ repo_script.chmod(0o755)++ # The wrapper exists at the known location but is NOT on PATH.+ # Realistic installer shim: execs this checkout's venv python on the+ # checkout's hermes script (the aidiyet check requires it to target+ # the writing checkout).+ 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',+ encoding="utf-8",+ )+ known_wrapper.chmod(0o755)+ monkeypatch.setenv("HOME", str(tmp_path / "known-home"))++ _argv0_context(monkeypatch, str(repo_script))+ monkeypatch.setattr("shutil.which", lambda name: None)++ def fake_resolve():+ return sys.argv[0] if sys.argv[0] else None++ monkeypatch.setattr("hermes_cli.relaunch.resolve_hermes_bin", fake_resolve)+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ entry = lde.install_desktop_entry(root)+ exec_line = _parse(entry.read_text(encoding="utf-8"))["Exec"]++ # The probe found the wrapper despite the PATH miss.+ assert exec_line == f"{known_wrapper} desktop"+ @pytest.mark.platforms("linux")+++ def test_exec_rejects_known_wrapper_from_another_checkout(+ tmp_path, xdg_home, monkeypatch+ ):+ """A known-location wrapper that targets a DIFFERENT checkout is skipped.++ On machines with multiple installs over time, ~/.local/bin/hermes may+ belong to another checkout. Persisting it would make the entry stable+ but silently point at that other installation — the failure class the+ aidiyet check exists to prevent. The runnable module fallback must win+ instead.+ """+ import sys++ root = _make_project(tmp_path)+ repo_script = root / "hermes"+ repo_script.write_text(+ "#!/usr/bin/env python3\nimport hermes_cli\n", encoding="utf-8"+ )+ repo_script.chmod(0o755)++ # A shim belonging to a DIFFERENT checkout.+ other_root = tmp_path / "other-install"+ other_root.mkdir()+ 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'{other_root / "hermes"} "$@"\n',+ encoding="utf-8",+ )+ foreign_wrapper.chmod(0o755)+ monkeypatch.setenv("HOME", str(tmp_path / "known-home"))++ _argv0_context(monkeypatch, str(repo_script))+ monkeypatch.setattr("shutil.which", lambda name: None)++ def fake_resolve():+ return sys.argv[0] if sys.argv[0] else None++ monkeypatch.setattr("hermes_cli.relaunch.resolve_hermes_bin", fake_resolve)+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda _dir: [])++ entry = lde.install_desktop_entry(root)+ exec_line = _parse(entry.read_text(encoding="utf-8"))["Exec"]++ # The foreign wrapper was rejected; the runnable module fallback won.+ assert str(foreign_wrapper) not in exec_line+ assert exec_line.endswith("-m hermes_cli.main desktop")+++ @pytest.mark.parametrize(+ ("layout", "env_overrides", "expected"),+ [+ pytest.param(+ "user",+ {},+ "HOME-SET-BY-TEST/.local/bin/hermes",+ id="user-layout",+ ),+ pytest.param(+ "termux",+ {"PREFIX": "PREFIX-SET-BY-TEST"},+ "PREFIX-SET-BY-TEST/bin/hermes",+ id="termux-prefix-first",+ ),+ pytest.param(+ "root-fhs",+ {"__EUID0__": "1"},+ "/usr/local/bin/hermes",+ id="root-fhs",+ ),+ pytest.param(+ "non-root-no-fhs",+ {"__EUID0__": "0"},+ "HOME-SET-BY-TEST/.local/bin/hermes",+ id="non-root-excludes-fhs",+ ),+ ],+ )+ @pytest.mark.platforms("linux")+ def test_known_wrapper_candidates_cover_installer_layouts(+ layout, env_overrides, expected, monkeypatch+ ):+ """_known_wrapper_candidates mirrors get_command_link_dir() layouts.++ Termux ($PREFIX/bin) outranks everything; root FHS (/usr/local/bin)+ applies only to euid 0; the user layout (~/.local/bin) is always a+ candidate. Locking these in protects against silent regressions in+ the stripped-PATH probe path.+ """+ import os++ sentinel_home = "/home/__sentinel_home__"+ monkeypatch.setenv("HOME", sentinel_home)+ for key, value in env_overrides.items():+ if key == "__EUID0__":+ monkeypatch.setattr(lde.os, "geteuid", lambda: 0 if value == "1" else 1000)+ else:+ monkeypatch.setenv(key, value)++ candidates = [str(c) for c in lde._known_wrapper_candidates()]++ expected_resolved = expected.replace("HOME-SET-BY-TEST", sentinel_home)+ assert expected_resolved in candidates+ if layout == "termux":+ # PREFIX outranks the user layout.+ assert candidates[0] == expected_resolved+ if layout == "root-fhs":+ # Root FHS outranks the user layout.+ assert candidates.index("/usr/local/bin/hermes") < candidates.index(+ f"{sentinel_home}/.local/bin/hermes"+ )+ if layout == "non-root-no-fhs":+ # Non-root euid: /usr/local/bin must be excluded outright.+ assert "/usr/local/bin/hermes" not in candidates+ @pytest.mark.platforms("linux")++def test_install_is_idempotent_and_skips_cache_refresh(tmp_path, xdg_home, monkeypatch):root = _make_project(tmp_path)- monkeypatch.setattr(- "hermes_cli.relaunch.resolve_hermes_bin", lambda: "/usr/bin/hermes"- )+ monkeypatch.setattr("hermes_cli.relaunch.resolve_hermes_bin", lambda: "/usr/bin/hermes")calls: list[Path] = []- monkeypatch.setattr(- lde, "refresh_desktop_databases", lambda d: calls.append(d) or []- )+ monkeypatch.setattr(lde, "refresh_desktop_databases", lambda d: calls.append(d) or [])lde.install_desktop_entry(root)assert len(calls) == 1diff --cc tests/hermes_cli/test_npm_engine.pyindex 19b75ca37d4,1464b7436a5..1d52740eb6a--- a/tests/hermes_cli/test_npm_engine.py+++ b/tests/hermes_cli/test_npm_engine.py@@@ -84,6 -85,98 +84,100 @@@ class TestDetectionassert required_npm_range(broken) is None+++++ @pytest.mark.require_symlinks+ class TestManagedDetection:+ """The upgrade must fire for every spelling of the managed npm, and for+ no other npm — this is the boundary between "Hermes fixes it" and "the+ user's own toolchain is left alone"."""++ @pytest.fixture+ def managed_tree(self, tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ node = home / "node"+ (node / "bin").mkdir(parents=True)+ (node / "lib" / "node_modules" / "npm" / "bin").mkdir(parents=True)+ cli = node / "lib" / "node_modules" / "npm" / "bin" / "npm-cli.js"+ cli.write_text("#!/usr/bin/env node\n", encoding="utf-8")+ (node / "bin" / "npm").symlink_to(cli)+ monkeypatch.setenv("HERMES_HOME", str(home))+ return home++ def test_direct_managed_bin_is_managed(self, managed_tree):+ npm = managed_tree / "node" / "bin" / "npm"+ assert managed_npm_prefix(npm) == managed_tree / "node"++ def test_symlink_from_local_bin_resolves_to_managed(self, managed_tree, tmp_path):+ """An install links ~/.local/bin/npm at the managed tree; that link is+ the npm a user's PATH actually resolves, so it must count as managed."""+ local_bin = tmp_path / "local-bin"+ local_bin.mkdir()+ link = local_bin / "npm"+ link.symlink_to(managed_tree / "node" / "bin" / "npm")+ assert managed_npm_prefix(link) == managed_tree / "node"++ def test_system_npm_is_not_managed(self, managed_tree, tmp_path):+ system_npm = tmp_path / "usr" / "bin" / "npm"+ system_npm.parent.mkdir(parents=True)+ system_npm.write_text("#!/bin/sh\n", encoding="utf-8")+ assert managed_npm_prefix(system_npm) is None++ def test_no_npm_is_not_managed(self, managed_tree):+ assert managed_npm_prefix(None) is None+ assert managed_npm_prefix("") is None+++ class TestInUseDeferral:+ """The managed tree cannot be written while a running app executes from+ it (WinError 5 on npm.cmd, #80926) — the npm upgrade defers instead."""++ @pytest.fixture+ def managed_npm(self, tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ bin_dir = home / "node" / "bin"+ bin_dir.mkdir(parents=True)+ npm = bin_dir / "npm"+ npm.write_text("#!/bin/sh\n", encoding="utf-8")+ npm.chmod(0o755)+ monkeypatch.setenv("HERMES_HOME", str(home))+ return npm++ def test_in_use_managed_tree_defers_upgrade_without_running_npm(+ self, managed_npm, monkeypatch+ ):+ monkeypatch.setattr(npm_engine, "managed_node_tree_in_use", lambda: True)++ def forbidden_run(cmd, **kwargs):+ raise AssertionError(f"npm must not run while the tree is in use: {cmd}")++ monkeypatch.setattr(subprocess, "run", forbidden_run)++ result = npm_engine.upgrade_managed_npm(+ str(managed_npm),+ ">=11.0.0",+ prefix=managed_npm.parent,+ quiet=True,+ )+ assert result is False++ def test_in_use_deferral_blocks_repair_retry(self, managed_npm, monkeypatch):+ """End-to-end: an in-use tree means no npm subprocess runs and no+ retry is offered — the original EBADENGINE failure stands with the+ deferral notice."""+ monkeypatch.setattr(npm_engine, "managed_node_tree_in_use", lambda: True)++ def forbidden_run(cmd, **kwargs):+ raise AssertionError(f"npm must not run while the tree is in use: {cmd}")++ monkeypatch.setattr(subprocess, "run", forbidden_run)++ assert (+ maybe_repair_npm_engine(str(managed_npm), EBADENGINE_OUTPUT, quiet=True)+ is None+ )++class TestRepairDecision:"""`maybe_repair_npm_engine` returns the npm to retry with (truthy) onlywhen a repair actually happened, because its return value is what gatesdiff --cc tests/hermes_cli/test_runtime_repair.pyindex 439750344b1,ccbf3a3596b..e3f5257afae--- a/tests/hermes_cli/test_runtime_repair.py+++ b/tests/hermes_cli/test_runtime_repair.py@@@ -810,15 -1259,14 +810,16 @@@ class TestDefaultLiveVenvroot.mkdir()(root / "pyproject.toml").write_text("[project]\n", encoding="utf-8")for d in dirs:- bin_dir = root / d / "bin"+ bin_dir = root / d / ("Scripts" if windows else "bin")bin_dir.mkdir(parents=True)- (bin_dir / "python").write_text("py", encoding="utf-8")+ (bin_dir / ("python.exe" if windows else "python")).write_text(+ "py", encoding="utf-8"+ )return root+ @pytest.mark.platforms("linux")def test_dot_venv_only_is_targeted(self, tmp_path):- from hermes_cli.managed_uv import _default_live_venv+ from hermes_cli.runtime_repair import _default_live_venvroot = self._checkout(tmp_path, ".venv")assert _default_live_venv(root) == root / ".venv"diff --cc tests/hermes_cli/test_serve_runtime_inventory.pyindex 40481462fc5,793582436fc..4555c1d23a1--- a/tests/hermes_cli/test_serve_runtime_inventory.py+++ b/tests/hermes_cli/test_serve_runtime_inventory.py@@@ -214,24 -217,8 +217,27 @@@ def test_scan_dashboard_processes_ledgemonkeypatch.setitem(sys.modules, "hermes_cli.process_identity", fake_pi)fake_run = SimpleNamespace(returncode=0, stdout="")monkeypatch.setattr(dp.subprocess, "run", lambda *a, **k: fake_run)+ import hermes_cli._subprocess_compat as _sc++ monkeypatch.setattr(_sc, "bounded_probe_run", lambda *a, **k: fake_run)assert dp._scan_dashboard_processes(exclude_pids={8124}) == []+++def test_inventory_records_the_serve_process_incarnation(monkeypatch):+ """The plan carries ``(pid, create_time)``, not just the PID (#92145 review).++ The post-abort survivor probe compares a planned serve against the live+ spawn ledger. With only the number to compare, a NEW serve that reused the+ old PID reads as the pre-update process that never restarted, and recovery+ stays incomplete forever.+ """+ entry = _ledger_entry(create_time=1712345678.5)+ fake_pi = SimpleNamespace(+ ledger_entries=lambda **k: [entry],+ spawner_is_dead=lambda e: None,+ )+ monkeypatch.setitem(sys.modules, "hermes_cli.process_identity", fake_pi)+ plan = update_inventory.collect_runtime_inventory()+ serves = [r for r in plan.runtimes if r.kind == "serve"]+ assert serves and serves[0].detail["create_time"] == 1712345678.5diff --cc tests/hermes_cli/test_tui_npm_install.pyindex 484c138ee09,7495daeaa72..4dfbc33498c--- a/tests/hermes_cli/test_tui_npm_install.py+++ b/tests/hermes_cli/test_tui_npm_install.py@@@ -254,6 -287,114 +254,116 @@@ def test_no_install_prebuilt_bundle_modassert main_mod._tui_need_npm_install(tmp_path) is False+++++ def test_need_rebuild_when_tui_bundle_missing(tmp_path: Path, main_mod) -> None:+ (tmp_path / "src").mkdir()+ (tmp_path / "src" / "entry.tsx").write_text("console.log('src')")++ assert main_mod._tui_need_rebuild(tmp_path) is True+++ def test_no_rebuild_when_tui_bundle_newer_than_inputs(tmp_path: Path, main_mod) -> None:+ _touch_tui_entry(tmp_path)+ src = tmp_path / "src"+ src.mkdir()+ (src / "entry.tsx").write_text("console.log('src')")+ os.utime(src / "entry.tsx", (100, 100))+ os.utime(tmp_path / "dist" / "entry.js", (200, 200))++ assert main_mod._tui_need_rebuild(tmp_path) is False+++ def test_rebuild_when_tui_source_newer_than_bundle(tmp_path: Path, main_mod) -> None:+ _touch_tui_entry(tmp_path)+ src = tmp_path / "src"+ src.mkdir()+ (src / "entry.tsx").write_text("console.log('src')")+ os.utime(tmp_path / "dist" / "entry.js", (100, 100))+ os.utime(src / "entry.tsx", (200, 200))++ assert main_mod._tui_need_rebuild(tmp_path) is True+++ def test_make_tui_argv_skips_build_only_on_termux_when_fresh(+ tmp_path: Path, main_mod, monkeypatch+ ) -> None:+ _touch_tui_entry(tmp_path)+ monkeypatch.setenv("TERMUX_VERSION", "1")+ monkeypatch.setattr(main_mod, "_tui_need_npm_install", lambda _root: False)+ monkeypatch.setattr(main_mod, "_tui_need_rebuild", lambda _root: False)+ monkeypatch.setattr(main_mod.shutil, "which", lambda name: f"/bin/{name}")++ def fail_run(*_args, **_kwargs):+ raise AssertionError("fresh Termux TUI launch must not rebuild")++ monkeypatch.setattr(main_mod.subprocess, "run", fail_run)++ argv, cwd = main_mod._make_tui_argv(tmp_path, tui_dev=False)++ assert argv[1:] == ["--expose-gc", str(tmp_path / "dist" / "entry.js")]+ assert cwd == tmp_path+++ def test_make_tui_argv_skips_install_on_termux_when_bundle_fresh(+ tmp_path: Path, main_mod, monkeypatch+ ) -> None:+ _touch_tui_entry(tmp_path)+ monkeypatch.setenv("TERMUX_VERSION", "1")+ monkeypatch.setattr(main_mod, "_tui_need_npm_install", lambda _root: True)+ monkeypatch.setattr(main_mod, "_tui_need_rebuild", lambda _root: False)+ monkeypatch.setattr(main_mod.shutil, "which", lambda name: f"/bin/{name}")++ def fail_run(*_args, **_kwargs):+ raise AssertionError("fresh Termux TUI launch must not run npm")++ monkeypatch.setattr(main_mod.subprocess, "run", fail_run)++ argv, cwd = main_mod._make_tui_argv(tmp_path, tui_dev=False)++ assert argv[1:] == ["--expose-gc", str(tmp_path / "dist" / "entry.js")]+ assert cwd == tmp_path+++ def test_make_tui_argv_scopes_npm_install_on_termux_workspace(+ tmp_path: Path, main_mod, monkeypatch+ ) -> None:+ tui_dir = tmp_path / "ui-tui"+ tui_dir.mkdir()+ (tui_dir / "package.json").write_text("{}")+ ink_dir = tui_dir / "packages" / "hermes-ink"+ ink_dir.mkdir(parents=True)+ (ink_dir / "package.json").write_text("{}")+ (tmp_path / "package-lock.json").write_text("{}")++ monkeypatch.setenv("TERMUX_VERSION", "1")+ monkeypatch.setattr(main_mod, "_tui_need_npm_install", lambda _root: True)+ monkeypatch.setattr(main_mod, "_tui_need_rebuild", lambda _root: True)+ monkeypatch.setattr(main_mod.shutil, "which", lambda name: f"/bin/{name}")+ calls = []++ def fake_run(*args, **kwargs):+ calls.append((args, kwargs))+ return types.SimpleNamespace(returncode=0, stdout="", stderr="")++ monkeypatch.setattr(main_mod.subprocess, "run", fake_run)++ main_mod._make_tui_argv(tui_dir, tui_dev=False)++ install_cmd = calls[0][0][0]+ assert install_cmd[1:7] == [+ "install",+ "--workspace",+ "ui-tui",+ "--workspace",+ "ui-tui/packages/hermes-ink",+ "--include-workspace-root=false",+ ]+ assert calls[0][1]["cwd"] == str(tmp_path)+ _assert_utf8_replace_capture(calls[0][1])+ _assert_utf8_replace_capture(calls[1][1])++def test_make_tui_argv_keeps_desktop_workspace_install_behaviour(tmp_path: Path, main_mod, monkeypatch) -> None:diff --cc tests/tools/test_approval_timeout_overflow.pyindex 537cb973478,57649b4574b..82fc238312b--- a/tests/tools/test_approval_timeout_overflow.py+++ b/tests/tools/test_approval_timeout_overflow.py@@@ -77,11 -77,10 +77,16 @@@ class TestApprovalTimeoutOverflowClampmonkeypatch.setattr(builtins, "__import__", _blocked)with _with_configured_timeout(10**18):value = _get_approval_timeout()+ # Fail-closed contract: a FINITE cap below every platform's wait-+ # primitive limit (not a specific literal — see agent/deadline.py+ # for the platform-aware primary bound; the fallback stays below+ # the narrowest one, the Windows DWORD-ms cap).+ assert 0 < value < 0xFFFFFFFF / 1000.0+++ # The fallback mirrors the per-host MAX_SAFE_TIMEOUT_S ceiling+ # (imported BEFORE the block — the check itself must not depend on+ # the patched-away import).+ assert value == int(MAX_SAFE_TIMEOUT_S)# Still platform-safe for the crashing primitive.lock = threading.Lock()assert lock.acquire(timeout=value)diff --cc tests/tools/test_find_shell.pyindex 8184ae103c8,2947d4069f1..0b41f8be598--- a/tests/tools/test_find_shell.py+++ b/tests/tools/test_find_shell.py@@@ -102,37 -104,98 +104,37 @@@ class TestFindBashUnchangedassert len(result) > 0-class TestFindBashSkipsBrokenCustomPath:- """Stale HERMES_GIT_BASH_PATH must not brick Windows terminal startup."""-- @pytest.mark.platforms("windows")- def test_falls_through_to_portable_when_custom_fails_probe(self, tmp_path, monkeypatch):- """Windows-only: the candidate ladder (HERMES_GIT_BASH_PATH →- %LOCALAPPDATA%\\hermes\\git → Program Files) only exists in- ``_find_bash``'s Windows branch."""+class TestFindBashCollapsedToPmShell:+ """_find_bash is now a thin wrapper over pm.shell(); the Windows+ candidate ladder (HERMES_GIT_BASH_PATH → %LOCALAPPDATA%\\hermes\\git →+ Program Files) and the ASLR diagnostic were deleted — the store is the+ authority on bundled bash."""++ @pytest.mark.windows_only+ def test_delegates_to_pm_shell(self, monkeypatch):+ """_find_bash returns whatever pm.shell() resolves (store bash or+ provisioned PATH)."""import tools.environments.local as local_mod- local_mod._bash_starts_cache.clear()-- broken = tmp_path / "broken" / "bash.exe"- broken.parent.mkdir()- broken.write_text("", encoding="utf-8")- portable = tmp_path / "hermes" / "git" / "bin" / "bash.exe"- portable.parent.mkdir(parents=True)- portable.write_text("", encoding="utf-8")-- monkeypatch.setenv("HERMES_GIT_BASH_PATH", str(broken))- monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))-- def fake_starts(path: str) -> bool:- return path == str(portable)-- monkeypatch.setattr(local_mod, "_bash_starts", fake_starts)+ monkeypatch.setattr(+ "pm.shell.bash", lambda: r"C:\store\tools\git-x\usr\bin\bash.exe"+ )+ assert _find_bash() == r"C:\store\tools\git-x\usr\bin\bash.exe"- assert _find_bash() == str(portable)---class TestGitBashExternalProgramProbe:- """The Windows health check must exercise MSYS child-process creation."""-- def test_probe_runs_external_msys_programs(self, monkeypatch):- """``_bash_starts`` builds the same external-program probe argv on- every host, so this stays on the Linux runner with ``subprocess.run``- mocked — no platform faking needed."""+ def test_raises_when_pm_shell_finds_nothing(self, monkeypatch):+ """A store with no bash (and no PATH bash) surfaces a clear error+ pointing at `hermes pm install` instead of hunting locations."""import tools.environments.local as local_mod- local_mod._bash_starts_cache.clear()- local_mod._bash_probe_details_cache.clear()- calls = []-- def fake_run(argv, **kwargs):- calls.append((argv, kwargs))- return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")-- monkeypatch.setattr(local_mod.subprocess, "run", fake_run)-- assert local_mod._bash_starts(r"C:\Git\bin\bash.exe") is True- assert calls[0][0][-1] == "/usr/bin/true; /usr/bin/cat --version >/dev/null"-- @pytest.mark.platforms("windows")- def test_aslr_failure_surfaces_targeted_windows_command(- self, tmp_path, monkeypatch- ):- """Windows-only: the Mandatory-ASLR diagnostic is raised from- ``_find_bash``'s Windows candidate ladder and names PowerShell's- ``Set-ProcessMitigation`` — unreachable off Windows."""- import tools.environments.local as local_mod-- local_mod._bash_starts_cache.clear()- local_mod._bash_probe_details_cache.clear()- portable = tmp_path / "hermes" / "git" / "bin" / "bash.exe"- portable.parent.mkdir(parents=True)- portable.write_text("", encoding="utf-8")-- monkeypatch.setenv("HERMES_GIT_BASH_PATH", "")- monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))- monkeypatch.setenv("ProgramFiles", str(tmp_path / "empty-program-files"))- monkeypatch.delenv("ProgramFiles(x86)", raising=False)- monkeypatch.setattr(local_mod.shutil, "which", lambda _name: None)- monkeypatch.setattr(local_mod, "_mandatory_aslr_enabled", lambda: True)-- def failed_probe(path: str) -> bool:- local_mod._bash_probe_details_cache[path] = (- "dofork: child -1 - forked process died unexpectedly"- )- return False-- monkeypatch.setattr(local_mod, "_bash_starts", failed_probe)-+ monkeypatch.setattr("pm.shell.bash", lambda: None)with pytest.raises(RuntimeError) as exc_info:local_mod._find_bash()- message = str(exc_info.value)- assert "Mandatory ASLR" in message- assert "Reinstalling Git will not change" in message- assert "Set-ProcessMitigation" in message- assert str(tmp_path / "hermes" / "git") in message+ assert "No shell found" in str(exc_info.value)+ assert "hermes pm install" in str(exc_info.value)+- @pytest.mark.macos_only+ @pytest.mark.platforms("macos")@pytest.mark.skipif(not os.path.isfile("/bin/bash"),reason="reproduces the macOS system-bash-3.2 login-shell swallow",diff --cc tests/tools/test_local_tempdir.pyindex 093a04c515c,93377ff90a2..5e223207cc7--- a/tests/tools/test_local_tempdir.py+++ b/tests/tools/test_local_tempdir.py@@@ -4,19 -5,21 +5,21 @@@ import pytesclass TestLocalTempDir:+ @pytest.mark.platforms("linux")def test_uses_os_tmpdir_for_session_artifacts(self, monkeypatch):- monkeypatch.setenv("TMPDIR", "/data/data/com.termux/files/usr/tmp")+ monkeypatch.setenv("TMPDIR", "/var/host/tmp")monkeypatch.delenv("TMP", raising=False)monkeypatch.delenv("TEMP", raising=False)with patch.object(LocalEnvironment, "init_session", autospec=True, return_value=None):env = LocalEnvironment(cwd=".", timeout=10)- assert env.get_temp_dir() == "/data/data/com.termux/files/usr/tmp"- assert env._snapshot_path == f"/data/data/com.termux/files/usr/tmp/hermes-snap-{env._session_id}.sh"- assert env._cwd_file == f"/data/data/com.termux/files/usr/tmp/hermes-cwd-{env._session_id}.txt"+ assert env.get_temp_dir() == "/var/host/tmp"+ assert env._snapshot_path == f"/var/host/tmp/hermes-snap-{env._session_id}.sh"+ assert env._cwd_file == f"/var/host/tmp/hermes-cwd-{env._session_id}.txt"+ @pytest.mark.platforms("linux")def test_falls_back_to_tempfile_when_tmp_missing(self, monkeypatch):monkeypatch.delenv("TMPDIR", raising=False)monkeypatch.delenv("TMP", raising=False)diff --cc tools/approval.pyindex c97497aa511,d0abe1ea592..eeb78d8f416--- a/tools/approval.py+++ b/tools/approval.py@@@ -3524,11 -3541,11 +3548,12 @@@ def _get_approval_timeout() -> intsafe_cap = int(MAX_SAFE_TIMEOUT_S)except Exception:# Fail CLOSED: returning the raw value here would re-open the exact- # time_t overflow this clamp exists to prevent. Mirror the per-host- # ceiling of agent.deadline.MAX_SAFE_TIMEOUT_S — 1 year on POSIX,- # but the DWORD-millisecond ceiling on Windows (WaitForSingleObject- # caps at ~49.7 days; a year overflows it).- safe_cap = 4_294_907 if sys.platform == "win32" else 365 * 24 * 3600+ # time_t overflow this clamp exists to prevent. Use the conservative+ # cross-platform bound — below the Windows DWORD-millisecond cap+ # (~49.7 days) so the fallback is safe even where the platform-aware+ # constant cannot be read.+ safe_cap = 40 * 24 * 3600 # 40 days < 0xFFFFFFFF ms / 1000++if raw > safe_cap:logger.warning("approvals.timeout=%s exceeds the platform-safe maximum; "diff --cc uv.lockindex fb9ab7b83c6,89047b226b9..64dca2171eb--- a/uv.lock+++ b/uv.lock@@@ -51,9 -51,10 +51,10 @@@ boto3 = falsruamel-yaml = falsesherpa-onnx = falsehuggingface-hub = false+ slack-bolt = falsepytest-asyncio = false+google-cloud-pubsub = falseslack-sdk = false-unpaddedbase64 = falsediscord-py = falsehoncho-ai = falsefaster-whisper = false@@@ -1806,7 -1763,7 +1816,9 @@@ dev ={ name = "mcp" },{ name = "pytest" },{ name = "pytest-asyncio" },- { name = "pytest-xdist" },++{ name = "pytest-xdist" },+ { name = "resvg-py" },++{ name = "ruff" },{ name = "setuptools" },{ name = "starlette" },