Skip to content

The agent that grows with you

fix: CI python-tests backlog — no import-time dependency syncs, CI-shaped test fixtures

ethernet925c08cecafc
diff --git a/agent/bedrock_adapter.py b/agent/bedrock_adapter.py
index 512811e82d2..1e039f80851 100644
--- a/agent/bedrock_adapter.py
+++ b/agent/bedrock_adapter.py
@@ -22,19 +22,6 @@ import httpx
logger = logging.getLogger(__name__)
-# ---------------------------------------------------------------------------
-# Ensure boto3/botocore are installed before any code in this module runs.
-# Upstream removed boto3 from [all] extras (PRs #24220, #24515); pm
-# handles on-demand installation so the Bedrock provider still works in the
-# EKS deployment without baking boto3 into the base image.
-# ---------------------------------------------------------------------------
-try:
- from pm import ensure_import
- ensure_import("bedrock")
-except Exception as exc: # downstream imports surface the real error
- logger.warning("boto3 lazy install did not complete: %s", exc)
-
-
_bedrock_runtime_client_cache: Dict[str, Any] = {}
_bedrock_control_client_cache: Dict[str, Any] = {}
# Routed multiplex profiles: one client per (profile home, region). boto3 freezes the credential
@@ -77,6 +64,14 @@ _MIN_BOTO3_VERSION = (1, 34, 59)
def _require_boto3():
"""Import boto3; converse_stream() needs >= 1.34.59 (a system boto3 can shadow the venv pin)."""
try:
+ # boto3 left [all] (PRs #24220, #24515); PM installs the [bedrock] extra on first use. This
+ # runs at the first client build, never at import: an import-time sync would rebuild the
+ # dependency environment of whatever process happens to import this module.
+ try:
+ from pm import ensure_import
+ ensure_import("bedrock")
+ except Exception as exc: # the import below reports the real failure
+ logger.warning("boto3 lazy install did not complete: %s", exc)
import boto3
except ImportError:
raise ImportError(
diff --git a/agent/vertex_adapter.py b/agent/vertex_adapter.py
index cf0554acbfa..8022b3134cd 100644
--- a/agent/vertex_adapter.py
+++ b/agent/vertex_adapter.py
@@ -15,15 +15,6 @@ from typing import Any, Optional, Tuple
from agent.secret_scope import get_secret as _get_secret, is_multiplex_active
-# Ensure google-auth is installed before importing. The [vertex] extra is no
-# longer in [all] per the lazy-install policy added 2026-05-12 — pm
-# handles on-demand installation so the Vertex provider still works for users
-# who installed plain `hermes-agent` and only later selected a Gemini model.
-try:
- from pm import ensure_import as _ensure_import
- _ensure_import("vertex")
-except Exception:
- pass # pm unavailable or install failed — fall through to the real ImportError below
try:
import google.auth
import google.auth.transport.requests
@@ -31,6 +22,31 @@ try:
except ImportError:
google = None # type: ignore[assignment]
+
+def _ensure_google_auth() -> bool:
+ """Bind ``google.auth`` on first use, installing the [vertex] extra through PM if needed.
+
+ The extra left [all] under the lazy-install policy (2026-05-12) so a plain ``hermes-agent``
+ install still reaches Vertex after selecting a Gemini model. This runs at the first
+ credential request, never at import: an import-time sync would rebuild the dependency
+ environment of whatever process happens to import this module.
+ """
+ global google, service_account
+ if google is not None:
+ return True
+ try:
+ from pm import ensure_import
+ ensure_import("vertex")
+ import google.auth as _auth # noqa: F401 — rebinding the module globals below
+ import google.auth.transport.requests # noqa: F401
+ from google.oauth2 import service_account as _service_account
+ except Exception as exc:
+ logger.warning("google-auth package not installed (%s). Cannot use Vertex AI.", exc)
+ return False
+ import google as _google
+ google, service_account = _google, _service_account
+ return True
+
logger = logging.getLogger(__name__)
DEFAULT_REGION = "global"
@@ -131,8 +147,7 @@ def _needs_refresh(creds) -> bool:
def get_vertex_credentials(credentials_path: Optional[str] = None) -> Tuple[Optional[str], Optional[str]]:
"""Return (fresh access_token, project_id) or (None, None); Credentials cached per file content."""
- if google is None:
- logger.warning("google-auth package not installed. Cannot use Vertex AI.")
+ if not _ensure_google_auth():
return None, None
resolved_path = _resolve_credentials_path(credentials_path)
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.py
index 144b59de883..10b11ac0569 100644
--- a/plugins/platforms/matrix/adapter.py
+++ b/plugins/platforms/matrix/adapter.py
@@ -728,7 +728,7 @@ def ensure_matrix_deps() -> bool:
forever and broke E2EE connect with ``No module named 'asyncpg'``
(#31116). Rebinds module-level type globals on success.
"""
- from pm.extras import ensure_and_bind
+ from pm import extras
def _import():
from mautrix.types import (
@@ -744,7 +744,9 @@ def ensure_matrix_deps() -> bool:
"UserID": UserID,
}
- if not ensure_and_bind("matrix", _import, globals()):
+ # A complete install (module-level imports already bound the types) needs no sync; only a
+ # partial one goes through ensure_and_bind, which rebinds after the install.
+ if extras.missing("matrix") and not extras.ensure_and_bind("matrix", _import, globals()):
logger.warning(
"Matrix: required packages not installed or need a restart. "
"Run `hermes pm install`, then restart Hermes."
diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh
index 62a0f247d1d..4137437dc42 100755
--- a/scripts/run_tests.sh
+++ b/scripts/run_tests.sh
@@ -108,21 +108,6 @@ if [ -f "$HOME/.hermes/pytest_live_guard.py" ]; then
fi
-# ── Real-home PATH entries (computed before we drop env) ────────────────────
-# An installed Hermes puts ~/.hermes/{bin,node/bin} on the shell PATH. Tests
-# run under the real-home I/O tripwire, so a `shutil.which()` walking those
-# entries fails as "I/O against the REAL hermes home" — CI has none of them.
-TEST_PATH=""
-_IFS_SAVE="$IFS"; IFS=':'
-for _entry in $PATH; do
- case "$_entry" in
- "$HOME/.hermes"|"$HOME/.hermes/"*) ;;
- *) TEST_PATH="${TEST_PATH:+$TEST_PATH:}$_entry" ;;
- esac
-done
-IFS="$_IFS_SAVE"
-
-
# ── Windows location variables (computed before we drop env) ───────────────
# `env -i` forwards HOME, which is enough on POSIX. Native Windows CPython
# resolves Path.home() from USERPROFILE (or HOMEDRIVE+HOMEPATH), stdlib
@@ -202,7 +187,7 @@ echo "▶ pre-compiling bytecode cache"
echo "▶ launching test runner"
exec env -i \
- PATH="$TEST_PATH" \
+ PATH="$PATH" \
HOME="$HOME" \
${WIN_ENV[@]+"${WIN_ENV[@]}"} \
${TEST_ENV[@]+"${TEST_ENV[@]}"} \
diff --git a/tests-js/scripts/desktop-smoke-process.ts b/tests-js/scripts/desktop-smoke-process.ts
index d8ce5aabf51..4ccdb79bd11 100644
--- a/tests-js/scripts/desktop-smoke-process.ts
+++ b/tests-js/scripts/desktop-smoke-process.ts
@@ -4,6 +4,8 @@ import path from 'node:path'
import { z } from 'zod'
+import { within } from '../../tests/install/e2e-assets/smoke-env.mjs'
+
export interface NativeProcess {
pid: number
parentPid: number
@@ -24,11 +26,6 @@ export interface OriginEvidence {
appReportedRoot?: string
}
-export function within(root: string, candidate: string): boolean {
- const relative = path.relative(fs.realpathSync(root), fs.realpathSync(candidate))
- return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
-}
-
function nativeText(command: string, args: string[]): string {
return execFileSync(command, args, { encoding: 'utf8', timeout: 30_000, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }).trim()
}
diff --git a/tests/agent/test_codex_cloudflare_headers.py b/tests/agent/test_codex_cloudflare_headers.py
index c49309d4db9..08748a836e3 100644
--- a/tests/agent/test_codex_cloudflare_headers.py
+++ b/tests/agent/test_codex_cloudflare_headers.py
@@ -100,7 +100,7 @@ class TestCodexCloudflareHeaders:
def test_residency_header_from_jwt_claims(self, monkeypatch):
"""#23896: residency-enforced workspaces 401 without x-openai-internal-codex-residency.
chatgpt_data_residency wins; chatgpt_compute_residency is the fallback; and the two
- models-catalog probes (picker via httpx, context-length via requests) send it on the
+ models-catalog probes (picker via httpx, context-length via model_metadata_http) send it on the
wire — not just the shared helper."""
import sys
@@ -122,14 +122,15 @@ class TestCodexCloudflareHeaders:
class _FakeHttp:
@staticmethod
- def get(url, headers=None, timeout=None, verify=None):
+ def get(url, headers=None, timeout=None, verify=None, **kwargs):
sent.append(dict(headers or {}))
return _FakeResp()
monkeypatch.setitem(sys.modules, "httpx", _FakeHttp)
codex_models._fetch_models_from_api(access_token=compute_only)
- monkeypatch.setattr(model_metadata, "requests", _FakeHttp)
- monkeypatch.setattr(model_metadata, "_ensure_requests", lambda: None)
+ # The context-length probe goes through the shared model_metadata_http seam.
+ from agent import model_metadata_http
+ monkeypatch.setattr(model_metadata_http, "get", _FakeHttp.get)
monkeypatch.setattr(model_metadata, "_codex_oauth_context_cache", {})
model_metadata._fetch_codex_oauth_context_lengths_with_source(compute_only)
diff --git a/tests/agent/test_model_metadata.py b/tests/agent/test_model_metadata.py
index 60afd8d8763..849a5f2dfe2 100644
--- a/tests/agent/test_model_metadata.py
+++ b/tests/agent/test_model_metadata.py
@@ -716,7 +716,7 @@ class TestCodexOAuthContextLength:
fake_response = MagicMock()
fake_response.status_code = 200
fake_response.json.return_value = {"models": [item]}
- with patch("agent.model_metadata.requests.get", return_value=fake_response), \
+ with patch("agent.model_metadata_http.get", return_value=fake_response), \
patch("agent.model_metadata.get_cached_context_length", return_value=None), \
patch("agent.model_metadata.save_context_length"):
ctx = get_model_context_length(
@@ -737,7 +737,7 @@ class TestCodexOAuthContextLength:
fake_response.json.return_value = {
"models": [{"slug": "gpt-5.6-sol", "context_window": 272_000, "max_context_window": 872_000}]
}
- with patch("agent.model_metadata.requests.get", return_value=fake_response), \
+ with patch("agent.model_metadata_http.get", return_value=fake_response), \
patch("agent.model_metadata.get_cached_context_length", return_value=None), \
patch("agent.model_metadata.save_context_length"):
ctx = get_model_context_length(
diff --git a/tests/gateway/test_systemd_notify.py b/tests/gateway/test_systemd_notify.py
index c4765b715f7..2b7c818998c 100644
--- a/tests/gateway/test_systemd_notify.py
+++ b/tests/gateway/test_systemd_notify.py
@@ -10,7 +10,7 @@ import pytest
pytestmark = pytest.mark.platforms("linux")
[email protected]("linux") # abstract (NUL-prefixed) AF_UNIX names are a Linux kernel feature
+# abstract (NUL-prefixed) AF_UNIX names are a Linux kernel feature
def test_notify_supports_systemd_abstract_socket(monkeypatch):
name = "\0hermes-test-notify"
receiver = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
diff --git a/tests/hermes_cli/conftest.py b/tests/hermes_cli/conftest.py
index 273cc6d2ca8..9958b10a534 100644
--- a/tests/hermes_cli/conftest.py
+++ b/tests/hermes_cli/conftest.py
@@ -116,4 +116,15 @@ def _reset_prompt_toolkit_output_cache():
yield
_clear()
-
+def probe_root(tmp_path):
+ """A fixture checkout the installation launcher can boot from.
+
+ ``runtime_command`` prepends the checkout root and runs ``import hermes_bootstrap``
+ before the probe body, exactly as production does. Tests that point the import
+ guard at a scratch tree need that module present, or the probe dies before its
+ health marker — a developer venv whose editable ``.pth`` shadows the root hides
+ the dependency, CI's clean environment does not.
+ """
+ (tmp_path / "hermes_bootstrap.py").write_text("", encoding="utf-8")
+ return tmp_path
diff --git a/tests/hermes_cli/test_update_autostash.py b/tests/hermes_cli/test_update_autostash.py
index 0848ee42749..03ad2592bd8 100644
--- a/tests/hermes_cli/test_update_autostash.py
+++ b/tests/hermes_cli/test_update_autostash.py
@@ -110,9 +110,11 @@ def test_rescue_retention_uses_real_refs(tmp_path, monkeypatch, mode):
('terminated', 'import os\nos._exit(7)\n', ('consumer',), 'exit code 7'),
('paths', 'VALUE = 2\n', (), 'restored Python source discovery'),
])
-def test_restore_validates_real_stash_and_each_import(tmp_path, monkeypatch, capsys, fault, body, modules, message):
+def test_restore_validates_real_stash_and_each_import(probe_root, monkeypatch, capsys, fault, body, modules, message):
import hermes_cli.update_cmd_stash as stash
+ tmp_path = probe_root
+
git(tmp_path, 'init', '-q', '-b', 'main')
(tmp_path / 'first.py').write_text("raise RuntimeError('missing local config')\n", encoding='utf-8')
source = tmp_path / 'consumer.py'
diff --git a/tests/hermes_cli/test_update_import_guard.py b/tests/hermes_cli/test_update_import_guard.py
index 8a23f891c90..2a760a5ab8b 100644
--- a/tests/hermes_cli/test_update_import_guard.py
+++ b/tests/hermes_cli/test_update_import_guard.py
@@ -40,9 +40,9 @@ def _write_skewed_tree(root: Path, *, skewed: bool) -> None:
(root / "consumer.py").write_text("from provider.thing import SHARED_NAME\n")
-def test_syntax_guard_passes_but_import_guard_catches_skew(monkeypatch, tmp_path):
+def test_syntax_guard_passes_but_import_guard_catches_skew(monkeypatch, probe_root):
"""The regression: a skewed tree parses cleanly but cannot be imported."""
- _write_skewed_tree(tmp_path, skewed=True)
+ _write_skewed_tree(probe_root, skewed=True)
# Both files are valid Python -- the syntax guard sees nothing wrong.
# NOTE: patch update_cmd's global, not hermes_main's. Both modules expose
@@ -53,43 +53,43 @@ def test_syntax_guard_passes_but_import_guard_catches_skew(monkeypatch, tmp_path
monkeypatch.setattr(
update_cmd, "_UPDATE_CRITICAL_FILES", ("consumer.py", "provider/thing.py")
)
- syntax_ok, _, _ = update_cmd._validate_critical_files_syntax(tmp_path)
+ syntax_ok, _, _ = update_cmd._validate_critical_files_syntax(probe_root)
assert syntax_ok, "sanity: the skewed tree must parse cleanly"
# The import guard catches it.
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
- ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)
+ ok, module, error = update_cmd._validate_critical_modules_import(probe_root)
assert ok is False
assert module == "consumer"
assert error is not None and "SHARED_NAME" in error
-def test_import_guard_passes_on_consistent_tree(monkeypatch, tmp_path):
- _write_skewed_tree(tmp_path, skewed=False)
+def test_import_guard_passes_on_consistent_tree(monkeypatch, probe_root):
+ _write_skewed_tree(probe_root, skewed=False)
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
- assert update_cmd._validate_critical_modules_import(tmp_path) == (True, None, None)
+ assert update_cmd._validate_critical_modules_import(probe_root) == (True, None, None)
-def test_import_guard_ignores_non_import_errors(monkeypatch, tmp_path):
+def test_import_guard_ignores_non_import_errors(monkeypatch, probe_root):
"""A module that raises at import time for config/env reasons is not
update breakage -- the guard must not roll back a good update."""
- (tmp_path / "consumer.py").write_text(
+ (probe_root / "consumer.py").write_text(
"raise RuntimeError('no API key configured')\n"
)
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
- ok, _, _ = update_cmd._validate_critical_modules_import(tmp_path)
+ ok, _, _ = update_cmd._validate_critical_modules_import(probe_root)
assert ok is True
-def test_import_guard_can_report_non_import_errors(monkeypatch, tmp_path):
+def test_import_guard_can_report_non_import_errors(monkeypatch, probe_root):
"""Stash restore can compare runtime failures before and after apply."""
- (tmp_path / "consumer.py").write_text("raise RuntimeError('broken config')\n")
+ (probe_root / "consumer.py").write_text("raise RuntimeError('broken config')\n")
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
ok, module, error = update_cmd._validate_critical_modules_import(
- tmp_path, report_runtime_errors=True
+ probe_root, report_runtime_errors=True
)
assert ok is False
@@ -98,14 +98,14 @@ def test_import_guard_can_report_non_import_errors(monkeypatch, tmp_path):
def test_import_guard_can_report_missing_third_party_dependency(
- monkeypatch, tmp_path
+ monkeypatch, probe_root
):
"""Stash comparison must see newly introduced missing dependencies."""
- (tmp_path / "consumer.py").write_text("import totally_not_installed_pkg\n")
+ (probe_root / "consumer.py").write_text("import totally_not_installed_pkg\n")
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
ok, module, error = update_cmd._validate_critical_modules_import(
- tmp_path, report_runtime_errors=True
+ probe_root, report_runtime_errors=True
)
assert ok is False
@@ -113,16 +113,16 @@ def test_import_guard_can_report_missing_third_party_dependency(
assert error is not None and "totally_not_installed_pkg" in error
-def test_import_failure_comparison_preserves_exception_type(monkeypatch, tmp_path):
- source = tmp_path / "consumer.py"
+def test_import_failure_comparison_preserves_exception_type(monkeypatch, probe_root):
+ source = probe_root / "consumer.py"
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
source.write_text("raise RuntimeError('stopped')\n")
runtime_failure = update_cmd._critical_module_import_failures(
- tmp_path, report_runtime_errors=True
+ probe_root, report_runtime_errors=True
)
source.write_text("raise SystemExit('stopped')\n")
terminating_failure = update_cmd._critical_module_import_failures(
- tmp_path, report_runtime_errors=True
+ probe_root, report_runtime_errors=True
)
assert runtime_failure == {"consumer": ("RuntimeError", "stopped")}
@@ -130,14 +130,14 @@ def test_import_failure_comparison_preserves_exception_type(monkeypatch, tmp_pat
def test_import_guard_reports_probe_termination_when_comparing_states(
- monkeypatch, tmp_path
+ monkeypatch, probe_root
):
"""A terminating import is unsafe when validating a restored stash."""
- (tmp_path / "consumer.py").write_text("import os\nos._exit(7)\n")
+ (probe_root / "consumer.py").write_text("import os\nos._exit(7)\n")
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
ok, module, error = update_cmd._validate_critical_modules_import(
- tmp_path, report_runtime_errors=True
+ probe_root, report_runtime_errors=True
)
assert ok is False
@@ -145,33 +145,33 @@ def test_import_guard_reports_probe_termination_when_comparing_states(
assert error == "terminated before reporting import health (exit code 7)"
-def test_import_guard_reports_probe_termination_by_default(monkeypatch, tmp_path):
+def test_import_guard_reports_probe_termination_by_default(monkeypatch, probe_root):
"""A missing health marker must not classify a terminated probe as healthy."""
- (tmp_path / "consumer.py").write_text("import os\nos._exit(9)\n")
+ (probe_root / "consumer.py").write_text("import os\nos._exit(9)\n")
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
- ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)
+ ok, module, error = update_cmd._validate_critical_modules_import(probe_root)
assert ok is False
assert module == "critical-module probe"
assert error == "terminated before reporting import health (exit code 9)"
-def test_import_guard_reports_system_exit_by_default(monkeypatch, tmp_path):
+def test_import_guard_reports_system_exit_by_default(monkeypatch, probe_root):
"""Catchable terminating imports must not complete with a healthy marker."""
- (tmp_path / "consumer.py").write_text("raise SystemExit('stopped')\n")
+ (probe_root / "consumer.py").write_text("raise SystemExit('stopped')\n")
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
- ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)
+ ok, module, error = update_cmd._validate_critical_modules_import(probe_root)
assert ok is False
assert module == "consumer"
assert error == "stopped"
-def test_import_guard_does_not_accept_forged_static_marker(monkeypatch, tmp_path):
+def test_import_guard_does_not_accept_forged_static_marker(monkeypatch, probe_root):
"""Imported stdout cannot impersonate the per-probe completion marker."""
- (tmp_path / "consumer.py").write_text(
+ (probe_root / "consumer.py").write_text(
"import os, sys\n"
"sys.stdout.write('__HERMES_IMPORT_HEALTH__[]')\n"
"sys.stdout.flush()\n"
@@ -179,14 +179,14 @@ def test_import_guard_does_not_accept_forged_static_marker(monkeypatch, tmp_path
)
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
- ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)
+ ok, module, error = update_cmd._validate_critical_modules_import(probe_root)
assert ok is False
assert module == "critical-module probe"
assert error == "terminated before reporting import health (exit code 7)"
-def test_import_guard_rejects_malformed_health_payload(monkeypatch, tmp_path):
+def test_import_guard_rejects_malformed_health_payload(monkeypatch, probe_root):
class Result:
returncode = 0
stdout = ""
@@ -198,14 +198,14 @@ def test_import_guard_rejects_malformed_health_payload(monkeypatch, tmp_path):
monkeypatch.setattr("secrets.token_hex", lambda size: "fixture")
monkeypatch.setattr(update_cmd.subprocess, "run", malformed)
- ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)
+ ok, module, error = update_cmd._validate_critical_modules_import(probe_root)
assert ok is False
assert module == "critical-module probe"
assert error == "reported malformed import health data"
-def test_import_guard_reports_probe_timeout(monkeypatch, tmp_path):
+def test_import_guard_reports_probe_timeout(monkeypatch, probe_root):
import subprocess
def timeout(*_args, **_kwargs):
@@ -213,35 +213,35 @@ def test_import_guard_reports_probe_timeout(monkeypatch, tmp_path):
monkeypatch.setattr(update_cmd_validation.subprocess, "run", timeout)
- ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)
+ ok, module, error = update_cmd._validate_critical_modules_import(probe_root)
assert ok is False
assert module == "critical-module probe"
assert error == "timed out before reporting import health"
-def test_untracked_enumeration_failure_is_visible(monkeypatch, tmp_path, capsys):
+def test_untracked_enumeration_failure_is_visible(monkeypatch, probe_root, capsys):
class Result:
returncode = 1
stdout = ""
monkeypatch.setattr(update_cmd.subprocess, "run", lambda *_a, **_kw: Result())
- assert update_cmd._git_untracked_paths(["git"], tmp_path) is None
+ assert update_cmd._git_untracked_paths(["git"], probe_root) is None
assert "Could not enumerate untracked files" in capsys.readouterr().out
@pytest.mark.platforms("posix")
-def test_import_guard_is_non_fatal_when_probe_cannot_run(tmp_path):
+def test_import_guard_is_non_fatal_when_probe_cannot_run(probe_root):
"""A venv interpreter that exists but cannot be executed must not read as a hung probe:
spawn failure stays advisory (real ``bounded_probe_run``, real ``Popen``)."""
- venv_python = tmp_path / "venv" / "bin" / "python"
+ venv_python = probe_root / "venv" / "bin" / "python"
venv_python.parent.mkdir(parents=True)
venv_python.write_text("#!/bin/sh\nexit 0\n")
venv_python.chmod(0o644) # present, not executable -> Popen raises PermissionError
- assert update_cmd._validate_critical_modules_import(tmp_path) == (True, None, None)
+ assert update_cmd._validate_critical_modules_import(probe_root) == (True, None, None)
# ---------------------------------------------------------------------------
@@ -274,27 +274,27 @@ def test_hint_stays_silent_for_unrelated_failures(exc):
assert partial_update_hint(exc) == []
-def test_import_guard_ignores_missing_third_party_dependency(monkeypatch, tmp_path):
+def test_import_guard_ignores_missing_third_party_dependency(monkeypatch, probe_root):
"""A new third-party requirement is not a partially-updated tree.
On the git path this guard runs BEFORE the dependency sync, so a release
that adds a dependency would otherwise look like breakage and trigger a
spurious `git reset --hard` rollback of a perfectly good update.
"""
- (tmp_path / "consumer.py").write_text("import totally_not_installed_pkg\n")
+ (probe_root / "consumer.py").write_text("import totally_not_installed_pkg\n")
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
- assert update_cmd._validate_critical_modules_import(tmp_path) == (True, None, None)
+ assert update_cmd._validate_critical_modules_import(probe_root) == (True, None, None)
-def test_import_guard_flags_missing_first_party_module(monkeypatch, tmp_path):
+def test_import_guard_flags_missing_first_party_module(monkeypatch, probe_root):
"""A missing *first-party* module IS skew — the update dropped a file."""
- (tmp_path / "tools").mkdir()
- (tmp_path / "tools" / "__init__.py").write_text("")
- (tmp_path / "consumer.py").write_text("import tools.nonexistent_module\n")
+ (probe_root / "tools").mkdir()
+ (probe_root / "tools" / "__init__.py").write_text("")
+ (probe_root / "consumer.py").write_text("import tools.nonexistent_module\n")
monkeypatch.setattr(update_cmd, "_UPDATE_CRITICAL_MODULES", ("consumer",))
- ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)
+ ok, module, error = update_cmd._validate_critical_modules_import(probe_root)
assert ok is False
assert module == "consumer"
assert error is not None and "tools.nonexistent_module" in error
diff --git a/tests/hermes_cli/test_update_launch_completion.py b/tests/hermes_cli/test_update_launch_completion.py
index d28c77fbe16..7fa588c59e6 100644
--- a/tests/hermes_cli/test_update_launch_completion.py
+++ b/tests/hermes_cli/test_update_launch_completion.py
@@ -13,7 +13,25 @@ from hermes_cli import venv_sync
from pm.environments import runtime_facts_path
-def test_first_launch_syncs_without_marker_then_uses_completion_fact(tmp_path, monkeypatch):
+def completion_tail(monkeypatch):
+ """Record the source-completion child prepare_launch spawns after a sync instead of running it.
+
+ The real child is ``hermes_cli/source_completion.py`` from the checkout under test — a
+ scratch tree here — building products with the selected interpreter; the tests below
+ cover the sync decision, not the build.
+ """
+ spawned = []
+
+ def call(command, **kwargs):
+ spawned.append(command)
+ return 0
+
+ monkeypatch.setattr(venv_sync.subprocess, "call", call)
+ return spawned
+
+
+def test_first_launch_syncs_without_marker_then_uses_completion_fact(tmp_path, monkeypatch, completion_tail):
import pm
from hermes_cli import _launchers
@@ -43,6 +61,7 @@ def test_first_launch_syncs_without_marker_then_uses_completion_fact(tmp_path, m
assert venv_sync.prepare_launch(root, []) == Path(sys.executable)
assert calls == [(["all"], {"explicit": True, "project_root": root})]
assert not (root / ".update-incomplete").exists()
+ assert any("source_completion.py" in str(part) for cmd in completion_tail for part in cmd)
assert venv_sync.prepare_launch(root, []) is None
assert len(calls) == 1
@@ -113,7 +132,7 @@ def test_failed_launch_keeps_previous_completion_and_retries(tmp_path, monkeypat
assert not (root / ".update-incomplete").exists()
-def test_blessed_legacy_install_is_adopted_before_sync(tmp_path, monkeypatch):
+def test_blessed_legacy_install_is_adopted_before_sync(tmp_path, monkeypatch, completion_tail):
import pm
from hermes_cli import _launchers
monkeypatch.setattr(Path, "home", lambda: tmp_path)
diff --git a/tests/hermes_cli/test_update_missing_configured_deps.py b/tests/hermes_cli/test_update_missing_configured_deps.py
index 3ee0aaa8e6c..a5a1db17093 100644
--- a/tests/hermes_cli/test_update_missing_configured_deps.py
+++ b/tests/hermes_cli/test_update_missing_configured_deps.py
@@ -40,6 +40,13 @@ def configured_update(source_launch, tmp_path, monkeypatch):
# offline while exercising the real selected-environment launch boundary.
for path in repository.iterdir():
if path.name in {"hermes_cli", "gateway", "agent", "tools", "plugins", "pm"} or path.suffix == ".py":
+ if (root / path.name).exists():
+ # source_launch already stubs hermes_cli/source_completion.py; link the rest of that
+ # package's modules beside it.
+ for module in path.iterdir():
+ if not (root / path.name / module.name).exists():
+ (root / path.name / module.name).symlink_to(module, target_is_directory=module.is_dir())
+ continue
(root / path.name).symlink_to(path, target_is_directory=path.is_dir())
def build_in_child():
script = (
diff --git a/tests/home_io_guard.py b/tests/home_io_guard.py
index daebdb8f32c..1a03190b73f 100644
--- a/tests/home_io_guard.py
+++ b/tests/home_io_guard.py
@@ -8,8 +8,13 @@ import os
from pathlib import Path
import shutil
import sqlite3
+import sys
import threading
+_INTERPRETER_PREFIXES = tuple({
+ Path(p).resolve() for p in (sys.prefix, sys.base_prefix, sys.exec_prefix, sys.base_exec_prefix)
+})
+
class HomeIOGuard:
def __init__(self, roots):
@@ -22,7 +27,14 @@ class HomeIOGuard:
return
self.checking.active = True
try:
- candidate = Path(os.fsdecode(value)).expanduser()
+ candidate = Path(os.fsdecode(value))
+ if candidate.parts and candidate.parts[0].startswith("~"):
+ # A test may have patched Path.expanduser to fail; the guard must not
+ # turn that into its own crash — the unexpanded path is checked instead.
+ try:
+ candidate = candidate.expanduser()
+ except Exception:
+ pass
if dir_fd is not None and not candidate.is_absolute():
parent = self.directories.get(dir_fd)
if parent is None:
@@ -39,6 +51,17 @@ class HomeIOGuard:
# probe) reads no state; only its contents are guarded.
if metadata and absolute in roots:
return
+ # ``shutil.which`` stats/accesses ``<PATH entry>/<name>``. A developer shell puts
+ # PM's tool store (~/.hermes/tools/...) on PATH; probing an executable there is
+ # command lookup, not reading Hermes state. CI has no such entries.
+ if metadata and any(absolute.parent == entry for entry in self._path_entries()):
+ return
+ # The interpreter's own installation (a PM-managed python under ~/.hermes/tools):
+ # stdlib source reads (linecache, traceback) are not Hermes state either, nor is
+ # realpath() walking up through its ancestors.
+ if any(absolute.is_relative_to(prefix) or (metadata and prefix.is_relative_to(absolute))
+ for prefix in _INTERPRETER_PREFIXES):
+ return
# Check the lexical path first: resolving must not probe a protected
# tree merely to decide that the original path was forbidden.
if any(absolute.is_relative_to(root) for root in roots):
@@ -46,6 +69,9 @@ class HomeIOGuard:
resolved = absolute.resolve()
if metadata and resolved in roots:
return
+ # A fixture symlink to the running interpreter resolves into its installation.
+ if any(resolved.is_relative_to(prefix) for prefix in _INTERPRETER_PREFIXES):
+ return
if any(resolved.is_relative_to(root) for root in roots):
self.refuse(value)
finally:
@@ -58,6 +84,10 @@ class HomeIOGuard:
"Use the isolated HERMES_HOME or a temporary fixture instead."
)
+ @staticmethod
+ def _path_entries():
+ return [Path(os.path.abspath(entry)) for entry in os.environ.get("PATH", "").split(os.pathsep) if entry]
+
def install(self, monkeypatch):
def wrap(module, name, parameters, *, metadata=False):
original = getattr(module, name)
diff --git a/tests/install/e2e-assets/desktop-smoke.ts b/tests/install/e2e-assets/desktop-smoke.ts
index 37d7acffef6..a1a0a29373b 100644
--- a/tests/install/e2e-assets/desktop-smoke.ts
+++ b/tests/install/e2e-assets/desktop-smoke.ts
@@ -11,7 +11,8 @@ import { z } from 'zod'
import { resolveDesktopHermesHome } from '../../../apps/desktop/electron/data-paths.mjs'
import { applyBundleEnvironment } from '../../../apps/desktop/scripts/bundle-env.mjs'
import { readChatIdentity, runDesktopChatSmoke, waitForChatReady } from '../../../tests-js/scripts/desktop-chat-smoke.ts'
-import { assertBackendOrigin, localBackendProcess, readBundledBundleEnv, readInstallationCommit, within } from '../../../tests-js/scripts/desktop-smoke-process.ts'
+import { assertBackendOrigin, localBackendProcess, readBundledBundleEnv, readInstallationCommit } from '../../../tests-js/scripts/desktop-smoke-process.ts'
+import { type SmokeEnvironment, smokeEnvironment, within } from './smoke-env.mjs'
import { validateMockUrl, writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config.ts'
import { type MockServer, startMockServer } from '../../../tests-js/scripts/mock-server.ts'
@@ -34,16 +35,6 @@ const launchSpecSchema = z.object({
env: z.record(z.string(), z.string()), matchedShape: z.enum(['source', 'packaged']),
})
-interface SmokeEnvironment extends Record<string, string> {
- HOME: string
- USERPROFILE: string
- HERMES_HOME: string
- HERMES_DESKTOP_USER_DATA_DIR: string
- XDG_CONFIG_HOME: string
- XDG_DATA_HOME: string
- XDG_CACHE_HOME: string
-}
-
interface Launch {
executablePath: string
args: string[]
@@ -63,30 +54,7 @@ interface ElectronProcess extends NodeJS.Process {
resourcesPath: string
}
-export function smokeEnvironment(inherited: NodeJS.ProcessEnv, home: string, userData: string): SmokeEnvironment {
- const clean: Record<string, string> = {}
- const keepHermes = new Set(['HERMES_TEST_INSTALL_REF', 'HERMES_TEST_INSTALL_REPO'])
- for (const [key, value] of Object.entries(inherited)) {
- const name = key.toUpperCase()
- if (!value || /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/.test(name)
- || /^(?:PYTHON|VIRTUAL_ENV|CONDA|NODE_|NPM_|ELECTRON_|VITE_|UV_|PM_)/.test(name)
- || /^(?:OPENAI|ANTHROPIC|OPENROUTER|OLLAMA|GEMINI|GROQ|XAI)_/.test(name)
- || (name.startsWith('HERMES_') && !keepHermes.has(name))
- || ['INIT_CWD', 'TERMINAL_CWD', 'LD_PRELOAD', 'DYLD_INSERT_LIBRARIES', 'SSH_AUTH_SOCK', 'SSH_ASKPASS', 'GIT_ASKPASS'].includes(name)) {
- continue
- }
- clean[key] = value
- }
- return {
- ...clean, HOME: path.join(home, '.desktop-smoke-home'), USERPROFILE: path.join(home, '.desktop-smoke-home'),
- XDG_CONFIG_HOME: path.join(home, '.desktop-smoke-home', '.config'),
- XDG_DATA_HOME: path.join(home, '.desktop-smoke-home', '.local', 'share'),
- XDG_CACHE_HOME: path.join(home, '.desktop-smoke-home', '.cache'),
- HERMES_HOME: home, HERMES_DESKTOP_USER_DATA_DIR: userData,
- APPDATA: path.join(home, '.desktop-smoke-home', 'AppData', 'Roaming'),
- LOCALAPPDATA: path.join(home, '.desktop-smoke-home', 'AppData', 'Local'),
- }
-}
+export { smokeEnvironment }
/** The bundled app resolves its Hermes home the same way electron/data-paths.ts does:
* an explicit HERMES_HOME wins, but a bundle-env clear (HERMES_HOME=null) empties it before
diff --git a/tests/install/e2e-assets/drive-update.cjs b/tests/install/e2e-assets/drive-update.cjs
index 1eeff0b8ddb..d3d8e68480a 100644
--- a/tests/install/e2e-assets/drive-update.cjs
+++ b/tests/install/e2e-assets/drive-update.cjs
@@ -60,7 +60,8 @@ const killer = setTimeout(() => {
killer.unref()
async function main() {
- const { runUpdateWindowChat, updateWindowEnvironment } = await import('./update-window-chat.mjs')
+ const { runUpdateWindowChat } = await import('./update-window-chat.mjs')
+ const { updateWindowEnvironment } = await import('./smoke-env.mjs')
const origin = nativeHandoff ? 'bundled' : 'source'
const root = nativeHandoff ? path.join(path.dirname(exePath), 'resources', 'agent-payload') : path.join(process.env.HERMES_HOME, 'hermes-agent')
log(`launching ${exePath}`)
diff --git a/tests/install/e2e-assets/launch-from-spec.mjs b/tests/install/e2e-assets/launch-from-spec.mjs
index 422a0ac1a56..043bd93d7c9 100644
--- a/tests/install/e2e-assets/launch-from-spec.mjs
+++ b/tests/install/e2e-assets/launch-from-spec.mjs
@@ -32,7 +32,8 @@ import { _electron } from '@playwright/test';
import { prepareWindowForInput } from './window-input.cjs';
import { pickAppWindow, openAbout, waitForUpdate } from './update-ui.cjs';
import { observeSourceUpdate } from './source-update-observer.mjs';
-import { runUpdateWindowChat, updateWindowEnvironment } from './update-window-chat.mjs';
+import { runUpdateWindowChat } from './update-window-chat.mjs';
+import { updateWindowEnvironment } from './smoke-env.mjs';
/**
* @typedef {{argv: string[], cwd: string, env: Record<string, string>,
diff --git a/tests/install/e2e-assets/mac-bundled-update-driver.mjs b/tests/install/e2e-assets/mac-bundled-update-driver.mjs
index c17e316bd0b..bcd3f400c8f 100644
--- a/tests/install/e2e-assets/mac-bundled-update-driver.mjs
+++ b/tests/install/e2e-assets/mac-bundled-update-driver.mjs
@@ -23,7 +23,8 @@ import path from 'node:path';
import { parseArgs } from 'node:util';
import { _electron } from '@playwright/test';
import { createRequire } from 'node:module';
-import { runUpdateWindowChat, updateWindowEnvironment } from './update-window-chat.mjs';
+import { runUpdateWindowChat } from './update-window-chat.mjs';
+import { updateWindowEnvironment } from './smoke-env.mjs';
const require = createRequire(import.meta.url);
const { observeProcessClose } = require('./process-close.cjs');
diff --git a/tests/install/e2e-assets/smoke-env.d.mts b/tests/install/e2e-assets/smoke-env.d.mts
new file mode 100644
index 00000000000..3a9c40808b8
--- /dev/null
+++ b/tests/install/e2e-assets/smoke-env.d.mts
@@ -0,0 +1,15 @@
+export interface SmokeEnvironment extends Record<string, string> {
+ HOME: string
+ USERPROFILE: string
+ HERMES_HOME: string
+ HERMES_DESKTOP_USER_DATA_DIR: string
+ XDG_CONFIG_HOME: string
+ XDG_DATA_HOME: string
+ XDG_CACHE_HOME: string
+ APPDATA: string
+ LOCALAPPDATA: string
+}
+
+export function within(root: string, candidate: string): boolean
+export function smokeEnvironment(inherited: NodeJS.ProcessEnv, home: string, userData: string): SmokeEnvironment
+export function updateWindowEnvironment(inherited: NodeJS.ProcessEnv, root: string, origin: 'source' | 'bundled'): SmokeEnvironment
diff --git a/tests/install/e2e-assets/smoke-env.mjs b/tests/install/e2e-assets/smoke-env.mjs
new file mode 100644
index 00000000000..8a1c3dbab60
--- /dev/null
+++ b/tests/install/e2e-assets/smoke-env.mjs
@@ -0,0 +1,93 @@
+// Environment shaping shared by the desktop smoke drivers and the source-update
+// window. Dependency-free on purpose: `tests/scripts/test_source_build_env.py`
+// runs it under a bare `node` with no workspace install, so nothing here may
+// import Playwright, zod, or the TypeScript smoke modules.
+import fs from 'node:fs';
+import path from 'node:path';
+
+/**
+ * @param {string} root
+ * @param {string} candidate
+ * @returns {boolean}
+ */
+export function within(root, candidate) {
+ const relative = path.relative(fs.realpathSync(root), fs.realpathSync(candidate));
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
+}
+
+/**
+ * The launch environment for an isolated desktop smoke: inherited display/toolchain
+ * variables minus credentials, driver activation, and every HERMES_* override.
+ * @param {NodeJS.ProcessEnv} inherited
+ * @param {string} home
+ * @param {string} userData
+ * @returns {Record<string, string> & {HOME: string, USERPROFILE: string, HERMES_HOME: string,
+ * HERMES_DESKTOP_USER_DATA_DIR: string, XDG_CONFIG_HOME: string, XDG_DATA_HOME: string, XDG_CACHE_HOME: string}}
+ */
+export function smokeEnvironment(inherited, home, userData) {
+ /** @type {Record<string, string>} */
+ const clean = {};
+ const keepHermes = new Set(['HERMES_TEST_INSTALL_REF', 'HERMES_TEST_INSTALL_REPO']);
+ for (const [key, value] of Object.entries(inherited)) {
+ const name = key.toUpperCase();
+ if (!value || /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/.test(name)
+ || /^(?:PYTHON|VIRTUAL_ENV|CONDA|NODE_|NPM_|ELECTRON_|VITE_|UV_|PM_)/.test(name)
+ || /^(?:OPENAI|ANTHROPIC|OPENROUTER|OLLAMA|GEMINI|GROQ|XAI)_/.test(name)
+ || (name.startsWith('HERMES_') && !keepHermes.has(name))
+ || ['INIT_CWD', 'TERMINAL_CWD', 'LD_PRELOAD', 'DYLD_INSERT_LIBRARIES', 'SSH_AUTH_SOCK', 'SSH_ASKPASS', 'GIT_ASKPASS'].includes(name)) {
+ continue;
+ }
+ clean[key] = value;
+ }
+ return {
+ ...clean, HOME: path.join(home, '.desktop-smoke-home'), USERPROFILE: path.join(home, '.desktop-smoke-home'),
+ XDG_CONFIG_HOME: path.join(home, '.desktop-smoke-home', '.config'),
+ XDG_DATA_HOME: path.join(home, '.desktop-smoke-home', '.local', 'share'),
+ XDG_CACHE_HOME: path.join(home, '.desktop-smoke-home', '.cache'),
+ HERMES_HOME: home, HERMES_DESKTOP_USER_DATA_DIR: userData,
+ APPDATA: path.join(home, '.desktop-smoke-home', 'AppData', 'Roaming'),
+ LOCALAPPDATA: path.join(home, '.desktop-smoke-home', 'AppData', 'Local'),
+ };
+}
+
+// Source updater processes still need the git redirect; smokeEnvironment keeps
+// it while removing driver activation, credentials and remote/backend overrides.
+/** @param {NodeJS.ProcessEnv} inherited @param {string} root @param {'source'|'bundled'} origin */
+export function updateWindowEnvironment(inherited, root, origin) {
+ const home = inherited.HERMES_HOME;
+ const userData = inherited.HERMES_DESKTOP_USER_DATA_DIR;
+ if (!home || !userData) throw new Error('Update chat requires isolated HERMES_HOME and HERMES_DESKTOP_USER_DATA_DIR');
+ const env = smokeEnvironment(inherited, home, userData);
+ // The detached source updater builds NEW in this environment too.
+ for (const key of ['GITHUB_SHA', 'GITHUB_REF', 'GITHUB_REF_NAME', 'GITHUB_HEAD_REF', 'GITHUB_BASE_REF']) {
+ delete env[key];
+ }
+ fs.mkdirSync(env.HOME, { recursive: true });
+ fs.mkdirSync(userData, { recursive: true });
+ for (const [filename, local] of [
+ ['connection.json', { mode: 'local' }],
+ ['connections.json', { primary: 'local', launchMode: 'primary', lastUsed: 'local' }],
+ ]) {
+ const file = path.join(userData, filename);
+ if (filename === 'connections.json' && !fs.existsSync(file)) continue;
+ const prior = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
+ fs.writeFileSync(file, JSON.stringify({ ...prior, ...local }), { mode: 0o600 });
+ }
+ if (origin === 'source') {
+ const editableRoot = inherited.HERMES_PYTHON_SRC_ROOT;
+ if (editableRoot) {
+ if (!path.isAbsolute(editableRoot) || fs.realpathSync(editableRoot) !== fs.realpathSync(root)) {
+ throw new Error('Captured HERMES_PYTHON_SRC_ROOT differs from the installed source');
+ }
+ env.HERMES_PYTHON_SRC_ROOT = editableRoot;
+ }
+ for (const key of ['HERMES_DESKTOP_PYTHON', 'HERMES_DESKTOP_HERMES', 'HERMES_DESKTOP_HERMES_ROOT']) {
+ if (inherited[key]) {
+ if (!path.isAbsolute(inherited[key]) || (key !== 'HERMES_DESKTOP_PYTHON' && !within(root, inherited[key]))) throw new Error(`Captured ${key} escapes the installed source`);
+ fs.accessSync(inherited[key]);
+ env[key] = inherited[key];
+ }
+ }
+ }
+ return env;
+}
diff --git a/tests/install/e2e-assets/update-window-chat.mjs b/tests/install/e2e-assets/update-window-chat.mjs
index b35eb49473e..ca6fe87fb10 100644
--- a/tests/install/e2e-assets/update-window-chat.mjs
+++ b/tests/install/e2e-assets/update-window-chat.mjs
@@ -3,50 +3,7 @@
import fs from 'node:fs';
import path from 'node:path';
import { readChatIdentity, runDesktopChatSmoke, waitForChatReady } from '../../../tests-js/scripts/desktop-chat-smoke.ts';
-import { assertBackendOrigin, localBackendProcess, readInstallationCommit, within } from '../../../tests-js/scripts/desktop-smoke-process.ts';
-import { smokeEnvironment } from './desktop-smoke.ts';
-
-// Source updater processes still need the git redirect; smokeEnvironment keeps
-// it while removing driver activation, credentials and remote/backend overrides.
-/** @param {NodeJS.ProcessEnv} inherited @param {string} root @param {'source'|'bundled'} origin */
-export function updateWindowEnvironment(inherited, root, origin) {
- const home = inherited.HERMES_HOME;
- const userData = inherited.HERMES_DESKTOP_USER_DATA_DIR;
- if (!home || !userData) throw new Error('Update chat requires isolated HERMES_HOME and HERMES_DESKTOP_USER_DATA_DIR');
- const env = smokeEnvironment(inherited, home, userData);
- // The detached source updater builds NEW in this environment too.
- for (const key of ['GITHUB_SHA', 'GITHUB_REF', 'GITHUB_REF_NAME', 'GITHUB_HEAD_REF', 'GITHUB_BASE_REF']) {
- delete env[key];
- }
- fs.mkdirSync(env.HOME, { recursive: true });
- fs.mkdirSync(userData, { recursive: true });
- for (const [filename, local] of [
- ['connection.json', { mode: 'local' }],
- ['connections.json', { primary: 'local', launchMode: 'primary', lastUsed: 'local' }],
- ]) {
- const file = path.join(userData, filename);
- if (filename === 'connections.json' && !fs.existsSync(file)) continue;
- const prior = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
- fs.writeFileSync(file, JSON.stringify({ ...prior, ...local }), { mode: 0o600 });
- }
- if (origin === 'source') {
- const editableRoot = inherited.HERMES_PYTHON_SRC_ROOT;
- if (editableRoot) {
- if (!path.isAbsolute(editableRoot) || fs.realpathSync(editableRoot) !== fs.realpathSync(root)) {
- throw new Error('Captured HERMES_PYTHON_SRC_ROOT differs from the installed source');
- }
- env.HERMES_PYTHON_SRC_ROOT = editableRoot;
- }
- for (const key of ['HERMES_DESKTOP_PYTHON', 'HERMES_DESKTOP_HERMES', 'HERMES_DESKTOP_HERMES_ROOT']) {
- if (inherited[key]) {
- if (!path.isAbsolute(inherited[key]) || (key !== 'HERMES_DESKTOP_PYTHON' && !within(root, inherited[key]))) throw new Error(`Captured ${key} escapes the installed source`);
- fs.accessSync(inherited[key]);
- env[key] = inherited[key];
- }
- }
- }
- return env;
-}
+import { assertBackendOrigin, localBackendProcess, readInstallationCommit } from '../../../tests-js/scripts/desktop-smoke-process.ts';
/**
* @param {import('@playwright/test').ElectronApplication} app
diff --git a/tests/pm/_fixtures.py b/tests/pm/_fixtures.py
index 147784bb4d6..730e6fbbb77 100644
--- a/tests/pm/_fixtures.py
+++ b/tests/pm/_fixtures.py
@@ -35,6 +35,26 @@ def _wheel(directory: Path, name: str, version: str = "1.0", requirements=()) ->
return wheel
+def stage_host_python(python: Path) -> Path:
+ """Place a runnable copy of the test host's interpreter at ``python`` (``<root>/bin/python…``).
+
+ CI's test interpreter is a relocatable python-build-standalone whose prefix is wherever the
+ binary sits, so a bare copy cannot find its stdlib (``No module named 'encodings'``). Copy the
+ host's stdlib beside it (a real copy, not a link: payload guards refuse links that escape the
+ tree); site-packages and the test suite stay out. Production's package stage ships the whole
+ distribution.
+ """
+ python.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(Path(sys._base_executable).resolve(), python)
+ host_lib = Path(sys.base_prefix) / "lib"
+ stdlib = next((d for d in host_lib.glob("python3.*") if (d / "os.py").is_file()), None)
+ if stdlib is not None and not (python.parent.parent / "lib" / stdlib.name).exists():
+ shutil.copytree(stdlib, python.parent.parent / "lib" / stdlib.name,
+ ignore=shutil.ignore_patterns("site-packages", "test", "__pycache__", "idlelib", "tkinter"),
+ symlinks=True)
+ return python
+
+
def _run(command, *, cwd: Path, env: dict) -> str:
result = subprocess.run(command, cwd=cwd, env=env, capture_output=True, text=True, timeout=60)
assert result.returncode == 0, result.stderr
diff --git a/tests/pm/test_cold_runtime_e2e.py b/tests/pm/test_cold_runtime_e2e.py
index 30679f8790a..671b054d40e 100644
--- a/tests/pm/test_cold_runtime_e2e.py
+++ b/tests/pm/test_cold_runtime_e2e.py
@@ -130,6 +130,12 @@ def test_cold_cli_builds_own_runtime_discovers_plugins_and_repairs_app(tmp_path,
with tarfile.open(archive, "w:gz", compresslevel=1) as tar:
for binary, name in files:
tar.add(binary, arcname=name)
+ if package.name == "python":
+ # A relocatable python-build-standalone finds its stdlib beside the binary, not at
+ # the host's prefix: ship the host's stdlib the way the real archive does.
+ stdlib = next(d for d in (Path(sys.base_prefix) / "lib").glob("python3.*") if (d / "os.py").is_file())
+ tar.add(stdlib, arcname=f"python/lib/{stdlib.name}",
+ filter=lambda info: None if any(part in info.name.split("/") for part in ("site-packages", "test", "__pycache__")) else info)
version = _run([str(files[0][0]), "--version"], cwd=tmp_path,
env=env).stdout.split()[1]
rows[package.name] = {
diff --git a/tests/pm/test_runtime_wheelhouse.py b/tests/pm/test_runtime_wheelhouse.py
index 97106e9aa44..11be6373b69 100644
--- a/tests/pm/test_runtime_wheelhouse.py
+++ b/tests/pm/test_runtime_wheelhouse.py
@@ -14,6 +14,7 @@ import pytest
from pm.runtime import runtime_environment
from scripts.bundles.payload import seal_pm_runtime
+from tests.pm._fixtures import stage_host_python
@pytest.fixture(scope="module")
@@ -60,9 +61,7 @@ def test_offline_wheelhouse_runtime_survives_sealing_and_move(
):
wheelhouse, versions = locked_wheelhouse
root = tmp_path / "payload"
- python = root / "tools/python/bin/python"
- python.parent.mkdir(parents=True)
- shutil.copy2(Path(sys._base_executable).resolve(), python)
+ python = stage_host_python(root / "tools/python/bin/python")
from pm import stage_manager_runtime
from pm.lock import _write
diff --git a/tests/scripts/test_agent_build.py b/tests/scripts/test_agent_build.py
index 3d27b69f102..c39056e7848 100644
--- a/tests/scripts/test_agent_build.py
+++ b/tests/scripts/test_agent_build.py
@@ -9,6 +9,7 @@ import subprocess
import sys
import pytest
+from tests.pm._fixtures import stage_host_python
ROOT = Path(__file__).resolve().parents[2]
@@ -28,9 +29,7 @@ def inputs_fixture(tmp_path):
(source / "skills").mkdir()
(source / "skills/data").write_text("resource", encoding="utf-8")
out = tmp_path / "payload"
- python = out / "tools/python/bin/python3"
- python.parent.mkdir(parents=True)
- shutil.copy2(Path(sys._base_executable).resolve(), python)
+ python = stage_host_python(out / "tools/python/bin/python3")
site = out / "venv/lib/python3.14/site-packages"
site.mkdir(parents=True)
(site / "dependency.py").write_text("VALUE = 'prepared'\n", encoding="utf-8")
diff --git a/tests/scripts/test_native_build.py b/tests/scripts/test_native_build.py
index 71a10242937..e8fb239b264 100644
--- a/tests/scripts/test_native_build.py
+++ b/tests/scripts/test_native_build.py
@@ -9,6 +9,7 @@ import subprocess
import sys
import pytest
+from tests.pm._fixtures import stage_host_python
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "scripts/bundles/native_build.py"
@@ -63,9 +64,7 @@ def test_native_cli_consumes_real_minimal_preparation_without_bootstrap(tmp_path
(code / "entry.py").write_text('def main():\n print("native fixture")\n return 0\n')
for name in RESOURCE_ENV:
(code / name).mkdir()
- python = out / "tools/python/bin/python3"
- python.parent.mkdir(parents=True)
- shutil.copy2(Path(getattr(sys, "_base_executable")).resolve(), python)
+ python = stage_host_python(out / "tools/python/bin/python3")
site = out / "venv/lib/site-packages"
site.mkdir(parents=True)
runtime = out / "pm-runtime"
diff --git a/tests/scripts/test_pm_build_consumers.py b/tests/scripts/test_pm_build_consumers.py
index 68d74e17108..745c55fd094 100644
--- a/tests/scripts/test_pm_build_consumers.py
+++ b/tests/scripts/test_pm_build_consumers.py
@@ -19,7 +19,11 @@ def local_toolchain(tmp_path, monkeypatch):
monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
-def test_ci_setup_exports_no_installer_path_or_policy(tmp_path, monkeypatch, local_toolchain):
+def test_ci_setup_exports_python_first_and_no_installer_policy(tmp_path, monkeypatch, local_toolchain):
+ """The CI toolchain exports PM's Python (a command environment) as HERMES_PYTHON and never
+ leaks installer policy (``UV_*``). uv itself IS placed on PATH — after the interpreter —
+ because the test suites this toolchain serves drive real uv through ``shutil.which("uv")``.
+ """
import importlib
from types import SimpleNamespace
from scripts.ci import setup_toolchain
@@ -35,9 +39,10 @@ def test_ci_setup_exports_no_installer_path_or_policy(tmp_path, monkeypatch, loc
composed.append(names)
return {"PATH": str(Path(sys.executable).parent)}
+ uv_binary = Path(shutil.which("uv"))
+
def package(name):
- assert name != "uv", "CI must not resolve an installer executable"
- return SimpleNamespace(binary=lambda *args: Path(sys.executable))
+ return SimpleNamespace(binary=lambda *args: uv_binary if name == "uv" else Path(sys.executable))
monkeypatch.setattr(manager, "env_for", environment)
monkeypatch.setattr("pm.registry.get_package", package)
@@ -50,10 +55,14 @@ def test_ci_setup_exports_no_installer_path_or_policy(tmp_path, monkeypatch, loc
assert composed == [("python",)]
outputs = dict(line.split("=", 1) for line in files["GITHUB_OUTPUT"].read_text(encoding="utf-8").splitlines())
exported = dict(line.split("=", 1) for line in files["GITHUB_ENV"].read_text(encoding="utf-8").splitlines())
- assert "uv-path" not in outputs
+ assert outputs["uv-path"] == str(uv_binary)
assert not any(name.startswith("UV_") for name in exported)
assert exported["HERMES_PYTHON"] == outputs["python-path"]
- assert Path(outputs["python-path"]).parent.as_posix() in files["GITHUB_PATH"].read_text(encoding="utf-8").replace("\\", "/")
+ path_entries = files["GITHUB_PATH"].read_text(encoding="utf-8").replace("\\", "/").splitlines()
+ python_dir = Path(outputs["python-path"]).parent.as_posix()
+ assert python_dir in path_entries
+ # GITHUB_PATH lines are prepended one by one, so the last line wins: python must be written after uv.
+ assert path_entries.index(python_dir) > path_entries.index(uv_binary.parent.as_posix())
subprocess.run([outputs["python-path"], "-I", "-c", "import sys; assert sys.prefix != sys.base_prefix"], check=True)
diff --git a/tests/scripts/test_source_build_env.py b/tests/scripts/test_source_build_env.py
index 3961dbcd72b..e88d3106f7a 100644
--- a/tests/scripts/test_source_build_env.py
+++ b/tests/scripts/test_source_build_env.py
@@ -77,7 +77,7 @@ if source_build_env "$PROBE_PYTHON" -I -S -c 'raise SystemExit(23)'; then exit 9
command = [shell, "--input-type=module", "-e", '''
import { pathToFileURL } from 'node:url';
import { spawnSync } from 'node:child_process';
-const { updateWindowEnvironment } = await import(pathToFileURL(process.env.ASSETS + '/update-window-chat.mjs'));
+const { updateWindowEnvironment } = await import(pathToFileURL(process.env.ASSETS + '/smoke-env.mjs'));
const env = updateWindowEnvironment(process.env, process.env.PROBE_ROOT, 'source');
const result = spawnSync(process.env.PROBE_PYTHON, ['-I', '-S', process.env.PROBE_SCRIPT], { env, stdio: 'inherit' });
if (result.error || result.status !== 0) throw new Error(`stamp child failed: ${result.error || result.status}`);
diff --git a/tests/tui_gateway/conftest.py b/tests/tui_gateway/conftest.py
new file mode 100644
index 00000000000..06ee7de640d
--- /dev/null
+++ b/tests/tui_gateway/conftest.py
@@ -0,0 +1,10 @@
+"""tui_gateway test fixtures.
+
+Several files here import ``tui_gateway.server`` inside a ``patch.dict("sys.modules", {"hermes_constants":
+MagicMock(...)})`` window so the module binds a fixed home. The server's import graph reaches
+``agent.process_bootstrap`` → ``hermes_bootstrap``, which is process boot: PM dependency activation reads
+the real install root through ``hermes_constants`` and exits the process when that is a MagicMock.
+Importing it once here, before any window opens, keeps boot out of the mocked import.
+"""
+
+import hermes_bootstrap # noqa: F401
diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.py
index 2f653393054..c528126fcbf 100644
--- a/tests/tui_gateway/test_protocol.py
+++ b/tests/tui_gateway/test_protocol.py
@@ -36,9 +36,6 @@ def server():
# from sys.modules and a test's own ``from tui_gateway import server_requests`` would get a fresh,
# unbound copy whose default sinks drop frames and treat every client as answerable.
import tui_gateway.server_requests # noqa: F401
- # hermes_bootstrap is process boot (PM dependency activation reads the real install root);
- # its first import must not happen while hermes_constants is a MagicMock.
- import hermes_bootstrap # noqa: F401
with patch.dict("sys.modules", {
"hermes_constants": MagicMock(get_hermes_home=MagicMock(return_value="/tmp/hermes_test")),
"hermes_cli.env_loader": MagicMock(),
diff --git a/tools/browser_tool.py b/tools/browser_tool.py
index f86836569f6..d8e8bbdb8e8 100644
--- a/tools/browser_tool.py
+++ b/tools/browser_tool.py
@@ -35,11 +35,6 @@ _BROWSER_PASSTHROUGH_KEYS: tuple[str, ...] = (
)
-def warm_agent_browser_npx_cache(timeout: float = 60.0) -> bool:
- # Shim to stop the old updater doing work until relaunch. Nothing was warmed.
- return False
-
-
def _build_browser_env() -> dict:
"""Credential-scrubbed env for an agent-browser subprocess (deferred import: test
harnesses stub the ``tools`` package). The passthrough keys are re-added from the active