Skip to content

The agent that grows with you

test: consolidate backend contracts around real caller boundaries

ethernet657bc3682dc4
diff --git a/tests/agent/lsp/test_install_and_lint_fixes.py b/tests/agent/lsp/test_install_and_lint_fixes.py
index e6f0e3f74e4..c3c61e52832 100644
--- a/tests/agent/lsp/test_install_and_lint_fixes.py
+++ b/tests/agent/lsp/test_install_and_lint_fixes.py
@@ -45,32 +45,6 @@ def test_install_python_server_uses_pm_tool_environment(tmp_path, monkeypatch):
assert install_mod.detect_status("fake-lsp") == "installed"
-# ---------------------------------------------------------------------------
-# Fix 2: ``hermes lsp status`` surfaces shellcheck-missing for bash
-# ---------------------------------------------------------------------------
-
-
-
-
-
-
-def test_backend_warnings_fires_when_bash_installed_but_shellcheck_missing(tmp_path, monkeypatch):
- """The exact scenario from the bug report."""
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- from agent.lsp import cli as lsp_cli
-
- def which(name):
- if name == "bash-language-server":
- return "/fake/bin/bash-language-server"
- return None # shellcheck missing
-
- with patch("shutil.which", side_effect=which):
- notes = lsp_cli._backend_warnings()
- assert len(notes) == 1
- assert "shellcheck" in notes[0].lower()
- assert "bash-language-server" in notes[0].lower()
-
-
def test_status_output_includes_backend_warnings_section(tmp_path, monkeypatch):
"""End-to-end: status command output includes the warning section."""
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
@@ -90,19 +64,7 @@ def test_status_output_includes_backend_warnings_section(tmp_path, monkeypatch):
output = buf.getvalue()
assert "Backend warnings" in output
assert "shellcheck" in output
-
-
-# ---------------------------------------------------------------------------
-# Fix 3: tier-1 lint treats unusable linters as ``skipped``, not ``error``
-# ---------------------------------------------------------------------------
-
-
-
-
-
-
-
-
+ assert "bash-language-server" in output
def test_check_lint_returns_error_for_real_ts_type_errors(tmp_path, monkeypatch):
diff --git a/tests/agent/lsp/test_python_discovery.py b/tests/agent/lsp/test_python_discovery.py
index 5cd716e1ad4..0c95c1d2d99 100644
--- a/tests/agent/lsp/test_python_discovery.py
+++ b/tests/agent/lsp/test_python_discovery.py
@@ -1,19 +1,15 @@
"""Pyright uses the project environment before the Hermes runtime fallback."""
-import json
import os
import subprocess
import sys
from pathlib import Path
-import pm
from pm import paths
from pm.lock import Facts, Lockfile
from pm.registry import get_package
from pm.store import current_target
-from agent.lsp.servers import _detect_python
-
def _seed_pm_python(tmp_path, monkeypatch):
"""Stage a pm bundled-install layout: HERMES_RUNTIME_DIR -> store with a
@@ -41,79 +37,6 @@ def _seed_pm_python(tmp_path, monkeypatch):
return exe
-def test_pyright_respects_pm_writable_selection_over_old_bundle(tmp_path, monkeypatch):
- monkeypatch.delenv("VIRTUAL_ENV", raising=False)
- bundled = _seed_pm_python(tmp_path, monkeypatch)
- bundled_facts = Facts(paths.facts_path())
- old = bundled_facts.get("python")
- assert old is not None
- store = paths.writable_store_root()
- package = get_package("python")
- target = current_target()
- entry = store / old["entry"]
- binary = package.binary(entry, target)
- assert binary is not None
- binary.parent.mkdir(parents=True)
- binary.write_text("", encoding="utf-8")
- Facts(store / "facts.json").record(
- "python", old["version"], entry.name, package.env(entry, target), store,
- target=target, artifacts=old["artifacts"],
- )
- bundled_facts.record(
- "python", "old-bundle", old["entry"], {}, paths.store_root(),
- target=target, artifacts=old["artifacts"],
- )
- before = paths.facts_path().read_bytes(), (store / "facts.json").read_bytes()
- selected = pm.installed_package("python")
- assert selected is not None and selected.binary == binary
- assert _detect_python(str(tmp_path / "workspace")) == str(binary)
- assert (paths.facts_path().read_bytes(), (store / "facts.json").read_bytes()) == before
- assert bundled.is_file()
-
-
-def test_pm_store_python_resolved_without_virtual_env(tmp_path, monkeypatch):
- """No VIRTUAL_ENV anywhere — the pm store interpreter is the answer."""
- monkeypatch.delenv("VIRTUAL_ENV", raising=False)
- exe = _seed_pm_python(tmp_path, monkeypatch)
-
- assert _detect_python(str(tmp_path / "some-workspace")) == str(exe)
-
-
-def test_no_pm_python_falls_back_to_project_layouts(tmp_path, monkeypatch):
- """Without a pm python fact, project .venv candidates still resolve."""
- monkeypatch.delenv("VIRTUAL_ENV", raising=False)
- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "no-such-store"))
-
- dot_venv_bin = tmp_path / "proj" / ".venv" / "bin"
- dot_venv_bin.mkdir(parents=True)
- python = dot_venv_bin / "python"
- python.write_text("", encoding="utf-8")
-
- assert Path(_detect_python(str(tmp_path / "proj"))) == python
-
-
-def test_missing_store_entry_is_not_an_answer(tmp_path, monkeypatch):
- """A python fact whose store entry is gone resolves to None (pm only
- vouches for what is on disk)."""
- monkeypatch.delenv("VIRTUAL_ENV", raising=False)
- payload = tmp_path / "payload"
- store = payload / "tools"
- store.mkdir(parents=True)
- (payload / "manifest.json").write_text("{}", encoding="utf-8")
- (store / "facts.json").write_text(
- json.dumps(
- {
- "schema": 1,
- "packages": {"python": {"entry": "python-3.11.13", "version": "3.11.13"}},
- }
- ),
- encoding="utf-8",
- )
- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
-
- assert _detect_python(str(tmp_path / "some-workspace")) is None
-
-
def test_pyright_uses_the_project_interpreter_before_hermes(tmp_path, monkeypatch):
from agent.lsp import servers
@@ -131,6 +54,11 @@ def test_pyright_uses_the_project_interpreter_before_hermes(tmp_path, monkeypatc
assert spec is not None
assert spec.initialization_options["python"]["pythonPath"] == str(pm_python)
+ pm_python.unlink()
+ spec = server.build_spawn(str(project), context)
+ assert spec is not None
+ assert "pythonPath" not in spec.initialization_options.get("python", {})
+
for environment in (project / ".venv", tmp_path / "explicit-environment"):
subprocess.run(
[sys.executable, "-m", "venv", "--without-pip", str(environment)],
diff --git a/tests/agent/metadata_transport.py b/tests/agent/metadata_transport.py
new file mode 100644
index 00000000000..075778dfc79
--- /dev/null
+++ b/tests/agent/metadata_transport.py
@@ -0,0 +1,21 @@
+"""Socket-free response data for tests that exercise the real metadata transport."""
+import httpx
+import pytest
+
+
+def metadata_transport(monkeypatch):
+ from agent import model_metadata
+
+ responses, requests = [], []
+ real_client = httpx.Client
+
+ def handle(request):
+ requests.append(request)
+ return responses.pop(0)
+
+ monkeypatch.setattr(httpx, "Client", lambda **kw: real_client(
+ **kw, transport=httpx.MockTransport(handle),
+ ))
+ monkeypatch.setattr(model_metadata, "detect_local_server_type", lambda *a, **kw: None)
+ return responses, requests
diff --git a/tests/agent/test_custom_provider_ca_probes.py b/tests/agent/test_custom_provider_ca_probes.py
index 155200cb86b..ab83eeacef7 100644
--- a/tests/agent/test_custom_provider_ca_probes.py
+++ b/tests/agent/test_custom_provider_ca_probes.py
@@ -1,299 +1,79 @@
-"""Custom-provider TLS settings must reach the /models and pricing probes.
-
-Regression coverage for provider-scoped ``ssl_ca_cert`` / ``ssl_verify`` being
-ignored by the discovery/pricing probes. Two probe families share the root
-cause and are covered here:
-
-* HTTPX endpoint metadata / pricing probe
- (``agent.model_metadata.fetch_endpoint_model_metadata`` via
- ``resolve_verify``).
-* ``urllib``-based ``/models`` catalog discovery probe
- (``hermes_cli.models.probe_api_models`` via ``_custom_provider_ssl_context``).
-
-Both previously resolved TLS from process-wide env vars only, so a custom
-endpoint whose chain verifies against the provider's configured bundle (but not
-``SSL_CERT_FILE``) logged a spurious CERTIFICATE_VERIFY_FAILED on every probe
-even though the chat client succeeded.
-
-No network I/O: real CA-bundle stand-in files via ``tmp_path`` plus a patched
-provider list and a patched request seam.
-"""
-
-from __future__ import annotations
-
-from contextlib import contextmanager
+"""Probe-specific policy edges; real TLS handshakes live in test_ssl_transport_contracts."""
import ssl
-import urllib.error
from unittest.mock import MagicMock, patch
-import certifi
import pytest
from agent.model_metadata_http import resolve_verify
-from agent.ssl_verify import resolve_httpx_verify
from hermes_cli.models import _custom_provider_ssl_context
-_CA_ENV_VARS = (
- "HERMES_CA_BUNDLE",
- "REQUESTS_CA_BUNDLE",
- "SSL_CERT_FILE",
- "CURL_CA_BUNDLE",
-)
-
_BASE = "https://relay.example.invalid/v1"
@pytest.fixture
def clean_env(monkeypatch):
- """Clear the CA env vars so each test starts from a known state."""
- for var in _CA_ENV_VARS:
- monkeypatch.delenv(var, raising=False)
+ for key in ("HERMES_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "SSL_CERT_FILE", "SSL_CERT_DIR", "CURL_CA_BUNDLE"):
+ monkeypatch.delenv(key, raising=False)
return monkeypatch
-def bundle_file(tmp_path):
- path = tmp_path / "provider-ca.pem"
- from pathlib import Path
- path.write_bytes(Path(certifi.where()).read_bytes())
- return str(path)
-
-
-def real_ca():
- """Both probe transports parse this actual bundle before connecting."""
- return certifi.where()
-
-
-def _providers(base_url, **tls):
- entry = {"name": "relay", "base_url": base_url}
- entry.update(tls)
- return [entry]
-
-
-class TestResolveVerifyProviderScoped:
- """Provider configuration resolves before the probe's transport is built."""
-
- def test_provider_ca_used_for_matching_base_url(self, clean_env, bundle_file):
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=_providers(_BASE, ssl_ca_cert=bundle_file),
- ):
- assert resolve_verify(_BASE) is resolve_httpx_verify(ca_bundle=bundle_file)
-
- def test_provider_ca_overrides_env_ssl_cert_file(self, clean_env, tmp_path, bundle_file):
- env_bundle = tmp_path / "env-ca.pem"
- env_bundle.write_text("stub")
- clean_env.setenv("SSL_CERT_FILE", str(env_bundle))
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=_providers(_BASE, ssl_ca_cert=bundle_file),
- ):
- assert resolve_verify(_BASE) is resolve_httpx_verify(ca_bundle=bundle_file)
-
- def test_provider_ssl_verify_false_disables(self, clean_env):
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=_providers(_BASE, ssl_verify=False),
- ):
- assert resolve_verify(_BASE) is False
-
- def test_no_base_url_does_not_consult_config(self, clean_env, bundle_file):
- """Existing callers pass no base_url — no config read, and env never steers trust."""
- clean_env.setenv("HERMES_CA_BUNDLE", bundle_file)
- probe = MagicMock(return_value=[])
- with patch("hermes_cli.config.get_compatible_custom_providers", probe):
- assert resolve_verify() is True
- probe.assert_not_called()
-
- def test_unmatched_base_url_env_ignored_returns_true(self, clean_env, bundle_file):
- """An unmatched base_url and an ambient CA env var both leave trust at the OS store."""
- clean_env.setenv("REQUESTS_CA_BUNDLE", bundle_file)
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=_providers("https://other.example.invalid/v1", ssl_ca_cert="/nope.pem"),
- ):
- assert resolve_verify(_BASE) is True
-
- def test_unmatched_base_url_no_env_returns_true(self, clean_env):
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=[],
- ):
- assert resolve_verify(_BASE) is True
-
- def test_provider_ca_missing_file_keeps_platform_trust(self, clean_env):
- """A configured bundle that does not exist warns and verifies against the OS store —
- an ambient ``SSL_CERT_FILE`` does not become the fallback authority."""
- clean_env.setenv("SSL_CERT_FILE", "/does/not/matter.pem")
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=_providers(_BASE, ssl_ca_cert="/does/not/exist.pem"),
- ):
- context = resolve_verify(_BASE)
- assert type(context).__module__.startswith("truststore")
- assert context.verify_mode == ssl.CERT_REQUIRED
-
- def test_config_lookup_failure_keeps_platform_trust(self, clean_env):
- """A config crash must not silently swap in an ambient env var as trust authority."""
- clean_env.setenv("SSL_CERT_FILE", "/does/not/matter.pem")
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- side_effect=RuntimeError("config boom"),
- ):
- context = resolve_verify(_BASE)
- assert type(context).__module__.startswith("truststore")
- assert context.verify_mode == ssl.CERT_REQUIRED
-
-
-class TestCustomProviderSSLContext:
- """``_custom_provider_ssl_context`` — the urllib /models discovery path."""
-
- def test_returns_verifying_context_with_provider_ca(self, real_ca):
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=_providers(_BASE, ssl_ca_cert=real_ca),
- ):
- ctx = _custom_provider_ssl_context(_BASE)
- assert ctx is resolve_httpx_verify(ca_bundle=real_ca)
- assert ctx.verify_mode == ssl.CERT_REQUIRED
-
- def test_ssl_verify_false_returns_unverified_context(self):
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=_providers(_BASE, ssl_verify=False),
- ):
- ctx = _custom_provider_ssl_context(_BASE)
- assert isinstance(ctx, ssl.SSLContext)
- assert ctx.check_hostname is False
- assert ctx.verify_mode == ssl.CERT_NONE
-
- def test_no_base_url_returns_none(self):
- assert _custom_provider_ssl_context("") is None
-
- def test_unmatched_returns_none(self):
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=[],
- ):
- assert _custom_provider_ssl_context(_BASE) is None
-
- def test_missing_ca_file_returns_none(self):
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=_providers(_BASE, ssl_ca_cert="/does/not/exist.pem"),
- ):
- assert _custom_provider_ssl_context(_BASE) is None
-
- def test_config_lookup_failure_returns_none(self):
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- side_effect=RuntimeError("config boom"),
- ):
- assert _custom_provider_ssl_context(_BASE) is None
-
-
-class TestMetadataProbeThreadsProviderCA:
- @pytest.mark.parametrize("pinned", [False, True])
- def test_provider_policy_reaches_the_transport(self, clean_env, real_ca, pinned):
- import httpx
- from agent import model_metadata as mm
- from agent import model_metadata_http
- from agent.ssl_verify import resolve_httpx_verify
-
- @contextmanager
- def response(*args, **kwargs):
- yield httpx.Response(200, json={"data": []}, request=httpx.Request("GET", args[0]))
-
- mm._endpoint_model_metadata_cache.clear()
- mm._endpoint_model_metadata_cache_time.clear()
- providers = _providers(_BASE, ssl_ca_cert=real_ca) if pinned else []
- with patch("hermes_cli.config.get_compatible_custom_providers", return_value=providers), \
- patch.object(model_metadata_http, "stream", side_effect=response) as stream:
- assert mm.fetch_endpoint_model_metadata(_BASE, force_refresh=True) == {}
- expected = resolve_httpx_verify(ca_bundle=real_ca) if pinned else True
- assert stream.call_args.kwargs["verify"] is expected
-
-
-class TestCatalogProbeThreadsSSLContext:
- """End-to-end: the urllib catalog probe carries the provider SSL context."""
-
- @pytest.fixture(autouse=True)
- def _clear_probe_neg_cache(self):
- import hermes_cli.models as models
-
- models._probe_neg_cache.clear()
- yield
- models._probe_neg_cache.clear()
-
- def test_probe_api_models_passes_ssl_context(self, clean_env, real_ca):
- import hermes_cli.models as models
-
- captured = {}
-
- def fake_open(req, *, timeout, ssl_context=None):
- captured["ssl_context"] = ssl_context
- raise urllib.error.URLError("stop after capture")
-
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=_providers(_BASE, ssl_ca_cert=real_ca),
- ), patch.object(models, "open_credentialed_url", side_effect=fake_open):
- models.probe_api_models(None, _BASE, timeout=1)
-
- assert captured["ssl_context"] is resolve_httpx_verify(ca_bundle=real_ca)
- assert captured["ssl_context"].verify_mode == ssl.CERT_REQUIRED
-
- def test_probe_api_models_public_endpoint_uses_default_policy(self, clean_env):
- import hermes_cli.models as models
-
- captured = {}
-
- def fake_open(req, *, timeout, ssl_context=None):
- captured["ssl_context"] = ssl_context
- raise urllib.error.URLError("stop after capture")
-
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=[],
- ), patch.object(models, "open_credentialed_url", side_effect=fake_open):
- models.probe_api_models(None, _BASE, timeout=1)
-
- assert captured["ssl_context"] is None
-
- def test_public_endpoint_calls_seam_without_ssl_context_kwarg(self, clean_env):
- """A public endpoint must not pass ssl_context to the call seam.
-
- Regression guard: threading ssl_context unconditionally broke existing
- call-seam mocks whose signature is ``(req, timeout=...)``. The probe
- must keep the original 2-arg call shape when no per-provider override
- applies, so a strict 2-arg mock still works.
- """
- import hermes_cli.models as models
-
- class _Resp:
- def __enter__(self):
- return self
-
- def __exit__(self, exc_type, exc, tb):
- return False
-
- def read(self):
- return b'{"data": [{"id": "local-model"}]}'
-
- calls = []
-
- def _strict_two_arg(req, timeout=5.0):
- calls.append(req.full_url)
- return _Resp()
-
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=[],
- ), patch.object(
- models, "_urlopen_model_catalog_request", side_effect=_strict_two_arg
- ):
- probe = models.probe_api_models("key", "http://localhost:8000", timeout=1)
-
- assert probe["models"] == ["local-model"]
- assert calls == ["http://localhost:8000/models"]
[email protected]("case", ["no-url", "unmatched", "missing-ca", "config-error"])
[email protected]("ambient", [False, True])
+def test_probe_policy_edges(clean_env, case, ambient):
+ if ambient:
+ clean_env.setenv("SSL_CERT_FILE", "/does/not/exist.pem")
+ providers = MagicMock(return_value=[{
+ "name": "test", "base_url": _BASE if case != "unmatched" else "https://other.invalid",
+ "ssl_ca_cert": "/missing-provider.pem",
+ }])
+ if case == "config-error":
+ providers.side_effect = RuntimeError("config unavailable")
+ url = "" if case == "no-url" else _BASE
+ with patch("hermes_cli.config.get_compatible_custom_providers", providers):
+ verify = resolve_verify(url)
+ context = _custom_provider_ssl_context(url)
+ assert context is (verify if ambient else None)
+ if ambient:
+ assert verify.verify_mode == ssl.CERT_REQUIRED and verify.check_hostname
+ else:
+ assert verify is True
+ if not url:
+ providers.assert_not_called()
+
+
+def test_public_endpoint_calls_seam_without_ssl_context_kwarg(clean_env):
+ """A public endpoint must not pass ssl_context to the call seam.
+
+ Regression guard: threading ssl_context unconditionally broke existing
+ call-seam mocks whose signature is ``(req, timeout=...)``. The probe
+ must keep the original 2-arg call shape when no per-provider override
+ applies, so a strict 2-arg mock still works.
+ """
+ import hermes_cli.models as models
+
+ class _Resp:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc, tb):
+ return False
+
+ def read(self):
+ return b'{"data": [{"id": "local-model"}]}'
+
+ calls = []
+
+ def _strict_two_arg(req, timeout=5.0):
+ calls.append(req.full_url)
+ return _Resp()
+
+ with patch(
+ "hermes_cli.config.get_compatible_custom_providers",
+ return_value=[],
+ ), patch.object(
+ models, "_urlopen_model_catalog_request", side_effect=_strict_two_arg
+ ):
+ probe = models.probe_api_models("key", "http://localhost:8000", timeout=1)
+
+ assert probe["models"] == ["local-model"]
+ assert calls == ["http://localhost:8000/models"]
diff --git a/tests/agent/test_model_metadata.py b/tests/agent/test_model_metadata.py
index 0bb0e197735..927e748bb12 100644
--- a/tests/agent/test_model_metadata.py
+++ b/tests/agent/test_model_metadata.py
@@ -11,7 +11,7 @@ Coverage levels:
"""
import time
-from contextlib import contextmanager
+from tests.agent.metadata_transport import metadata_transport # noqa: F401
import pytest
import hermes_yaml as yaml
@@ -752,117 +752,26 @@ class TestCodexOAuthContextLength:
# =========================================================================
class TestFetchEndpointModelMetadata:
- @pytest.fixture(autouse=True)
- def streamed_responses(self, monkeypatch):
- from agent import model_metadata_http
-
- @contextmanager
- def stream(*args, **kwargs):
- response = model_metadata_http.get(*args, **kwargs)
- try:
- yield response
- finally:
- response.close()
-
- monkeypatch.setattr(model_metadata_http, "stream", stream)
-
def setup_method(self):
import agent.model_metadata as mm
mm._endpoint_model_metadata_cache.clear()
mm._endpoint_model_metadata_cache_time.clear()
- @pytest.mark.parametrize("status_code", [401, 403])
- def test_auth_failure_stops_after_first_candidate(self, status_code):
+ def test_remote_probe_is_memoized_on_disk_across_processes(self, tmp_path, monkeypatch, metadata_transport):
+ import httpx
import agent.model_metadata as mm
- response = MagicMock()
- response.status_code = status_code
- response.raise_for_status.side_effect = RuntimeError(str(status_code))
-
- with patch("agent.model_metadata_http.get", return_value=response) as mock_get:
- result = mm.fetch_endpoint_model_metadata("https://custom.example/v1")
-
- assert result == {}
- mock_get.assert_called_once()
- response.read.assert_not_called()
- response.raise_for_status.assert_not_called()
- response.json.assert_not_called()
- response.close.assert_called_once()
-
- def test_auth_failure_empty_result_is_cached(self):
- import agent.model_metadata as mm
-
- response = MagicMock()
- response.status_code = 401
- response.raise_for_status.side_effect = RuntimeError("401")
-
- with patch("agent.model_metadata_http.get", return_value=response) as mock_get:
- first = mm.fetch_endpoint_model_metadata("https://custom.example/v1")
- second = mm.fetch_endpoint_model_metadata("https://custom.example/v1")
-
- assert first == second == {}
- mock_get.assert_called_once()
- response.close.assert_called_once()
-
- def test_not_found_still_tries_alternate_candidate(self):
- import agent.model_metadata as mm
-
- not_found = MagicMock()
- not_found.status_code = 404
- not_found.raise_for_status.side_effect = RuntimeError("404")
- success = MagicMock()
- success.status_code = 200
- success.json.return_value = {
- "data": [{"id": "test/model", "context_length": 32768}]
- }
-
- with patch(
- "agent.model_metadata_http.get",
- side_effect=[not_found, success],
- ) as mock_get:
- result = mm.fetch_endpoint_model_metadata("https://custom.example/v1")
-
- assert result["test/model"]["context_length"] == 32768
- assert mock_get.call_count == 2
- assert [call.args[0] for call in mock_get.call_args_list] == [
- "https://custom.example/v1/models",
- "https://custom.example/models",
- ]
- not_found.read.assert_not_called()
- success.read.assert_called_once()
- not_found.json.assert_not_called()
- not_found.close.assert_called_once()
- success.close.assert_called_once()
-
- def test_remote_probe_is_memoized_on_disk_across_processes(self, tmp_path, monkeypatch):
- """A fresh process (cleared in-memory cache) must answer from the disk
- memo within the TTL instead of re-probing the endpoint — the cost every
- one-shot Bot Mode DM hop paid on startup. Expired memos re-probe."""
- import agent.model_metadata as mm
-
- monkeypatch.setattr(
- mm, "_get_endpoint_metadata_cache_path", lambda: tmp_path / "endpoint_model_metadata.json"
- )
- success = MagicMock()
- success.status_code = 200
- success.json.return_value = {"data": [{"id": "test/model", "context_length": 32768}]}
-
- with patch("agent.model_metadata_http.get", return_value=success) as mock_get:
+ monkeypatch.setattr(mm, "_get_endpoint_metadata_cache_path", lambda: tmp_path / "endpoint.json")
+ responses, requests = metadata_transport
+ responses.extend(httpx.Response(200, json={"data": [{"id": "test/model", "context_length": 32768}]}) for _ in range(2))
+ for _ in range(2):
assert mm.fetch_endpoint_model_metadata("https://custom.example/v1")["test/model"]["context_length"] == 32768
- # "New process": drop the in-memory cache only.
mm._endpoint_model_metadata_cache.clear()
mm._endpoint_model_metadata_cache_time.clear()
- assert mm.fetch_endpoint_model_metadata("https://custom.example/v1")["test/model"]["context_length"] == 32768
- mock_get.assert_called_once()
-
- # Past the TTL the memo is stale and the endpoint is probed again.
- mm._endpoint_model_metadata_cache.clear()
- mm._endpoint_model_metadata_cache_time.clear()
- with patch("agent.model_metadata.time.time", return_value=time.time() + mm._ENDPOINT_MODEL_CACHE_TTL + 1), patch(
- "agent.model_metadata_http.get", return_value=success
- ) as mock_get:
+ assert len(requests) == 1
+ with patch("agent.model_metadata.time.time", return_value=time.time() + mm._ENDPOINT_MODEL_CACHE_TTL + 1):
mm.fetch_endpoint_model_metadata("https://custom.example/v1")
- mock_get.assert_called_once()
+ assert len(requests) == 2
# =========================================================================
diff --git a/tests/agent/test_model_metadata_http.py b/tests/agent/test_model_metadata_http.py
index e81b08b9caa..811f3694971 100644
--- a/tests/agent/test_model_metadata_http.py
+++ b/tests/agent/test_model_metadata_http.py
@@ -67,7 +67,7 @@ def test_redirect_credentials_and_proxy_routing_are_preserved(servers, monkeypat
assert seen[-1][0] == "http://probe.invalid/models"
[email protected]("status", [401, 403])
[email protected]("status", [401, 403, 404])
def test_metadata_auth_failure_closes_without_reading_body(servers, monkeypatch, status):
requests = []
@@ -76,9 +76,16 @@ def test_metadata_auth_failure_closes_without_reading_body(servers, monkeypatch,
def do_GET(self):
requests.append(self.path)
- self.send_response(status)
- self.send_header("Content-Length", "1000000")
- self.end_headers()
+ if status == 404 and self.path == "/models":
+ body = b'{"data":[{"id":"test/model","context_length":32768}]}'
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+ else:
+ self.send_response(status)
+ self.send_header("Content-Length", "1000000")
+ self.end_headers()
# Intentionally send no body. The client must close on the headers,
# not wait for a read timeout or try the alternate /v1 URL.
@@ -98,7 +105,15 @@ def test_metadata_auth_failure_closes_without_reading_body(servers, monkeypatch,
return original_client(**{**kwargs, "timeout": 2.0})
monkeypatch.setattr(httpx, "Client", recorded_client)
- assert model_metadata.fetch_endpoint_model_metadata(url, force_refresh=True) == {}
- assert requests == ["/models"]
- assert len(responses) == 1 and responses[0].is_closed
- assert not responses[0].is_stream_consumed, "auth rejection read the absent body"
+ url += "/v1"
+ result = model_metadata.fetch_endpoint_model_metadata(url, force_refresh=True)
+ if status == 404:
+ assert result["test/model"]["context_length"] == 32768
+ assert requests == ["/v1/models", "/models"]
+ assert responses[1].is_stream_consumed
+ else:
+ assert result == {}
+ assert model_metadata.fetch_endpoint_model_metadata(url) == {}
+ assert requests == ["/v1/models"]
+ assert all(response.is_closed for response in responses)
+ assert not responses[0].is_stream_consumed, "rejection read the absent body"
diff --git a/tests/agent/test_model_metadata_ssl.py b/tests/agent/test_model_metadata_ssl.py
deleted file mode 100644
index 5639a569649..00000000000
--- a/tests/agent/test_model_metadata_ssl.py
+++ /dev/null
@@ -1,19 +0,0 @@
-"""Metadata discovery uses chat's resolved TLS policy without ambient CA files."""
-from __future__ import annotations
-
-import ssl
-
-import httpx
-import pytest
-
-from agent.model_metadata_http import resolve_verify
-
-
[email protected]("variable", ["HERMES_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE", "SSL_CERT_FILE", "SSL_CERT_DIR"])
-def test_ambient_ca_paths_do_not_break_metadata_clients(monkeypatch, tmp_path, variable):
- monkeypatch.setenv(variable, str(tmp_path / "missing-ca"))
- verify = resolve_verify()
- with httpx.Client(verify=verify) as client:
- context = client._transport._pool._ssl_context
- assert context.verify_mode == ssl.CERT_REQUIRED
- assert context.check_hostname
diff --git a/tests/agent/test_probe_cache_followups.py b/tests/agent/test_probe_cache_followups.py
index 57e9a938e4b..485fe11dc06 100644
--- a/tests/agent/test_probe_cache_followups.py
+++ b/tests/agent/test_probe_cache_followups.py
@@ -7,7 +7,7 @@ Covers:
from __future__ import annotations
-from contextlib import contextmanager
+from tests.agent.metadata_transport import metadata_transport # noqa: F401
from unittest.mock import MagicMock, patch
import pytest
@@ -165,21 +165,6 @@ class TestLocalhostIPv4SiblingSites:
"""#37595 widened: every probe helper rewrites localhost→127.0.0.1,
not just detect_local_server_type."""
- @pytest.fixture(autouse=True)
- def streamed_responses(self, monkeypatch):
- from agent import model_metadata_http
-
- @contextmanager
- def stream(*args, **kwargs):
- response = model_metadata_http.get(*args, **kwargs)
- try:
- yield response
- finally:
- response.close()
-
- monkeypatch.setattr(model_metadata_http, "stream", stream)
-
-
def test_rewrite_is_host_only_not_substring(self):
"""A URL that merely EMBEDS 'http://localhost' in its path/query must
not be corrupted — only the URL's own host is rewritten."""
@@ -201,61 +186,25 @@ class TestLocalhostIPv4SiblingSites:
assert client.post.call_args[0][0].startswith("http://127.0.0.1:11434")
- def test_fetch_endpoint_model_metadata_generic_probe_uses_ipv4(self):
- """The generic (non-LM-Studio) /models fetch loop must also rewrite
- localhost->127.0.0.1 before probing, like the LM Studio branch above."""
- from agent import model_metadata
- from agent.model_metadata import fetch_endpoint_model_metadata
-
- model_metadata._endpoint_model_metadata_cache.clear()
- model_metadata._endpoint_model_metadata_cache_time.clear()
-
- resp = MagicMock()
- resp.status_code = 200
- resp.raise_for_status = MagicMock()
- resp.json.return_value = {"data": []}
-
- with patch("agent.model_metadata.detect_local_server_type", return_value=None), \
- patch("agent.model_metadata_http.get", return_value=resp) as mock_get:
- fetch_endpoint_model_metadata("http://localhost:8000/v1")
-
- assert mock_get.call_args[0][0].startswith("http://127.0.0.1:8000")
-
- def test_fetch_endpoint_model_metadata_llamacpp_props_followup_uses_ipv4(self):
- """The llama.cpp /props context-length follow-up must also rewrite
- localhost->127.0.0.1 before probing, not just the initial /models call."""
- from agent import model_metadata
- from agent.model_metadata import fetch_endpoint_model_metadata
-
- model_metadata._endpoint_model_metadata_cache.clear()
- model_metadata._endpoint_model_metadata_cache_time.clear()
-
- models_resp = MagicMock()
- models_resp.status_code = 200
- models_resp.raise_for_status = MagicMock()
- models_resp.json.return_value = {
- "data": [{"id": "llama-3-8b", "owned_by": "llamacpp"}],
- }
-
- props_resp = MagicMock()
- props_resp.is_error = False
- props_resp.json.return_value = {
- "default_generation_settings": {"n_ctx": 32768},
- "model_alias": "llama-3-8b",
- }
-
- with patch("agent.model_metadata.detect_local_server_type", return_value=None), \
- patch(
- "agent.model_metadata_http.get",
- side_effect=[models_resp, props_resp],
- ) as mock_get:
- result = fetch_endpoint_model_metadata("http://localhost:8000/v1")
-
- assert mock_get.call_count == 2
- props_call_url = mock_get.call_args_list[1][0][0]
- assert props_call_url.startswith("http://127.0.0.1:8000")
- assert result["llama-3-8b"]["context_length"] == 32768
-
+ @pytest.mark.parametrize("llamacpp", [False, True])
+ def test_endpoint_and_props_followup_use_ipv4(self, metadata_transport, llamacpp):
+ import httpx
+ from agent import model_metadata as mm
+
+ mm._endpoint_model_metadata_cache.clear()
+ mm._endpoint_model_metadata_cache_time.clear()
+ responses, requests = metadata_transport
+ models = [{"id": "llama-3-8b", "owned_by": "llamacpp"}] if llamacpp else []
+ responses.extend([
+ httpx.Response(200, json={"data": models}),
+ httpx.Response(200, json={"default_generation_settings": {"n_ctx": 32768}, "model_alias": "llama-3-8b"}),
+ ])
+ result = mm.fetch_endpoint_model_metadata("http://localhost:8000/v1", force_refresh=True)
+ assert len(requests) == (2 if llamacpp else 1)
+ assert all(request.url.host == "127.0.0.1" for request in requests)
+ if llamacpp:
+ assert requests[1].url.path == "/v1/props"
+ assert result["llama-3-8b"]["context_length"] == 32768
class TestContextCacheKeyNormalization:
diff --git a/tests/agent/test_skill_utils.py b/tests/agent/test_skill_utils.py
index 82d9350cdd0..e048563bc4d 100644
--- a/tests/agent/test_skill_utils.py
+++ b/tests/agent/test_skill_utils.py
@@ -246,21 +246,20 @@ def test_skill_support_path_uses_explicit_discovery_root_not_cwd(tmp_path, monke
class TestSkillMatchesPlatform:
+ @pytest.mark.platforms("any")
def test_no_platforms_field_matches_everywhere(self):
# Backward-compat default — skills without a platforms tag load
# on any OS.
- with patch("agent.skill_utils.sys.platform", "linux"):
- assert skill_matches_platform({}) is True
- assert skill_matches_platform({"name": "foo"}) is True
+ assert skill_matches_platform({}) is True
+ assert skill_matches_platform({"name": "foo"}) is True
+ @pytest.mark.platforms("any")
def test_linux_skill_matches_only_linux(self):
fm = {"platforms": ["linux"]}
- with patch("agent.skill_utils.sys.platform", "linux"):
- assert skill_matches_platform(fm) is True
- assert skill_matches_platform_list(fm["platforms"]) is True
- with patch("agent.skill_utils.sys.platform", "darwin"):
- assert skill_matches_platform(fm) is False
- assert skill_matches_platform_list(fm["platforms"]) is False
+ import sys
+
+ assert skill_matches_platform(fm) is sys.platform.startswith("linux")
+ assert skill_matches_platform_list(fm["platforms"]) is sys.platform.startswith("linux")
def test_relative_path_unchanged(self, tmp_path, monkeypatch):
diff --git a/tests/agent/test_ssl_transport_contracts.py b/tests/agent/test_ssl_transport_contracts.py
index 3a36b1fac93..d8bac8372a8 100644
--- a/tests/agent/test_ssl_transport_contracts.py
+++ b/tests/agent/test_ssl_transport_contracts.py
@@ -74,8 +74,9 @@ def test_provider_ca_reaches_the_real_probe_transport(local_tls, monkeypatch, pr
url, bundle = local_tls
monkeypatch.setattr(model_metadata, "detect_local_server_type", lambda *args, **kwargs: None)
- settings = {"ssl_ca_cert": certifi.where()}
- monkeypatch.setattr("hermes_cli.config.get_custom_provider_tls_settings", lambda base_url: dict(settings))
+ settings = {"name": "loopback", "base_url": url, "ssl_ca_cert": certifi.where()}
+ monkeypatch.setattr("hermes_cli.config.get_compatible_custom_providers", lambda config=None: [dict(settings)])
+ monkeypatch.setenv("SSL_CERT_FILE", "/missing-ambient.pem")
def discover():
if probe == "metadata":
@@ -86,38 +87,41 @@ def test_provider_ca_reaches_the_real_probe_transport(local_tls, monkeypatch, pr
settings["ssl_ca_cert"] = str(bundle)
assert discover() == ["test-model"]
- # Model probing must use the same resolver as chat, not a path whose TLS
- # semantics change after truststore's process-wide injection.
- seen = []
- original = ssl_verify.resolve_httpx_verify
-
- def record(**kwargs):
- context = original(**kwargs)
- seen.append(context)
- return context
-
- monkeypatch.setattr(ssl_verify, "resolve_httpx_verify", record)
+ settings["ssl_ca_cert"] = certifi.where()
+ settings["ssl_verify"] = False
assert discover() == ["test-model"]
- assert seen and seen[-1] is original(ca_bundle=str(bundle))
[email protected]("variable", ["SSL_CERT_FILE", "SSL_CERT_DIR"])
[email protected]("variable", ["HERMES_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE", "SSL_CERT_FILE", "SSL_CERT_DIR"])
def test_ambient_ca_cannot_break_the_shared_client(variable, tmp_path, monkeypatch):
+ from run_agent import AIAgent
+
monkeypatch.setenv(variable, str(tmp_path / "missing-ca"))
+ for _ in range(2):
+ assert ssl_verify.install_truststore() is True
verify = ssl_verify.resolve_httpx_verify()
with httpx.Client(verify=verify) as client:
- assert not client.is_closed
- client = process_bootstrap.build_keepalive_http_client("https://example.invalid", verify=verify)
+ context = client._transport._pool._ssl_context
+ assert context.verify_mode == ssl.CERT_REQUIRED and context.check_hostname
+ assert type(context).__module__.startswith("truststore")
+ client = AIAgent._build_keepalive_http_client("https://example.invalid", verify=verify)
assert client is not None
client.close()
-def test_pinned_clients_share_transport_not_close_state(local_tls):
[email protected]("insecure", [False, True])
+def test_pinned_clients_share_transport_not_close_state(local_tls, insecure):
+ from run_agent import AIAgent
url, bundle = local_tls
- first = ssl_verify.resolve_httpx_verify(ca_bundle=str(bundle))
- second = ssl_verify.resolve_httpx_verify(ca_bundle=str(bundle))
+ first = ssl_verify.resolve_httpx_verify(ca_bundle=str(bundle), ssl_verify=not insecure)
+ second = ssl_verify.resolve_httpx_verify(ca_bundle=str(bundle), ssl_verify=not insecure)
+ if not insecure:
+ assert isinstance(first, _original_SSLContext)
+ assert not type(first).__module__.startswith("truststore")
+ assert first.verify_mode == ssl.CERT_REQUIRED and first.check_hostname
+ assert len(first.get_ca_certs()) == 1
assert first is second
- a = process_bootstrap.build_keepalive_http_client(url, verify=first)
+ a = AIAgent._build_keepalive_http_client(url, verify=first)
b = process_bootstrap.build_keepalive_http_client(url, verify=second)
assert a is not None and b is not None
try:
diff --git a/tests/agent/test_ssl_verify.py b/tests/agent/test_ssl_verify.py
index a6b1ce4e6cc..361b322223f 100644
--- a/tests/agent/test_ssl_verify.py
+++ b/tests/agent/test_ssl_verify.py
@@ -4,90 +4,9 @@ These are behavior contracts, not snapshots — they assert WHERE trust comes
from and that explicit per-provider settings still beat it.
"""
-import ssl
-
import pytest
-from agent import ssl_verify
-from agent.ssl_verify import (
- install_truststore,
- resolve_httpx_verify,
-)
-
-
[email protected](autouse=True)
-def _reset_install_cache():
- ssl_verify._installed = None
- yield
- ssl_verify._installed = None
-
-
-def test_install_truststore_puts_the_platform_verifier_in_charge():
- assert install_truststore() is True
- # Every default context built anywhere in the process is now
- # platform-verified — including stdlib urllib call sites.
- assert ssl.SSLContext.__module__.startswith("truststore")
-
-
-def test_install_truststore_is_idempotent():
- assert install_truststore() is True
- assert install_truststore() is True
-
-
-def test_default_verify_defers_to_the_platform_store():
- # True means "verify normally", which after the install means the OS
- # store. No CA bundle path is threaded through.
- assert resolve_httpx_verify() is True
-
-
-def test_env_ca_bundle_vars_no_longer_steer_trust(monkeypatch, tmp_path):
- """The old SSL_CERT_FILE/REQUESTS_CA_BUNDLE ladders are gone.
-
- Trust is the machine's, and a stale env var pointing at a bundle (or at
- nothing) must not silently redirect or break verification — the exact
- failure the removed gateway/auth/urllib ladders each hand-rolled a
- workaround for.
- """
- import certifi
-
- import httpx
-
- for path in (certifi.where(), str(tmp_path / "does-not-exist.pem")):
- for var in ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"):
- monkeypatch.setenv(var, path)
- verify = resolve_httpx_verify()
- with httpx.Client(verify=verify) as client:
- context = client._transport._pool._ssl_context
- assert type(context).__module__.startswith("truststore")
- assert context.verify_mode == ssl.CERT_REQUIRED
- assert context.check_hostname
-
-
-def test_explicit_ca_bundle_replaces_the_platform_store():
- """A pinned ssl_ca_cert must verify against THAT bundle only.
-
- Tripwire: truststore's injected SSLContext ignores load_verify_locations
- and verifies against the OS store regardless, so this context has to come
- from the original class. If a truststore bump moves
- ``_ssl_constants._original_SSLContext``, this fails here instead of
- silently degrading a pinned corporate bundle into "trust the machine".
- """
- import certifi
- from truststore._ssl_constants import _original_SSLContext
-
- ctx = resolve_httpx_verify(ca_bundle=certifi.where())
-
- # NOT isinstance(ctx, ssl.SSLContext): that name is the patched class
- # now, and this context deliberately is not one.
- assert isinstance(ctx, _original_SSLContext)
- assert not type(ctx).__module__.startswith("truststore")
- # PROTOCOL_TLS_CLIENT's own defaults — asserted, not assigned: setting
- # them on this context recurses forever through the patched module
- # global (super(SSLContext, SSLContext) resolves to truststore's class).
- assert ctx.verify_mode == ssl.CERT_REQUIRED
- assert ctx.check_hostname is True
- # Introspectable precisely because it is NOT truststore-backed.
- assert len(ctx.get_ca_certs()) > 0
+from agent.ssl_verify import resolve_httpx_verify
def test_missing_explicit_bundle_falls_back_to_the_platform_store(tmp_path, caplog):
@@ -108,20 +27,27 @@ def test_insecure_beats_an_explicit_bundle():
assert resolve_httpx_verify(ca_bundle=certifi.where(), ssl_verify=False) is False
-def test_truststore_failure_degrades_to_openssl_defaults(monkeypatch, caplog):
- """No truststore (stripped env, odd platform) must not break startup."""
- import builtins
-
- real_import = builtins.__import__
-
- def _boom(name, *args, **kwargs):
- if name == "truststore":
- raise ImportError("no truststore here")
- return real_import(name, *args, **kwargs)
-
- monkeypatch.setattr(builtins, "__import__", _boom)
- assert install_truststore() is False
- assert "truststore unavailable" in caplog.text
- # Still resolves to a usable verify value rather than raising.
- monkeypatch.undo()
- assert resolve_httpx_verify() is True
+def test_truststore_failure_degrades_to_openssl_defaults():
+ import subprocess
+ import sys
+
+ child = subprocess.run([sys.executable, "-c", """
+import builtins, ssl
+original = ssl.SSLContext
+real_import = builtins.__import__
+def no_truststore(name, *args, **kwargs):
+ if name == 'truststore':
+ raise ImportError('unavailable fixture')
+ return real_import(name, *args, **kwargs)
+builtins.__import__ = no_truststore
+from agent.ssl_verify import install_truststore, resolve_httpx_verify
+assert install_truststore() is False
+assert install_truststore() is False
+assert ssl.SSLContext is original
+import httpx
+with httpx.Client(verify=resolve_httpx_verify()) as client:
+ ctx = client._transport._pool._ssl_context
+ assert ctx.verify_mode == ssl.CERT_REQUIRED and ctx.check_hostname
+"""], capture_output=True, text=True, timeout=30)
+ assert child.returncode == 0, child.stderr
+ assert "truststore unavailable" in child.stderr
diff --git a/tests/ci/test_desktop_release_tag_admission.py b/tests/ci/test_desktop_release_tag_admission.py
index cb6e7c319b0..00707b3dae2 100644
--- a/tests/ci/test_desktop_release_tag_admission.py
+++ b/tests/ci/test_desktop_release_tag_admission.py
@@ -59,14 +59,6 @@ def test_validate_exports_the_admitted_sha_as_a_job_output():
assert "steps.admission.outputs.sha" in outputs["sha"]
-def test_admission_script_requires_ancestry_on_origin_main():
- script = _admission_script()
- assert "merge-base --is-ancestor" in script
- assert "origin/main" in script
- assert "::error::" in script, "the refusal must be a loud, greppable error"
- assert "GITHUB_OUTPUT" in script, "the resolved SHA must be exported"
-
-
def test_every_signing_job_checks_out_the_admitted_sha_not_the_tag():
wf = _workflow()
privileged = {
diff --git a/tests/ci/test_list_os_marked_tests.py b/tests/ci/test_list_os_marked_tests.py
index 3e46c8e904e..08270694088 100644
--- a/tests/ci/test_list_os_marked_tests.py
+++ b/tests/ci/test_list_os_marked_tests.py
@@ -35,148 +35,30 @@ def _write(root: Path, relpath: str, body: str) -> Path:
return path
[email protected]("platform", ["linux", "macos", "windows"])
-def test_finds_decorator_and_pytestmark_forms(tmp_path, platform):
- """Both the decorator form and module-level ``pytestmark`` are detected."""
- _write(
- tmp_path,
- "test_decorated.py",
- f'import pytest\n\n\[email protected]("{platform}")\ndef test_x():\n pass\n',
- )
- _write(
- tmp_path,
- "nested/test_module_level.py",
- f'import pytest\n\npytestmark = pytest.mark.platforms("{platform}")\n\n\ndef test_y():\n pass\n',
- )
- # A file with no gate at all must not be selected.
- _write(tmp_path, "test_plain.py", "def test_z():\n pass\n")
- # A platforms() file gating a DIFFERENT platform must not be selected.
- other = "windows" if platform != "windows" else "linux"
- _write(
- tmp_path,
- "test_other_platform.py",
- f'import pytest\n\n\[email protected]("{other}")\ndef test_w():\n pass\n',
- )
- # A bare identifier that merely LOOKS like the platform name must not
- # match — the spec has to appear inside the quoted string literal.
- _write(
- tmp_path,
- "test_bare_identifier.py",
- f"import pytest\n\n\[email protected](\"kind\", [\"{platform}\"])\ndef test_v():\n assert kind\n",
- )
-
[email protected]("platform,expected", [
+ ("linux", {"linux", "posix", "any", "not_macos", "not_linux", "unknown", "dynamic", "empty"}),
+ ("macos", {"module", "single", "posix", "any", "not_macos", "not_linux", "unknown", "dynamic", "empty"}),
+ ("windows", {"arch", "multiline", "any", "not_macos", "not_linux", "unknown", "dynamic", "empty"}),
+])
+def test_selector_corpus(tmp_path, platform, expected):
+ # Selection deliberately overselects negated/unknown inputs; the runtime
+ # marker, not this file selector, decides whether each test runs.
+ calls = {
+ "linux": '"linux"', "single": "'macos'", "posix": '"posix"',
+ "any": '"any"', "not_macos": '"not macos"', "not_linux": '"not linux"',
+ "arch": '"windows", arch="arm64"',
+ "multiline": '\n"windows",\narch="arm64",\n',
+ "unknown": '"amiga"', "dynamic": 'PLATFORM', "empty": '',
+ }
+ for name, arguments in calls.items():
+ _write(tmp_path, f"test_{name}.py",
+ f"@pytest.mark.platforms({arguments})\ndef test_x(): pass\n")
+ _write(tmp_path, "nested/test_module.py", 'pytestmark = pytest.mark.platforms("macos")\n')
+ _write(tmp_path, "test_plain.py", "def test_x(): pass\n")
+ _write(tmp_path, "test_identifier.py", '@pytest.mark.parametrize("kind", ["linux", "macos", "windows"])\ndef test_x(): pass\n')
result = _run(platform, str(tmp_path))
-
- assert result.returncode == 0, result.stderr
- listed = result.stdout.split()
- assert any(p.endswith("test_decorated.py") for p in listed)
- assert any(p.endswith("test_module_level.py") for p in listed)
- assert not any(p.endswith("test_plain.py") for p in listed)
- assert not any(p.endswith("test_other_platform.py") for p in listed)
- assert not any(p.endswith("test_bare_identifier.py") for p in listed)
-
-
-def test_negated_spec_lists_for_that_lane(tmp_path):
- """``platforms("not macos")`` lists the file for the macOS lane import.
-
- The script only decides which files are IMPORTED; the per-test host
- skips remain authoritative. A negated-spec file may still contain other
- tests, so it must be imported on the macOS lane — under-selecting is
- the failure mode this tool exists to prevent.
- """
- _write(
- tmp_path,
- "test_negated.py",
- 'import pytest\n\n\[email protected]("not macos")\ndef test_x():\n pass\n',
- )
-
- result = _run("macos", str(tmp_path))
-
- assert result.returncode == 0, result.stderr
- listed = result.stdout.split()
- assert any(p.endswith("test_negated.py") for p in listed)
-
-
-def test_posix_spec_lists_for_both_posix_lanes_only(tmp_path):
- """``platforms("posix")`` runs on linux+macos hosts, not windows.
-
- The file must be listed for the macos lane (its tests RUN there);
- under-selecting it would silently drop that coverage.
- """
- _write(
- tmp_path,
- "test_posix.py",
- "import pytest\n\n\[email protected](\"posix\")\ndef test_x():\n pass\n",
- )
- for platform, expected in [("macos", True), ("linux", True), ("windows", False)]:
- result = _run(platform, str(tmp_path))
- listed = result.stdout.split()
- assert any(p.endswith("test_posix.py") for p in listed) is expected, platform
-
-
-def test_any_spec_lists_for_every_lane(tmp_path):
- _write(
- tmp_path,
- "test_any.py",
- "import pytest\n\n\[email protected](\"any\")\ndef test_x():\n pass\n",
- )
- for platform in ("linux", "macos", "windows"):
- result = _run(platform, str(tmp_path))
- assert result.returncode == 0, result.stderr
- assert any(p.endswith("test_any.py") for p in result.stdout.split()), platform
-
-
-def test_arch_filter_still_lists_the_file(tmp_path):
- """arch= narrows per-test skips, not file selection.
-
- The lane's machine is not statically known here; over-selecting is
- corrected by the per-test host skip, so an arch-filtered file must
- still be listed for its platform's lane.
- """
- _write(
- tmp_path,
- "test_arch.py",
- 'import pytest\n\n\[email protected]("windows", arch="arm64")\n'
- "def test_x():\n pass\n",
- )
- result = _run("windows", str(tmp_path))
assert result.returncode == 0, result.stderr
- assert any(p.endswith("test_arch.py") for p in result.stdout.split())
-
-
-def test_multiline_and_single_quoted_spec_lists(tmp_path):
- """Real call shapes: multiline decorator args and single-quoted specs."""
- _write(
- tmp_path,
- "test_multiline.py",
- "import pytest\n\n\n"
- '@pytest.mark.platforms(\n "windows",\n arch="arm64",\n)\n'
- "def test_x():\n pass\n",
- )
- _write(
- tmp_path,
- "test_single_quote.py",
- "import pytest\n\n\[email protected]('macos')\ndef test_y():\n pass\n",
- )
- result = _run("windows", str(tmp_path))
- listed = result.stdout.split()
- assert any(p.endswith("test_multiline.py") for p in listed)
- result = _run("macos", str(tmp_path))
- assert any(p.endswith("test_single_quote.py") for p in result.stdout.split())
-
-
-def test_negated_exclusive_spec_still_lists_other_lanes(tmp_path):
- """``platforms("not linux")`` runs on macos+windows — list it there."""
- _write(
- tmp_path,
- "test_not_linux.py",
- 'import pytest\n\n\[email protected]("not linux")\ndef test_x():\n pass\n',
- )
- for platform in ("macos", "windows"):
- result = _run(platform, str(tmp_path))
- assert any(p.endswith("test_not_linux.py") for p in result.stdout.split()), (
- platform
- )
+ assert {Path(p).stem.removeprefix("test_") for p in result.stdout.split()} == expected
def test_unknown_platform_is_rejected(tmp_path):
@@ -206,30 +88,16 @@ def test_rejects_missing_root():
assert "no such directory" in result.stderr
-def test_emits_repo_relative_posix_paths():
- """Output feeds a bash command line on the Windows runner, so separators
- must be POSIX and paths repo-relative.
-
- Asserted against the real ``tests/`` tree, which is the only case CI
- exercises — an out-of-repo root can't be made repo-relative and is
- emitted absolute instead.
- """
- result = _run("windows")
-
- assert result.returncode == 0, result.stderr
- listed = result.stdout.split()
- assert listed
- for line in listed:
- assert "\\" not in line
- assert not Path(line).is_absolute()
-
-
def test_real_tree_selects_files_for_every_platform():
"""Against the actual ``tests/`` tree each platform resolves to real files."""
for platform in ("linux", "macos", "windows"):
result = _run(platform)
assert result.returncode == 0, (platform, result.stderr)
assert result.stdout.split(), f"{platform} selected nothing in the real tree"
+ for line in result.stdout.split():
+ assert "\\" not in line
+ assert not Path(line).is_absolute()
+ assert (REPO_ROOT / line).is_file()
def test_unparseable_file_is_still_listed(tmp_path):
"""A file the selector cannot parse is conservatively listed so the lane
diff --git a/tests/ci/test_required_results.py b/tests/ci/test_required_results.py
index 4b96feaed3b..813112455d9 100644
--- a/tests/ci/test_required_results.py
+++ b/tests/ci/test_required_results.py
@@ -14,187 +14,62 @@ required_results = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(required_results)
evaluate_gate = required_results.evaluate_gate
-PR_ONLY_JOBS = required_results.PR_ONLY_JOBS
-DEFERRED_JOBS = required_results.DEFERRED_JOBS
-EXCLUDED_JOBS = required_results.EXCLUDED_JOBS
-def needs_of(entries):
- """Build the needs-context shape ci.yaml's all-checks-pass receives."""
- return {name: {"result": result} for name, result in entries}
-
-
-def test_non_release_failure_fails_gate_skip_counts_as_success():
- base = [("detect", "success"), ("tests", "success"), ("lint", "success")]
-
- assert evaluate_gate(needs_of(base))["ok"] is True
-
- with_failure = evaluate_gate(needs_of([*base, ("js-tests", "failure")]))
- assert with_failure["ok"] is False
- assert with_failure["failed"] == ["js-tests"]
-
- # Skipped lanes are fine when not releasing (e.g. docs-only PR).
- with_skips = evaluate_gate(
- needs_of([("detect", "success"), ("tests", "skipped"), ("rust-tests", "skipped"), ("lint", "success")])
- )
- assert with_skips["ok"] is True
- assert with_skips["allowed_skips"] == ["rust-tests", "tests"]
-
-
-def test_exclusion_sets_name_exactly_pr_only_and_deferred_jobs():
- assert PR_ONLY_JOBS == ("history-check", "lockfile-diff", "supply-chain", "review-labels")
- assert DEFERRED_JOBS == ("e2e-desktop",)
- assert EXCLUDED_JOBS == set(PR_ONLY_JOBS) | set(DEFERRED_JOBS)
-
-
-def test_release_only_excluded_jobs_may_skip():
- needs = needs_of(
- [
- ("detect", "success"),
- ("tests", "success"),
- ("js-tests", "success"),
- ("osv-scanner", "success"),
- # PR-only: never ran — release runs are push/tag events.
- ("history-check", "skipped"),
- ("lockfile-diff", "skipped"),
- ("supply-chain", "skipped"),
- ("review-labels", "skipped"),
- # Deferred: Desktop E2E stays disabled.
- ("e2e-desktop", "skipped"),
- ]
- )
- verdict = evaluate_gate(needs, release=True)
- assert verdict["ok"] is True
- assert verdict["allowed_skips"] == ["e2e-desktop", "history-check", "lockfile-diff", "review-labels", "supply-chain"]
-
-
-def test_release_osv_skipped_is_a_failure_not_advisory():
- # Advisory FINDINGS do not make the EXECUTION advisory: the OSV scan
- # must run to success on a release candidate.
- verdict = evaluate_gate(needs_of([("detect", "success"), ("osv-scanner", "skipped")]), release=True)
- assert verdict["ok"] is False
- assert verdict["failed"] == ["osv-scanner"]
-
-
-def test_release_skipped_required_job_fails_gate():
- needs = needs_of(
- [
- ("detect", "success"),
- ("tests", "success"),
- # Everything tagged python (and python_prod/frontend) skipped on
- # the release run: the strict gate must not wave this through.
- ("tests-os", "skipped"),
- ("lint", "skipped"),
- ("js-tests", "skipped"),
- ("infographic-check", "success"),
- ]
- )
- verdict = evaluate_gate(needs, release=True)
- assert verdict["ok"] is False
- assert verdict["failed"] == ["js-tests", "lint", "tests-os"]
-
-
-def test_every_non_success_result_fails_in_release_mode():
- # cancelled / with-status / action_required / unknown / missing all
- # fail; only `success` passes and only `skipped` on an excluded job
- # is tolerated.
- needs = needs_of(
- [
- ("a", "cancelled"),
- ("b", "with-status"),
- ("c", "action_required"),
- ("d", "unknown"),
- ]
+import pytest
+
+
[email protected]("release", [False, True])
[email protected]("job", ["tests", "osv-scanner", "history-check", "e2e-desktop"])
[email protected]("result,ordinary,excluded", [
+ ("success", True, True), ("skipped", False, True), ("failure", False, False),
+ ("cancelled", False, False), ("with-status", False, False),
+ ("action_required", False, False), ("unknown", False, False), (None, False, False),
+])
+def test_status_policy(job, result, ordinary, excluded, release):
+ expected = excluded if job in ("history-check", "e2e-desktop") else ordinary
+ if result == "skipped" and not release:
+ expected = True
+ verdict = evaluate_gate({job: {} if result is None else {"result": result}}, release=release)
+ assert verdict == {"ok": expected, "failed": [] if expected else [job],
+ "allowed_skips": [job] if expected and result == "skipped" else []}
+
+
+def test_release_exclusion_policy():
+ assert required_results.EXCLUDED_JOBS == {
+ "history-check", "lockfile-diff", "supply-chain", "review-labels", "e2e-desktop",
+ }
+
+
[email protected]("needs", [{}, None])
[email protected]("release", [False, True])
+def test_empty_needs_fails_closed(needs, release):
+ assert evaluate_gate(needs, release=release) == {
+ "ok": False, "failed": ["<no-needs>"], "allowed_skips": [],
+ }
+ assert required_results.compact_results(needs) == {}
+
+
[email protected]("release,results,code,report", [
+ (True, {"detect": "success", "e2e-desktop": "skipped"}, 0, "All checks passed"),
+ (True, {"tests": "skipped", "history-check": "skipped", "lint": "failure"},
+ 1, "::error::2 job(s) failed: lint, tests"),
+ (False, {"tests": "failure"}, 1, "::error::1 job(s) failed: tests"),
+])
+def test_cli_stdin_exit_codes_and_output(tmp_path, release, results, code, report):
+ output = tmp_path / "github-output.txt"
+ needs = {name: {"result": result, "outputs": {"detail": "kept"}}
+ for name, result in results.items()}
+ child = subprocess.run(
+ [sys.executable, str(SCRIPT), *(["--release"] if release else [])],
+ input=json.dumps(needs), capture_output=True, text=True, timeout=30,
+ env={**os.environ, "GITHUB_OUTPUT": str(output)},
)
- verdict = evaluate_gate(needs, release=True)
- assert verdict["ok"] is False
- assert verdict["failed"] == ["a", "b", "c", "d"]
-
- # A needs entry with no result key at all (should never happen, but
- # must not silently pass).
- verdict = evaluate_gate({"x": {}}, release=True)
- assert verdict["ok"] is False
- assert verdict["failed"] == ["x"]
-
-
-def test_release_failure_fails_gate_even_beside_allowed_skips():
- needs = needs_of(
- [
- ("detect", "success"),
- ("tests", "failure"),
- ("history-check", "skipped"),
- ("e2e-desktop", "skipped"),
- ]
- )
- verdict = evaluate_gate(needs, release=True)
- assert verdict["ok"] is False
- assert verdict["failed"] == ["tests"]
-
-
-def test_empty_needs_fails_closed():
- assert evaluate_gate({}, release=True)["ok"] is False
- assert evaluate_gate({}, release=False)["ok"] is False
- assert evaluate_gate(None, release=True)["ok"] is False
-
-
-def test_release_full_pipeline_all_green_passes():
- # What ci.yaml's all-checks-pass actually needs. A release run forces
- # the classifier lanes true, so a healthy candidate looks like this.
- all_green = [
- "detect", "tests", "tests-os", "lint", "js-tests", "installer-tests",
- "rust-tests", "bootstrap-installer", "e2e-desktop", "docs-site",
- "history-check", "contributor-check", "uv-lockfile", "infographic-check",
- "case-collision-check", "lazy-deps-guard", "lockfile-diff",
- "docker-lint", "profile-artifact-check", "icons-freshness-check",
- "supply-chain", "review-labels", "osv-scanner",
- ]
- needs = needs_of((name, "success") for name in all_green)
- assert evaluate_gate(needs, release=True)["ok"] is True
- assert evaluate_gate(needs, release=False)["ok"] is True
-
-
-def test_compact_results_maps_every_job_to_its_result():
- needs = needs_of([("detect", "success"), ("tests", "skipped")])
- assert required_results.compact_results(needs) == {"detect": "success", "tests": "skipped"}
- assert required_results.compact_results(None) == {}
-
-
-def test_render_report_reports_honest_skip_counts():
- needs = needs_of([("tests", "skipped"), ("lint", "failure"), ("detect", "success")])
- verdict = evaluate_gate(needs, release=True)
- lines = "\n".join(required_results.render_report(needs, verdict))
- assert "⏭️ tests: skipped" in lines
- assert "❌ lint: failure" in lines
- assert "::error::2 job(s) failed: lint, tests" in lines
-
-
-def test_cli_stdin_exit_codes_and_output(tmp_path):
- gh_output = tmp_path / "github-output.txt"
- green = needs_of([("detect", "success"), ("tests", "success"), ("e2e-desktop", "skipped")])
-
- def run(needs, release, env_file):
- # Inherit the full environment: on Windows a stripped env breaks
- # subprocess startup (SystemRoot etc.).
- env = dict(os.environ)
- env.pop("GITHUB_OUTPUT", None)
- if env_file is not None:
- env["GITHUB_OUTPUT"] = str(env_file)
- return subprocess.run(
- [sys.executable, str(SCRIPT)] + (["--release"] if release else []),
- input=json.dumps(needs),
- capture_output=True,
- text=True,
- env=env,
- )
-
- ok = run(green, release=True, env_file=gh_output)
- assert ok.returncode == 0
- assert "All checks passed" in ok.stdout
- assert "needs-json=" in ok.stdout
- assert "needs-json=" in gh_output.read_text(encoding="utf-8")
-
- bad = run(needs_of([("tests", "skipped")]), release=True, env_file=None)
- assert bad.returncode == 1
-
- failed = run(needs_of([("tests", "failure")]), release=False, env_file=None)
- assert failed.returncode == 1
+ assert child.returncode == code, child.stderr
+ assert report in child.stdout
+ key, value = output.read_text(encoding="utf-8").strip().split("=", 1)
+ assert key == "needs-json"
+ assert json.loads(value) == results
+ assert f"{key}={value}" in child.stdout
+ for name, result in results.items():
+ assert f"{name}: {result}" in child.stdout
diff --git a/tests/ci/test_termux_input_archive.py b/tests/ci/test_termux_input_archive.py
index beb99b8ff2b..d2a6fc62554 100644
--- a/tests/ci/test_termux_input_archive.py
+++ b/tests/ci/test_termux_input_archive.py
@@ -1,6 +1,5 @@
"""CI runs archival before the exact tool and payload consumers."""
from pathlib import Path
-import shlex
from ruamel.yaml import YAML
@@ -12,30 +11,6 @@ def load(name):
return YAML(typ="base").load((ROOT / ".github/workflows" / name).read_text(encoding="utf-8"))
-def test_termux_and_desktop_stagers_consume_archive_seeds():
- release = load("desktop-bundled-release.yml")
- for file, job_name in (("desktop-bundled-release.yml", "termux-deb"), ("termux-verify.yml", "native-runtime")):
- job = load(file)["jobs"][job_name]
- steps = job["steps"]
- index, step = next((i, s) for i, s in enumerate(steps) if "scripts.ci.archive_inputs" in s.get("run", ""))
- args = shlex.split(step["run"])
- assert args[args.index("--target") + 1] == "linux-arm64-bionic"
- assert args[args.index("--store") + 1] == "$HERMES_RUNTIME_DIR"
- assert args[args.index("--payload") + 1] == "termux-build/payload"
- assert "if" not in step and "continue-on-error" not in step
- assert R2_ENV <= (job.get("env", {}).keys() | step.get("env", {}).keys())
- first_stage = next(i for i, s in enumerate(steps) if "scripts/termux/build_cpython.sh" in s.get("run", ""))
- assert index < first_stage
- for name in ("build-win32", "build-darwin"):
- steps = release["jobs"][name]["steps"]
- index, step = next((i, s) for i, s in enumerate(steps) if "scripts.ci.archive_inputs" in s.get("run", ""))
- assert "--target '${{ matrix.target.label }}'" in step["run"]
- assert "--store apps/desktop/build/agent-payload/tools" in step["run"]
- assert index < next(i for i, s in enumerate(steps) if "scripts/bundles/desktop.py" in s.get("run", ""))
- setup = next(s for s in steps if s.get("uses") == "./.github/actions/setup-pm")
- assert setup["with"]["archive-inputs"] == "true"
-
-
def test_archive_gate_uses_bootstrap_python_and_trusted_exact_revision():
workflow = load("archive-inputs.yml")
assert not {"pull_request", "pull_request_target"} & workflow["on"].keys()
diff --git a/tests/computer_use/driver_fixture.py b/tests/computer_use/driver_fixture.py
new file mode 100644
index 00000000000..bfc94531901
--- /dev/null
+++ b/tests/computer_use/driver_fixture.py
@@ -0,0 +1,42 @@
+"""Independent CUA process fixture shared by selection and doctor callers."""
+import sys
+from pathlib import Path
+
+
+def record_driver(version="0.20.0", *, manifest=False):
+ from pm import Facts, Lockfile, current_target, get_package, paths
+ from pm.store import tree_digest
+
+ package, target, root = get_package("cua-driver"), current_target(), paths.store_root()
+ entry = root / package.store_entry(version, target)
+ binary = package.binary(entry, target)
+ assert binary is not None
+ binary.parent.mkdir(parents=True, exist_ok=True)
+ if manifest:
+ capabilities = {
+ "mcp": ["--socket", "--grant"],
+ "serve": ["--socket", "--permission-mode", "--capability-manifest",
+ "--approve-capability-manifest", "--embedded"],
+ "stop": ["--socket"],
+ }
+ payload = {
+ "binary_version": version,
+ "mcp_invocation": {"command": str(binary), "args": ["mcp"]},
+ "subcommands": [{"name": name, "args": [{"name": arg} for arg in args]}
+ for name, args in capabilities.items()],
+ }
+ binary.write_text(f"#!{sys.executable}\nimport json, sys\nmanifest = {payload!r}\n"
+ "if sys.argv[1:] == ['manifest']:\n print(json.dumps(manifest))\n"
+ "else:\n assert sys.argv[1] in ('status', 'stop')\n", encoding="utf-8")
+ else:
+ binary.write_bytes(Path(sys.executable).read_bytes())
+ binary.chmod(0o755)
+ artifact = {"url": "https://example.invalid/cua-fixture", "sha256": "a" * 64}
+ lock = Lockfile(paths.lockfile_path())
+ lock.set_pin(package.name, version, {target: artifact})
+ lock.save()
+ Facts(paths.facts_path()).record(
+ package.name, version, entry.name, package.env(entry, target), root,
+ target=target, artifacts=[artifact["sha256"]], digest=tree_digest(entry),
+ )
+ return binary
diff --git a/tests/computer_use/test_cua_pm_selection.py b/tests/computer_use/test_cua_pm_selection.py
index 8e2343edd91..9b9f34521e1 100644
--- a/tests/computer_use/test_cua_pm_selection.py
+++ b/tests/computer_use/test_cua_pm_selection.py
@@ -5,6 +5,8 @@ from pathlib import Path
import pytest
+from tests.computer_use.driver_fixture import record_driver
+
@pytest.fixture
def cua_home(tmp_path, monkeypatch):
@@ -21,31 +23,6 @@ def cua_home(tmp_path, monkeypatch):
return tmp_path
-def _record_driver(version="0.20.0"):
- from pm import Facts, Lockfile, current_target, get_package, paths
- from pm.store import tree_digest
-
- package = get_package("cua-driver")
- target = current_target()
- root = paths.store_root()
- entry = root / package.store_entry(version, target)
- entry.mkdir(parents=True)
- binary = package.binary(entry, target)
- assert binary is not None
- binary.parent.mkdir(parents=True, exist_ok=True)
- binary.write_bytes(Path(sys.executable).read_bytes())
- binary.chmod(0o755)
- artifact = {"url": "https://example.invalid/cua-fixture", "sha256": "a" * 64}
- lock = Lockfile(paths.lockfile_path())
- lock.set_pin(package.name, version, {target: artifact})
- lock.save()
- Facts(paths.facts_path()).record(
- package.name, version, entry.name, package.env(entry, target), root,
- target=target, artifacts=[artifact["sha256"]], digest=tree_digest(entry),
- )
- return binary
-
-
def test_pm_selection_ignores_vendor_tree_and_is_passive(cua_home, monkeypatch):
import pm
from pm import paths
@@ -55,7 +32,7 @@ def test_pm_selection_ignores_vendor_tree_and_is_passive(cua_home, monkeypatch):
pytest.fail("passive CUA lookup attempted acquisition")
monkeypatch.setattr(pm, "ensure", no_install)
- binary = _record_driver()
+ binary = record_driver()
legacy = cua_home / ".local" / "bin" / binary.name
legacy.parent.mkdir(parents=True)
legacy.write_bytes(binary.read_bytes())
@@ -67,46 +44,20 @@ def test_pm_selection_ignores_vendor_tree_and_is_passive(cua_home, monkeypatch):
assert resolve_cua_driver_cmd(str(legacy)) == str(legacy)
assert resolve_cua_driver_cmd(str(cua_home / "missing")) is None
assert paths.facts_path().read_bytes() == before
- lock = pm.Lockfile(paths.lockfile_path())
- lock.set_pin("cua-driver", "0.21.0", lock.pinned_artifacts("cua-driver"))
- lock.save()
- assert resolve_cua_driver_cmd() is None
- previous = pm.installed_package("cua-driver", allow_outdated=True)
- assert previous is not None and previous.binary == binary
- binary.unlink()
- assert resolve_cua_driver_cmd() is None
@pytest.mark.platforms("linux")
def test_setup_acquires_through_pm_and_validates_real_manifest(cua_home, monkeypatch):
import pm
from hermes_cli.tools_config_cua import install_cua_driver
- from tools.computer_use.cua_backend_driver import (
- _CUA_DRIVER_RUNTIME_CONTRACT_ARGS, cua_driver_runtime_contract_status,
- )
+ from tools.computer_use.cua_backend_driver import cua_driver_runtime_contract_status
monkeypatch.setenv("PATH", "")
calls = []
def acquire(name, *, explicit):
calls.append((name, explicit))
- binary = _record_driver()
- # A local process fixture, not an upstream CUA installation.
- manifest = {
- "binary_version": "0.20.0",
- "mcp_invocation": {"command": str(binary), "args": ["mcp"]},
- "subcommands": [
- {"name": verb, "args": [{"name": arg} for arg in sorted(args)]}
- for verb, args in _CUA_DRIVER_RUNTIME_CONTRACT_ARGS.items()
- ],
- }
- binary.write_text(
- f"#!{sys.executable}\nimport json, sys\n"
- f"manifest = {manifest!r}\n"
- "assert sys.argv[1:] == ['manifest']\n"
- "print(json.dumps(manifest))\n",
- encoding="utf-8",
- )
+ record_driver(manifest=True)
return pm.Runner(name, pm.env_for(name))
monkeypatch.setattr(pm, "ensure", acquire)
@@ -129,7 +80,6 @@ def test_private_start_uses_post_ensure_binary(cua_home, monkeypatch, permission
import pm
from tools.computer_use import cua_backend as backend_module
- from tools.computer_use.cua_backend_driver import _CUA_DRIVER_RUNTIME_CONTRACT_ARGS
monkeypatch.setenv("PATH", "")
manifest_path = cua_home / "capabilities.yaml"
@@ -138,7 +88,7 @@ def test_private_start_uses_post_ensure_binary(cua_home, monkeypatch, permission
"capability_manifest": str(manifest_path), "no_overlay": False,
})
if preinstalled:
- previous = _record_driver()
+ previous = record_driver()
previous.write_text(f"#!{sys.executable}\nprint('{{}}')\n", encoding="utf-8")
backend = backend_module.CuaDriverBackend(permission_mode=permission_mode)
assert backend._embedded_daemon is not None
@@ -148,22 +98,7 @@ def test_private_start_uses_post_ensure_binary(cua_home, monkeypatch, permission
def acquire(name, **kwargs):
assert name == "cua-driver" and not kwargs.get("explicit", False)
version = next(versions)
- binary = _record_driver(version)
- manifest = {
- "binary_version": version,
- "mcp_invocation": {"command": str(binary), "args": ["mcp"]},
- "subcommands": [
- {"name": verb, "args": [{"name": arg} for arg in sorted(args)]}
- for verb, args in _CUA_DRIVER_RUNTIME_CONTRACT_ARGS.items()
- ],
- }
- binary.write_text(
- f"#!{sys.executable}\nimport json, sys\n"
- f"manifest = {manifest!r}\n"
- "if sys.argv[1:] == ['manifest']:\n print(json.dumps(manifest))\n"
- "else:\n assert sys.argv[1] in ('status', 'stop')\n",
- encoding="utf-8",
- )
+ binary = record_driver(version, manifest=True)
acquired.append(str(binary))
return pm.Runner(name, pm.env_for(name))
diff --git a/tests/computer_use/test_cua_spawn_env_sanitization.py b/tests/computer_use/test_cua_spawn_env_sanitization.py
index 8177cfd2554..e7426461169 100644
--- a/tests/computer_use/test_cua_spawn_env_sanitization.py
+++ b/tests/computer_use/test_cua_spawn_env_sanitization.py
@@ -199,41 +199,3 @@ def test_doctor_spawn_sanitizes_env_and_hides_console_on_windows(monkeypatch):
assert report["overall"] == "ok"
_assert_sanitized(captured)
assert captured["creationflags"] == CREATE_NO_WINDOW
-
-
-def test_doctor_sanitized_env_helper(monkeypatch):
- """The doctor MCP spawn site must pass the sanitized env to Popen.
-
- Behavioral check: intercept subprocess.Popen at the `_open_mcp` spawn
- seam and assert the env it receives strips secrets and applies the
- telemetry opt-out (no source-text inspection — that breaks on any
- refactor with identical runtime behavior)."""
- monkeypatch.setenv("ANTHROPIC_API_KEY", SECRET)
- monkeypatch.setenv("PATH", "/usr/bin:/bin")
- monkeypatch.delenv("HERMES_CUA_TELEMETRY", raising=False)
-
- from tools.computer_use import doctor
-
- env = doctor._sanitized_cua_env()
- assert "ANTHROPIC_API_KEY" not in env
- _assert_path_preserved(env)
- assert env.get("CUA_DRIVER_RS_TELEMETRY_ENABLED") == "0"
-
- # The Popen spawn site must actually use the sanitized helper.
- captured = {}
-
- class _FakeProc:
- stdin = None
- stdout = None
- stderr = None
-
- def _fake_popen(*args, **kwargs):
- captured["env"] = kwargs.get("env")
- return _FakeProc()
-
- monkeypatch.setattr(doctor.subprocess, "Popen", _fake_popen)
- doctor._open_mcp("cua-driver")
- spawn_env = captured["env"]
- assert spawn_env is not None, "_open_mcp must pass an explicit env"
- assert "ANTHROPIC_API_KEY" not in spawn_env
- assert spawn_env.get("CUA_DRIVER_RS_TELEMETRY_ENABLED") == "0"
diff --git a/tests/computer_use/test_doctor.py b/tests/computer_use/test_doctor.py
index 2798ca25c82..a1e4310fad4 100644
--- a/tests/computer_use/test_doctor.py
+++ b/tests/computer_use/test_doctor.py
@@ -82,34 +82,25 @@ def _degraded_report() -> dict:
[email protected](autouse=True)
def pm_driver(tmp_path, monkeypatch):
- """Exercise real passive PM selection; native driver probes are mocked below."""
import pm
from pm import paths
- from pm.store import tree_digest
+ from tests.computer_use.driver_fixture import record_driver
monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "tools"))
+ monkeypatch.setattr(paths, "lockfile_path", lambda: tmp_path / "lock.json")
monkeypatch.delenv("HERMES_CUA_DRIVER_CMD", raising=False)
- monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1")
monkeypatch.setattr(pm, "ensure", MagicMock(side_effect=AssertionError("doctor must not install")))
- package, target = pm.get_package("cua-driver"), pm.current_target()
- lock = pm.Lockfile(paths.lockfile_path())
- version = lock.version(package.name)
- assert version is not None
- root = paths.store_root()
- entry = root / package.store_entry(version, target)
- binary = package.binary(entry, target)
- assert binary is not None
- binary.parent.mkdir(parents=True)
- binary.write_bytes(Path(sys.executable).read_bytes())
- binary.chmod(0o755)
- pm.Facts(paths.facts_path()).record(
- package.name, version, entry.name, package.env(entry, target), root,
- target=target, artifacts=[a["sha256"] for a in lock.artifacts(package.name, target)],
- digest=tree_digest(entry),
- )
- return binary
+ return record_driver()
+
+
[email protected](autouse=True)
+def protocol_driver(request, monkeypatch):
+ # Only selection tests need a real PM store; protocol/rendering tests
+ # begin after binary selection and never execute the copied interpreter.
+ if request.cls is not TestDriverCmdResolution:
+ monkeypatch.setattr("tools.computer_use.cua_backend_driver.resolve_cua_driver_cmd", lambda cmd=None: "fixture-driver")
@pytest.fixture(autouse=True)
@@ -292,36 +283,21 @@ class TestJsonOutput:
class TestDriverCmdResolution:
- def test_explicit_driver_cmd_arg_wins(self, pm_driver, tmp_path, monkeypatch):
- from tools.computer_use import doctor
-
- explicit = tmp_path / pm_driver.name
- explicit.write_bytes(pm_driver.read_bytes())
- explicit.chmod(0o755)
- monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", str(pm_driver))
- proc = _fake_proc_with_responses(
- {"jsonrpc": "2.0", "id": 1, "result": {}},
- {"jsonrpc": "2.0", "id": 2, "result": {"structuredContent": _ok_report()}},
- )
- with patch.object(doctor, "_open_mcp", return_value=proc) as spawn, \
- patch("sys.stdout", new_callable=StringIO):
- assert doctor.run_doctor(driver_cmd=str(explicit)) == 0
- spawn.assert_called_once_with(str(explicit))
-
- def test_env_var_used_when_no_arg_given(self, pm_driver, tmp_path, monkeypatch):
+ @pytest.mark.parametrize("explicit", [False, True])
+ def test_override_selection(self, pm_driver, tmp_path, monkeypatch, explicit):
from tools.computer_use import doctor
external = tmp_path / pm_driver.name
external.write_bytes(pm_driver.read_bytes())
external.chmod(0o755)
- monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", str(external))
+ monkeypatch.setenv("HERMES_CUA_DRIVER_CMD", str(pm_driver if explicit else external))
proc = _fake_proc_with_responses(
{"jsonrpc": "2.0", "id": 1, "result": {}},
{"jsonrpc": "2.0", "id": 2, "result": {"structuredContent": _ok_report()}},
)
with patch.object(doctor, "_open_mcp", return_value=proc) as spawn, \
patch("sys.stdout", new_callable=StringIO):
- assert doctor.run_doctor() == 0
+ assert doctor.run_doctor(driver_cmd=str(external) if explicit else None) == 0
spawn.assert_called_once_with(str(external))
def test_pm_driver_is_found_when_path_omits_it(self, pm_driver, monkeypatch):
@@ -339,7 +315,7 @@ class TestDriverCmdResolution:
assert paths.facts_path().read_bytes() == before
@pytest.mark.parametrize("use_env", [False, True], ids=["argument", "environment"])
- def test_missing_override_does_not_fall_back_to_pm(self, tmp_path, monkeypatch, use_env, capsys):
+ def test_missing_override_does_not_fall_back_to_pm(self, pm_driver, tmp_path, monkeypatch, use_env, capsys):
from tools.computer_use import doctor
missing = str(tmp_path / "missing-driver")
diff --git a/tests/cron/test_file_permissions.py b/tests/cron/test_file_permissions.py
index 2068990b2ea..62442468058 100644
--- a/tests/cron/test_file_permissions.py
+++ b/tests/cron/test_file_permissions.py
@@ -15,7 +15,7 @@ from unittest.mock import patch
import pytest
-pytestmark = pytest.mark.platforms("linux")
+pytestmark = pytest.mark.platforms("posix")
class TestCronFilePermissions(unittest.TestCase):
diff --git a/tests/cron/test_parallel_pool.py b/tests/cron/test_parallel_pool.py
index 978b490c73d..76ac6537a5c 100644
--- a/tests/cron/test_parallel_pool.py
+++ b/tests/cron/test_parallel_pool.py
@@ -46,7 +46,8 @@ class TestPersistentPool:
class TestRunningJobGuard:
"""_running_job_ids prevents double-dispatch of active jobs."""
- def test_running_set_prevents_double_dispatch(self, tmp_path, monkeypatch):
+ @pytest.mark.parametrize("with_workdir", [False, True])
+ def test_running_set_prevents_double_dispatch(self, tmp_path, monkeypatch, with_workdir):
"""A job already in _running_job_ids is skipped on the next tick."""
import cron.scheduler as sched
@@ -65,6 +66,9 @@ class TestRunningJobGuard:
"deliver": "local",
}
+ if with_workdir:
+ job["workdir"] = str(tmp_path)
+
# Simulate the job already running.
sched._running_job_ids.add("guard-job")
@@ -229,7 +233,8 @@ class TestSyncMode:
sched._shutdown_parallel_pool()
- def test_sync_false_returns_immediately(self, tmp_path, monkeypatch):
+ @pytest.mark.parametrize("with_workdir", [False, True])
+ def test_sync_false_returns_immediately(self, tmp_path, monkeypatch, with_workdir):
"""The ticker returns while its dispatched worker is still blocked."""
import cron.scheduler as sched
@@ -247,55 +252,8 @@ class TestSyncMode:
"deliver": "local",
}
- worker_started = threading.Event()
- release = threading.Event()
- worker_finished = threading.Event()
-
- def slow_run(j, *, defer_agent_teardown=None, **_kw):
- worker_started.set()
- try:
- assert release.wait(timeout=10), "test never released the worker"
- finally:
- worker_finished.set()
- return True, "out", "resp", None
-
- monkeypatch.setattr(sched, "get_due_jobs", lambda: [job])
- monkeypatch.setattr(sched, "claim_job_for_fire", lambda *_a, **_kw: True)
- monkeypatch.setattr(sched, "run_job", slow_run)
- monkeypatch.setattr(sched, "save_job_output", lambda *_a, **_kw: "/tmp/out")
- monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None)
- monkeypatch.setattr(sched, "_deliver_result", lambda *_a, **_kw: None)
-
- try:
- assert sched.tick(verbose=False, sync=False) == 1
- assert worker_started.wait(timeout=10)
- assert not worker_finished.is_set()
- finally:
- release.set()
- sched._shutdown_parallel_pool()
-
-
-class TestWorkdirParallelPool:
- """Task-scoped workdir jobs use the normal persistent parallel pool."""
-
- def test_workdir_job_does_not_block_ticker(self, tmp_path, monkeypatch):
- """The ticker returns while its dispatched worker is still blocked."""
- import cron.scheduler as sched
-
- sched._parallel_pool = None
- sched._parallel_pool_max_workers = None
- sched._running_job_ids.clear()
-
- job = {
- "id": "slow-workdir",
- "name": "slow-workdir",
- "prompt": "test",
- "schedule": "every 5m",
- "enabled": True,
- "next_run_at": "2020-01-01T00:00:00",
- "deliver": "local",
- "workdir": str(tmp_path),
- }
+ if with_workdir:
+ job["workdir"] = str(tmp_path)
worker_started = threading.Event()
release = threading.Event()
@@ -324,42 +282,6 @@ class TestWorkdirParallelPool:
release.set()
sched._shutdown_parallel_pool()
- def test_workdir_running_guard_prevents_double_dispatch(self, tmp_path, monkeypatch):
- """A workdir job already in _running_job_ids is skipped on next tick."""
- import cron.scheduler as sched
-
- sched._parallel_pool = None
- sched._parallel_pool_max_workers = None
- sched._running_job_ids.clear()
-
- job = {
- "id": "guard-seq",
- "name": "guard-seq",
- "prompt": "test",
- "schedule": "every 5m",
- "enabled": True,
- "next_run_at": "2020-01-01T00:00:00",
- "deliver": "local",
- "workdir": str(tmp_path),
- }
-
- # Simulate the job already running.
- sched._running_job_ids.add("guard-seq")
-
- dispatched = []
- monkeypatch.setattr(sched, "get_due_jobs", lambda: [job])
- monkeypatch.setattr(sched, "claim_job_for_fire", lambda *_a, **_kw: True)
- monkeypatch.setattr(sched, "run_job", lambda j, **_kw: dispatched.append(j["id"]) or (True, "out", "resp", None))
- monkeypatch.setattr(sched, "save_job_output", lambda *_a, **_kw: None)
- monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None)
- monkeypatch.setattr(sched, "_deliver_result", lambda *_a, **_kw: None)
-
- n = sched.tick(verbose=False)
- assert n == 0 # skipped, not dispatched
- assert dispatched == []
-
- sched._running_job_ids.discard("guard-seq")
- sched._shutdown_parallel_pool()
class TestTickBatchAdvance:
"""The tick's pre-dispatch advance must go through advance_next_runs
diff --git a/tests/cron/test_script_claim_heartbeat.py b/tests/cron/test_script_claim_heartbeat.py
index 7849a1e3b51..bc9c409c6e7 100644
--- a/tests/cron/test_script_claim_heartbeat.py
+++ b/tests/cron/test_script_claim_heartbeat.py
@@ -2,7 +2,6 @@
from datetime import datetime, timedelta, timezone
import contextlib
-import sys
import threading
import time
from unittest.mock import MagicMock, patch
@@ -10,178 +9,65 @@ from unittest.mock import MagicMock, patch
import 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."""
[email protected]_system_guard_bypass
[email protected]("trigger", ["cancel", "timeout"])
[email protected]("topology", ["detached", "stubborn-pipe"])
+def test_script_termination_reaps_descendants(tmp_path, monkeypatch, trigger, topology):
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
-
-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
- from cron import scheduler_script as sched_script
+ import psutil
+ from cron import scheduler, scheduler_script
monkeypatch.setattr(scheduler, "_get_hermes_home", lambda: tmp_path)
- # Under the hermetic runner sys.executable can be an emulated binary
- # whose children fail to spawn; cron resolves the script interpreter
- # from sys.executable, so pin it to one that actually works here.
- monkeypatch.setattr(scheduler.sys, "executable", _spawnable_python())
- scripts_dir = tmp_path / "scripts"
- scripts_dir.mkdir()
- PY = _spawnable_python() # interpreter the spawned script uses for grandchildren
- started = tmp_path / "started"
- child_done = tmp_path / "child-done"
- script = scripts_dir / "blocking.py"
- child_code = (
- "import time; from pathlib import Path; "
- # Long sleep: the descendant must outlive the tree-kill's worst-case
- # latency under load — child_done within the assertion window can
- # then ONLY mean the kill missed it, never that it finished on its
- # own (which a 1s sleep would allow under 36-way CPU contention).
- f"time.sleep(10); Path({str(child_done)!r}).write_text('done')"
- )
- script.write_text(
- "import subprocess, sys, time\n"
- f"subprocess.Popen([{PY!r}, '-c', {child_code!r}])\n"
- f"open({str(started)!r}, 'w').close()\n"
- "time.sleep(30)\n",
- encoding="utf-8",
- )
-
- cancel = threading.Event()
- result = []
- errors = []
-
- def _run() -> None:
+ monkeypatch.setattr(scheduler_script, "_get_script_timeout", lambda: 3 if trigger == "timeout" else 60)
+ scripts = tmp_path / "scripts"
+ scripts.mkdir()
+ ready = tmp_path / "child.pid"
+ child = ("import os, signal, time; from pathlib import Path; "
+ + ("signal.signal(signal.SIGTERM, signal.SIG_IGN); " if topology == "stubborn-pipe" else "")
+ + f"Path({str(ready)!r}).write_text(str(os.getpid())); time.sleep(60)")
+ script = scripts / "blocking.py"
+ script.write_text("import subprocess, sys, time\n"
+ + f"subprocess.Popen([sys.executable, '-c', {child!r}], start_new_session={topology == 'detached'})\n"
+ + "time.sleep(60)\n", encoding="utf-8")
+ cancel, results, errors = threading.Event(), [], []
+ def run():
try:
- result.append(
- sched_script._run_job_script(
- str(script),
- workdir=str(tmp_path),
- cancel_event=cancel,
- )
- )
- except Exception as exc:
+ results.append(scheduler_script._run_job_script(str(script), workdir=str(tmp_path), cancel_event=cancel))
+ except BaseException as exc:
errors.append(exc)
-
- thread = threading.Thread(target=_run)
- thread.start()
- # Generous deadline: under 36-way parallel load the spawned
- # interpreter's cold start can exceed 5s on first attempt.
- deadline = time.monotonic() + 15
- while not started.exists() and not errors and time.monotonic() < deadline:
- time.sleep(0.01)
- assert errors == []
- assert started.exists(), "script did not start"
-
- cancel.set()
- # The tree-kill (taskkill /T under load) can take several seconds when
- # 36 parallel test workers compete for the CPU — generous join bound.
- thread.join(timeout=15)
-
- assert errors == []
- assert not thread.is_alive(), "script ignored cancellation"
- assert result and result[0][0] is False
- assert "cancel" in result[0][1].lower()
- time.sleep(1.2)
- assert not child_done.exists(), "script descendant survived cancellation"
-
-
[email protected](sys.platform == "win32", reason="POSIX process-group semantics")
-def test_cancel_event_kills_sigterm_ignoring_descendant(tmp_path, monkeypatch):
- """A SIGTERM-ignoring grandchild must not wedge the cancellation path:
- the tree kill escalates to SIGKILL for surviving group members, and the
- pipe drain is bounded even if a descendant still holds the write ends."""
- import cron.scheduler as scheduler
- from cron import scheduler_script as sched_script
-
- monkeypatch.setattr(scheduler, "_get_hermes_home", lambda: tmp_path)
- # Under the hermetic runner sys.executable can be an emulated binary
- # whose children fail to spawn; cron resolves the script interpreter
- # from sys.executable, so pin it to one that actually works here.
- monkeypatch.setattr(scheduler.sys, "executable", _spawnable_python())
- scripts_dir = tmp_path / "scripts"
- scripts_dir.mkdir()
- PY = _spawnable_python() # interpreter the spawned script uses for grandchildren
- started = tmp_path / "started"
- script = scripts_dir / "stubborn.py"
- child_code = (
- "import signal, time; "
- "signal.signal(signal.SIGTERM, signal.SIG_IGN); "
- f"open({str(started)!r}, 'w').close(); "
- "time.sleep(60)"
- )
- script.write_text(
- "import subprocess, sys, time\n"
- f"subprocess.Popen([{PY!r}, '-c', {child_code!r}])\n"
- "time.sleep(60)\n",
- encoding="utf-8",
- )
-
- cancel = threading.Event()
- result = []
- errors = []
-
- def _run() -> None:
+ def live(pid):
try:
- result.append(
- sched_script._run_job_script(
- str(script),
- workdir=str(tmp_path),
- cancel_event=cancel,
- )
- )
- except Exception as exc:
- errors.append(exc)
-
- thread = threading.Thread(target=_run)
+ return psutil.Process(pid).status() != psutil.STATUS_ZOMBIE
+ except psutil.NoSuchProcess:
+ return False
+ thread = threading.Thread(target=run)
thread.start()
- # Generous deadline: under 36-way parallel load the spawned
- # interpreter's cold start can exceed 5s on first attempt.
- deadline = time.monotonic() + 15
- while not started.exists() and not errors and time.monotonic() < deadline:
- time.sleep(0.01)
- assert errors == []
- assert started.exists(), "script did not spawn its descendant"
-
- cancel.set()
- # TERM grace (1s) + KILL + bounded drain (5s) + margin: must return well
- # before the unbounded-communicate hang this regresses against.
- thread.join(timeout=10)
-
- assert errors == []
- assert not thread.is_alive(), "cancellation wedged on a SIGTERM-ignoring descendant"
- assert result and result[0][0] is False
- assert "cancel" in result[0][1].lower()
+ pid = None
+ try:
+ deadline = time.monotonic() + 10
+ while not ready.exists() and not errors and time.monotonic() < deadline:
+ time.sleep(0.01)
+ assert ready.exists() and not errors, errors
+ pid = int(ready.read_text(encoding="utf-8"))
+ assert live(pid), "child must acknowledge readiness before termination"
+ if trigger == "cancel":
+ cancel.set()
+ thread.join(timeout=15)
+ assert not thread.is_alive() and not errors, errors
+ assert results[0][0] is False
+ assert ("cancelled" if trigger == "cancel" else "timed out") in results[0][1]
+ deadline = time.monotonic() + 5
+ while live(pid) and time.monotonic() < deadline:
+ time.sleep(0.05)
+ assert not live(pid), f"descendant {pid} survived {trigger}"
+ finally:
+ cancel.set()
+ if pid is None and ready.exists():
+ pid = int(ready.read_text(encoding="utf-8"))
+ if pid is not None and live(pid):
+ os.kill(pid, 9)
+ thread.join(timeout=15)
def test_no_agent_forwards_cancel_event_to_script_runner(monkeypatch):
diff --git a/tests/desktop/test_appinstaller_check_script.py b/tests/desktop/test_appinstaller_check_script.py
index 3b465cbaaf8..db68412c110 100644
--- a/tests/desktop/test_appinstaller_check_script.py
+++ b/tests/desktop/test_appinstaller_check_script.py
@@ -29,100 +29,73 @@ SCRIPT = (
/ "apps/desktop/scripts/check-appinstaller-update.py"
)
-_NO_PACKAGE_IDENTITY_HRESULT = -2147009196 # 0x80073D54
-
-
-def _stub_module(*, identity_error: bool, availability: str | None, check_raises: bool) -> str:
- current_body = (
- " exc = OSError('The process has no package identity.')\n"
- f" exc.winerror = {_NO_PACKAGE_IDENTITY_HRESULT}\n"
- " raise exc"
- if identity_error
- else " return _FakePackage()"
- )
- get_body = (
- ' raise RuntimeError("rpc boom")'
- if check_raises
- else " return _AvailabilityResult(self._availability)"
- )
- check_body = (
- ' raise RuntimeError("winrt blew up")'
- if check_raises
- else f" return _AsyncOp({availability!r})"
- )
- return "\n".join(
- [
- "import enum",
- "",
- "class PackageUpdateAvailability(enum.Enum):",
- ' UNKNOWN = "unknown"',
- ' NO_UPDATES = "noUpdates"',
- ' AVAILABLE = "available"',
- ' REQUIRED = "required"',
- ' ERROR = "error"',
- "",
- "class _AvailabilityResult:",
- " def __init__(self, availability):",
- " self.availability = availability",
- "",
- "class _AsyncOp:",
- " def __init__(self, availability):",
- " self._availability = availability",
- "",
- " def get(self):",
- get_body,
- "",
- "class _FakePackage:",
- " def get_app_installer_info(self):",
- " from types import SimpleNamespace",
- " return SimpleNamespace(uri=SimpleNamespace(absolute_uri='https://registered.example/updates.appinstaller'))",
- " def check_update_availability_async(self):",
- check_body,
- "",
- "class _PackageMeta(type):",
- " @property",
- " def current(cls):",
- current_body,
- "",
- "class Package(metaclass=_PackageMeta):",
- " pass",
- "",
- ]
- )
-
-
-def _stub_winrt(tmp_path: Path, package_module: str) -> Path:
- """Render a stub winrt tree whose Package comes from ``package_module``.
- PackageManager deliberately has NO check_package_update_availability_async:
- the real projection's shape is part of the contract under test."""
- root = tmp_path / "stub"
- appmodel = root / "winrt/windows/applicationmodel"
- deployment = root / "winrt/windows/management/deployment"
- for d in (appmodel, deployment):
- d.mkdir(parents=True)
- (root / "winrt/__init__.py").write_text("")
- (root / "winrt/windows/__init__.py").write_text("")
- (root / "winrt/windows/management/__init__.py").write_text("")
- (deployment / "__init__.py").write_text("from .deployment import PackageManager\n")
- (deployment / "deployment.py").write_text(
- "class PackageManager:\n"
- " # No check_package_update_availability_async — it does not exist in\n"
- " # the real projection; the method lives on Package instances.\n"
- " pass\n"
- )
- (appmodel / "__init__.py").write_text(package_module)
- return root
-
-
-def _run(root: Path) -> tuple[int, dict]:
- env = {"PYTHONPATH": str(root)}
- if os.environ.get("SYSTEMROOT"):
- env["SYSTEMROOT"] = os.environ["SYSTEMROOT"]
- proc = subprocess.run(
- [HERMES_PYTHON, str(SCRIPT)],
- capture_output=True, text=True, timeout=60, env=env,
- )
- return proc.returncode, json.loads(proc.stdout.strip().splitlines()[-1])
[email protected]("state,code,available", [
+ ("not-packaged", 0, False), ("AVAILABLE", 2, True), ("REQUIRED", 2, True),
+ ("NO_UPDATES", 0, False), ("UNKNOWN", 1, None), ("ERROR", 1, None),
+ ("no-source", 1, None), ("check-error", 1, None), ("identity-error", 1, None),
+ ("missing-projection", 1, None), ("missing-current", 1, None),
+])
+def test_projection_outcomes(monkeypatch, capsys, state, code, available):
+ import enum
+ import runpy
+ from types import SimpleNamespace
+
+ main = runpy.run_path(str(SCRIPT))["main"]
+ availability = enum.IntEnum("Availability", "UNKNOWN NO_UPDATES AVAILABLE REQUIRED ERROR", start=0)
+ class PackageInstance:
+ def get_app_installer_info(self):
+ return None if state == "no-source" else SimpleNamespace(
+ uri=SimpleNamespace(absolute_uri="https://registered.example/updates.appinstaller"))
+
+ def check_update_availability_async(self):
+ def get():
+ if state == "check-error":
+ raise RuntimeError("rpc boom")
+ return SimpleNamespace(availability=availability[state])
+ return SimpleNamespace(get=get)
+
+ class PackageMeta(type):
+ @property
+ def current(cls):
+ if state in ("not-packaged", "identity-error"):
+ error = OSError("identity failure")
+ error.winerror = -2147009196 if state == "not-packaged" else -2147024891
+ raise error
+ return PackageInstance()
+
+ class Package(metaclass=PackageMeta):
+ pass
+
+ def load():
+ if state == "missing-projection":
+ raise ImportError("missing winrt")
+ return (object if state == "missing-current" else Package), availability
+
+ monkeypatch.setitem(main.__globals__, "_load_projection", load)
+ assert main() == code
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["available"] is available
+ if state == "not-packaged":
+ assert payload == {"available": False, "reason": "not-packaged"}
+ elif state in ("AVAILABLE", "REQUIRED", "NO_UPDATES"):
+ assert payload["availability"] == state
+ assert payload["source_uri"] == "https://registered.example/updates.appinstaller"
+ else:
+ assert payload["error"]
+ if state == "no-source":
+ assert payload["reason"] == "no-app-installer-source"
+ assert ".appinstaller" in payload["error"]
+
+
+def test_script_import_failure_json_and_exit(tmp_path):
+ # A real subprocess executes __main__ and imports the absent projection.
+ (tmp_path / "winrt.py").write_text("raise ImportError('fixture unavailable')", encoding="utf-8")
+ child = subprocess.run([HERMES_PYTHON, str(SCRIPT)], capture_output=True,
+ text=True, timeout=30, env={**os.environ, "PYTHONPATH": str(tmp_path)})
+ assert child.returncode == 1, child.stderr
+ payload = json.loads(child.stdout)
+ assert payload["available"] is None
+ assert "fixture unavailable" in payload["error"]
@pytest.mark.platforms("windows")
@@ -142,90 +115,3 @@ def test_installed_winrt_projects_checker_uri_and_async_types(tmp_path):
)
assert probe.returncode == 0, probe.stderr
assert probe.stdout.strip() == "WINRT_CHECKER_TYPES_OK"
-
-
-def test_not_packaged_is_reported_as_not_packaged(tmp_path):
- root = _stub_winrt(tmp_path, _stub_module(identity_error=True, availability=None, check_raises=False))
- code, payload = _run(root)
- assert code == 0
- assert payload == {"available": False, "reason": "not-packaged"}
-
-
-def test_update_available_exit_2(tmp_path):
- root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability="available", check_raises=False))
- code, payload = _run(root)
- assert code == 2
- assert payload["available"] is True
- assert payload["availability"] == "AVAILABLE"
- assert payload["source_uri"] == "https://registered.example/updates.appinstaller"
-
-
-def test_no_update_exit_0(tmp_path):
- root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability="noUpdates", check_raises=False))
- code, payload = _run(root)
- assert code == 0
- assert payload["available"] is False
-
-
-def test_unknown_availability_is_not_no_update(tmp_path):
- """UNKNOWN (enum 0) is an unknown, never available:false (C06-09 review)."""
- root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability="unknown", check_raises=False))
- code, payload = _run(root)
- assert code == 1
- assert payload["available"] is None
- assert "error" in payload
-
-
-def test_error_availability_is_not_no_update(tmp_path):
- """ERROR (enum 4) is an unknown with an extended error, never available:false."""
- root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability="error", check_raises=False))
- code, payload = _run(root)
- assert code == 1
- assert payload["available"] is None
- assert "error" in payload
-
-
-def test_missing_appinstaller_source_explains_the_remedy(tmp_path):
- module = _stub_module(identity_error=False, availability="unknown", check_raises=False).replace(
- "return SimpleNamespace(uri=SimpleNamespace(absolute_uri='https://registered.example/updates.appinstaller'))",
- "return None",
- )
- root = _stub_winrt(tmp_path, module)
- code, payload = _run(root)
- assert code == 1
- assert payload["available"] is None
- assert payload["reason"] == "no-app-installer-source"
- assert ".appinstaller" in payload["error"]
-
-
-def test_check_failure_is_unknown_not_no_update(tmp_path):
- root = _stub_winrt(tmp_path, _stub_module(identity_error=False, availability=None, check_raises=True))
- code, payload = _run(root)
- assert code == 1
- assert payload["available"] is None
- assert "error" in payload
-
-
-def test_unexpected_package_identity_error_is_unknown(tmp_path):
- """A non-identity failure while reading the current package is a real
- error — it must never masquerade as not-packaged (available:false)."""
- module = _stub_module(identity_error=False, availability="available", check_raises=False).replace(
- " return _FakePackage()",
- ' raise OSError(5, "access denied", None, -2147024891)',
- )
- root = _stub_winrt(tmp_path, module)
- code, payload = _run(root)
- assert code == 1
- assert payload["available"] is None
-
-
-def test_projection_without_current_property_is_unknown(tmp_path):
- """A projection that does not expose the current-package static must
- degrade to unknown — the checker may not guess an API shape."""
- module = _stub_module(identity_error=False, availability="available", check_raises=False).replace(
- "class Package(metaclass=_PackageMeta):", "class PackageNotProjected(metaclass=_PackageMeta):"
- )
- root = _stub_winrt(tmp_path, module)
- code, payload = _run(root)
- assert code == 1
- assert payload["available"] is None
diff --git a/tests/docker/test_dump_build_sha.py b/tests/docker/test_dump_build_sha.py
index 56a2dbaea75..9932e839509 100644
--- a/tests/docker/test_dump_build_sha.py
+++ b/tests/docker/test_dump_build_sha.py
@@ -21,6 +21,8 @@ This test asserts both cases:
from __future__ import annotations
import json
+import os
+from pathlib import Path
import re
import subprocess
@@ -81,6 +83,17 @@ def test_dump_reports_stamp_commit_when_present(built_image: str) -> None:
that breaks the stamp -> dump pipeline will fail CI here.
"""
stamped = _read_stamp_commit_from_image(built_image)
+ # docker.yml writes this build input before building and testing the image.
+ # Read the independent input: the canonical runner scrubs CI/GITHUB_SHA.
+ source_stamp = Path(__file__).resolve().parents[2] / "install-stamp.json"
+ if os.environ.get("HERMES_TEST_IMAGE"):
+ assert source_stamp.is_file(), "prebuilt image requires its checkout build stamp"
+ if source_stamp.is_file():
+ expected = json.loads(source_stamp.read_text(encoding="utf-8-sig"))["commit"]
+ assert re.fullmatch(r"[0-9a-f]{40}", expected), "invalid expected build commit"
+ assert stamped == expected, "image lost or changed its build provenance"
+ if stamped is not None:
+ assert re.fullmatch(r"[0-9a-f]{40}", stamped), "malformed image stamp commit"
stdout = _run_dump(built_image)
match = _VERSION_LINE.search(stdout)
diff --git a/tests/gateway/test_matrix.py b/tests/gateway/test_matrix.py
index 063c8c8673a..1e250231c0d 100644
--- a/tests/gateway/test_matrix.py
+++ b/tests/gateway/test_matrix.py
@@ -874,38 +874,6 @@ class TestMatrixRequirements:
with patch.object(builtins, "__import__", _blocking_import):
assert _check_e2ee_deps() is False
- def test_check_requirements_runs_lazy_install_when_partial(self, monkeypatch):
- """When mautrix is installed but asyncpg/aiosqlite are missing,
- check_matrix_requirements must still run the lazy installer.
-
- Regression for #31116: the previous ``try: import mautrix`` gate
- short-circuited the install of the OTHER 4 platform.matrix packages,
- so a partial install (mautrix only) was treated as fully installed.
- """
- monkeypatch.setenv("MATRIX_ACCESS_TOKEN", "syt_test")
- monkeypatch.setenv("MATRIX_HOMESERVER", "https://matrix.example.org")
- monkeypatch.delenv("MATRIX_ENCRYPTION", raising=False)
-
- import plugins.platforms.matrix.adapter as matrix_mod
-
- # Simulate "mautrix installed, asyncpg missing" → feature_missing
- # returns a non-empty tuple → ensure_and_bind MUST be called.
- called = {"ensure_and_bind": False}
-
- def _fake_ensure_and_bind(feature, importer, target_globals, **kwargs):
- called["ensure_and_bind"] = True
- assert feature == "matrix"
- return True # Pretend install succeeded.
-
- with patch("pm.extras.missing", return_value=("asyncpg==0.31.0",)), \
- patch("pm.extras.ensure_and_bind", side_effect=_fake_ensure_and_bind):
- matrix_mod.check_matrix_requirements()
-
- assert called["ensure_and_bind"], (
- "check_matrix_requirements must call ensure_and_bind whenever ANY "
- "platform.matrix dep is missing, not just when mautrix itself is "
- "missing (#31116)"
- )
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_matrix_deps_rebind.py b/tests/gateway/test_matrix_deps_rebind.py
index 5825ba0e7be..7e848c8a788 100644
--- a/tests/gateway/test_matrix_deps_rebind.py
+++ b/tests/gateway/test_matrix_deps_rebind.py
@@ -22,46 +22,15 @@ def _fake_mautrix_types():
"""Minimal mautrix.types with the 8 names the adapter imports/binds."""
mod = types.ModuleType("mautrix.types")
- class EventType:
- ROOM_MESSAGE = "m.room.message"
- REACTION = "m.reaction"
-
- class UserID(str):
- pass
-
- class RoomID(str):
- pass
-
- class EventID(str):
- pass
-
- class ContentURI(str):
- pass
-
- class RoomCreatePreset:
- PRIVATE = "private_chat"
-
- class PresenceState:
- ONLINE = "online"
-
- class TrustState:
- UNVERIFIED = 0
-
- mod.EventType = EventType
- mod.UserID = UserID
- mod.RoomID = RoomID
- mod.EventID = EventID
- mod.ContentURI = ContentURI
- mod.RoomCreatePreset = RoomCreatePreset
- mod.PresenceState = PresenceState
- mod.TrustState = TrustState
+ for name in ("EventType", "UserID", "RoomID", "EventID", "ContentURI",
+ "RoomCreatePreset", "PresenceState", "TrustState"):
+ setattr(mod, name, object())
return mod
[email protected](params=[(), ("asyncpg",)], ids=["installed", "fresh"])
-def fresh_dependency_boundary(monkeypatch, request):
- """Installed and fresh dependencies both bind through PM's single operation."""
- monkeypatch.setattr(pm_extras, "missing", lambda extra: request.param)
+def fresh_dependency_boundary(monkeypatch):
+ """Exercise the real importer after PM admits the SDK."""
monkeypatch.setattr(pm_extras, "ensure_import", lambda *a, **kw: None)
monkeypatch.delenv("MATRIX_E2EE_MODE", raising=False)
monkeypatch.delenv("MATRIX_ENCRYPTION", raising=False)
diff --git a/tests/gateway/test_matrix_mention.py b/tests/gateway/test_matrix_mention.py
index 54fe03ef30a..65c893a7802 100644
--- a/tests/gateway/test_matrix_mention.py
+++ b/tests/gateway/test_matrix_mention.py
@@ -329,58 +329,29 @@ async def test_dm_mention_thread_creates_thread(monkeypatch):
assert msg.text == "help me"
-# ---------------------------------------------------------------------------
-# YAML config bridge
-# ---------------------------------------------------------------------------
-
-
-class TestMatrixConfigBridge:
- def test_yaml_bridge_sets_env_vars(self, monkeypatch, tmp_path):
- """Matrix YAML config should bridge to env vars."""
- monkeypatch.delenv("MATRIX_REQUIRE_MENTION", raising=False)
- monkeypatch.delenv("MATRIX_FREE_RESPONSE_ROOMS", raising=False)
- monkeypatch.delenv("MATRIX_AUTO_THREAD", raising=False)
-
- yaml_content = {
- "matrix": {
- "require_mention": False,
- "free_response_rooms": ["!room1:example.org", "!room2:example.org"],
- "auto_thread": False,
- }
- }
-
- import os
-
- import hermes_yaml as yaml
-
- config_file = tmp_path / "config.yaml"
- config_file.write_text(yaml.safe_dump(yaml_content))
-
- # Simulate the bridge logic from gateway/config.py
- yaml_cfg = yaml.safe_load(config_file.read_text())
- matrix_cfg = yaml_cfg.get("matrix", {})
- if isinstance(matrix_cfg, dict):
- if "require_mention" in matrix_cfg and not os.getenv(
- "MATRIX_REQUIRE_MENTION"
- ):
- monkeypatch.setenv(
- "MATRIX_REQUIRE_MENTION", str(matrix_cfg["require_mention"]).lower()
- )
- frc = matrix_cfg.get("free_response_rooms")
- if frc is not None and not os.getenv("MATRIX_FREE_RESPONSE_ROOMS"):
- if isinstance(frc, list):
- frc = ",".join(str(v) for v in frc)
- monkeypatch.setenv("MATRIX_FREE_RESPONSE_ROOMS", str(frc))
- if "auto_thread" in matrix_cfg and not os.getenv("MATRIX_AUTO_THREAD"):
- monkeypatch.setenv(
- "MATRIX_AUTO_THREAD", str(matrix_cfg["auto_thread"]).lower()
- )
-
- assert os.getenv("MATRIX_REQUIRE_MENTION") == "false"
- assert (
- os.getenv("MATRIX_FREE_RESPONSE_ROOMS")
- == "!room1:example.org,!room2:example.org"
[email protected]("existing", [None, "operator"])
[email protected]("secondary", [False, True])
+def test_yaml_bridge_respects_scope_and_existing_env(monkeypatch, existing, secondary):
+ import os
+ from agent.secret_scope import set_multiplex_active, set_secret_scope, reset_secret_scope
+ from plugins.platforms.matrix.adapter import _apply_yaml_config
+
+ expected = {"MATRIX_REQUIRE_MENTION": "false", "MATRIX_AUTO_THREAD": "false",
+ "MATRIX_FREE_RESPONSE_ROOMS": "!one:example.org,!two:example.org"}
+ config = {"require_mention": False, "auto_thread": False,
+ "free_response_rooms": ["!one:example.org", "!two:example.org"]}
+ for key in expected:
+ monkeypatch.delenv(key, raising=False)
+ if existing is not None:
+ monkeypatch.setenv(key, existing)
+ token = set_secret_scope({}) if secondary else None
+ set_multiplex_active(secondary)
+ try:
+ assert _apply_yaml_config({"matrix": config}, config) == config
+ assert {key: os.environ.get(key) for key in expected} == (
+ dict.fromkeys(expected, existing) if secondary or existing else expected
)
- assert os.getenv("MATRIX_AUTO_THREAD") == "false"
-
-
+ finally:
+ if token is not None:
+ reset_secret_scope(token)
+ set_multiplex_active(False)
diff --git a/tests/gateway/test_pm_activation.py b/tests/gateway/test_pm_activation.py
index 632f02f53bf..ca7c56c3022 100644
--- a/tests/gateway/test_pm_activation.py
+++ b/tests/gateway/test_pm_activation.py
@@ -1,112 +1,31 @@
-"""Gateway main() must run the pm startup contract (gateway/run.py).
+"""Gateway startup remains fail-open when PM admission itself fails.
-The gateway daemon boots via its own entrypoint and never passes through the
-CLI dispatch in hermes_cli/main.py — without an explicit call here the
-gateway's os.environ PATH would lack the pm store's tool dirs (git/bash/
-ffmpeg/...), so every reactive ``shutil.which`` inside the daemon resolves
-system binaries (or nothing) instead of the pinned store ones.
-
-Behavior contract (mirrors the CLI-dispatch block, hermes_cli/main.py):
-- healthy store → ``pm.activate()`` provisions PATH
-- out-of-sync store → warning, boot continues (never blocks)
-- pm import/lookup failure → debug-logged, boot continues
+Healthy/damaged real-store activation belongs to tests/pm/test_startup_activation.py.
"""
-
-from __future__ import annotations
-
-import os
-from unittest.mock import patch
+from unittest.mock import AsyncMock
import pytest
-def gateway_main(monkeypatch, tmp_path):
- """Import gateway.run.main with the heavy boot machinery neutralized."""
- # The real main() advertises env vars, registers process identity, runs
- # boot bootstrap, and FORCE-EXITS via _exit_after_graceful_shutdown
- # (os._exit — wedge-proof by design, #53107) — none of it is what we
- # assert on. Neutralize the exit + the async boot; keep the pm block's
- # imports real.
- import gateway.run as gr
-
- async def _no_gateway(_config=None, **_kwargs):
- return True
-
- exited: list[int] = []
-
- def _fake_exit(code):
- exited.append(code)
-
- monkeypatch.setattr(gr, "start_gateway", _no_gateway)
- monkeypatch.setattr(gr, "_exit_after_graceful_shutdown", _fake_exit)
- monkeypatch.setattr(
- "hermes_cli.boot_bootstrap.maybe_run_boot_bootstrap", lambda _root: None
- )
-
- def _main():
- gr.main()
- return exited
-
- return _main
-
-
-def test_gateway_main_activates_pm_store(gateway_main, tmp_path, monkeypatch):
- """A healthy store: main() provisions PATH before starting adapters."""
- calls: list[str] = []
-
- class _FakePm:
- @staticmethod
- def adopt():
- calls.append("adopt")
-
- @staticmethod
- def activate():
- calls.append("activate")
- return [] # healthy
-
- import sys
-
- monkeypatch.setitem(sys.modules, "pm", _FakePm)
- with patch("sys.argv", ["gateway"]):
- gateway_main()
- assert calls == ["adopt", "activate"]
-
-
-def test_gateway_main_warns_but_boots_when_store_out_of_sync(
- gateway_main, monkeypatch, caplog
-):
- """An out-of-sync store surfaces a warning and NEVER blocks the boot."""
-
- class _FakePm:
- @staticmethod
- def adopt():
- pass
-
- @staticmethod
- def activate():
- return ["uv not installed", "ffmpeg outdated"]
-
- import sys
-
- monkeypatch.setitem(sys.modules, "pm", _FakePm)
- with patch("sys.argv", ["gateway"]):
- gateway_main()
- assert any(
- "install out of sync" in rec.message for rec in caplog.records
- ), "the out-of-sync warning must be logged"
-
-
-def test_gateway_main_survives_pm_failure(gateway_main, monkeypatch):
- """A broken pm import is debug-logged; the gateway still boots."""
-
- class _ExplodingPm:
- @staticmethod
- def adopt():
- raise RuntimeError("pm exploded")
-
- import sys
-
- monkeypatch.setitem(sys.modules, "pm", _ExplodingPm)
- with patch("sys.argv", ["gateway"]):
- gateway_main() # must not raise
[email protected]("boundary", ["adopt", "activate"])
+def test_gateway_main_survives_pm_failure(monkeypatch, boundary):
+ import pm
+ import gateway.run as gateway
+
+ failed = []
+ def broken():
+ failed.append(boundary)
+ raise RuntimeError("PM unavailable")
+
+ monkeypatch.setattr(pm, "adopt", lambda: None)
+ monkeypatch.setattr(pm, boundary, broken)
+ started = AsyncMock(return_value=True)
+ exited = []
+ monkeypatch.setattr(gateway, "start_gateway", started)
+ monkeypatch.setattr(gateway, "_exit_after_graceful_shutdown", exited.append)
+ monkeypatch.setattr("hermes_cli.boot_bootstrap.maybe_run_boot_bootstrap", lambda root: None)
+ monkeypatch.setattr("sys.argv", ["gateway"])
+ gateway.main()
+ started.assert_awaited_once()
+ assert exited == [0]
+ assert failed == [boundary]
diff --git a/tests/plugins/memory/test_hindsight_embedded_runtime.py b/tests/plugins/memory/test_hindsight_embedded_runtime.py
index 1a1e5f998d3..f706eb0f6fc 100644
--- a/tests/plugins/memory/test_hindsight_embedded_runtime.py
+++ b/tests/plugins/memory/test_hindsight_embedded_runtime.py
@@ -1,15 +1,13 @@
-"""The isolated local_embedded Hindsight runtime (embedded_runtime).
+"""Hindsight's shipped probe and bridge execute in an isolated side interpreter.
-Real plugin imports with fakes at PM's operation interface and the side-python
-bridge. Generation ownership is tested in tests/pm; here the URL the
-daemon reports is proven against a real loopback HTTP /health server, never a
-constant port. The boot-selected main environment is never touched.
+The tiny SDK models only the child protocol, not upstream ML/CPU compatibility.
+PM generation acquisition is owned by tests/pm; no upstream downloads occur here.
"""
-
-import http.server
import json
+import os
import subprocess
-import threading
+import sys
+from pathlib import Path
from types import SimpleNamespace
import pytest
@@ -24,10 +22,6 @@ def side_root(tmp_path, monkeypatch):
return root
-def _fake_completed(returncode=0, stdout="", stderr=""):
- return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)
-
-
def test_ensure_sideenv_uses_pm_selected_python(side_root, monkeypatch):
import pm
from hermes_constants import venv_python_path
@@ -61,200 +55,118 @@ def test_sideenv_python_is_pm_passive_selection(side_root, monkeypatch):
assert not side_root.exists()
-# -- runtime probe: side interpreter, never the boot env ----------------------
-
-
-def test_check_local_runtime_probes_the_side_python(side_root, monkeypatch):
- py = _install_side_python(side_root, monkeypatch)
- seen = {}
-
- def fake_run(cmd, **kw):
- seen["cmd"] = list(cmd)
- return _fake_completed()
+def side_python(side_root, monkeypatch, tmp_path):
+ import pm
- monkeypatch.setattr(rt.subprocess, "run", fake_run)
+ subprocess.run([sys.executable, "-m", "venv", "--without-pip", str(side_root)],
+ check=True, capture_output=True, timeout=30)
+ from hermes_constants import venv_python_path
+ python = venv_python_path(side_root)
+ site = Path(subprocess.check_output(
+ [str(python), "-c", "import sysconfig; print(sysconfig.get_path('purelib'))"],
+ text=True, timeout=10,
+ ).strip())
+ sdk = site / "hindsight_embed"
+ sdk.mkdir()
+ (sdk / "__init__.py").touch()
+ for module in (sdk / "daemon_embed_manager.py", site / "hindsight_api.py", site / "sentence_transformers.py"):
+ module.write_text("", encoding="utf-8")
+ (sdk / "daemon_client.py").write_text("""import json, os, sys
+from pathlib import Path
+stopped = None
+def stop_daemon(profile):
+ global stopped
+ stopped = profile
+def ensure_daemon_running(config, profile):
+ Path(os.environ['TEST_RECEIPT']).write_text(json.dumps({
+ 'config': config, 'profile': profile, 'stopped': stopped,
+ 'prefix': sys.prefix, 'env': dict(os.environ)}), encoding='utf-8')
+ print('manager startup noise')
+ return True
+def get_daemon_url(profile):
+ return 'http://127.0.0.1:54321/' + profile
+""", encoding="utf-8")
+ receipt = tmp_path / "bridge.json"
+ monkeypatch.setenv("TEST_RECEIPT", str(receipt))
+ monkeypatch.setattr(pm, "environment_python", lambda *a, **kw: python)
+ return site, receipt
+
+
[email protected]("grace,override,expected", [
+ (60, None, "60.0"), ("45", None, "45.0"), (0, None, "0.0"),
+ (None, None, None), ("", None, None), ("invalid", None, None),
+ (-5, None, None), (60, "99", "99"),
+])
+def test_side_interpreter_probe_and_bridge(side_python, side_root, monkeypatch, caplog, grace, override, expected):
+ site, receipt = side_python
+ markers = ("VIRTUAL_ENV", "PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP", "PYTHONEXECUTABLE")
+ for key in markers:
+ monkeypatch.setenv(key, "/invalid/main-environment")
+ monkeypatch.delenv("HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT", raising=False)
+ if override:
+ monkeypatch.setenv("HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT", override)
+ parent = dict(os.environ)
assert rt.check_local_runtime() == (True, None)
- assert seen["cmd"][0] == str(py)
- # The probe covers the API + manager + embedding stack (old-CPU NumPy class).
- assert "hindsight_embed.daemon_embed_manager" in seen["cmd"][2]
- assert "hindsight_api" in seen["cmd"][2]
- assert "sentence_transformers" in seen["cmd"][2]
-
-
-def test_check_local_runtime_reports_probe_failure(side_root, monkeypatch):
- _install_side_python(side_root, monkeypatch)
- monkeypatch.setattr(
- rt.subprocess, "run",
- lambda cmd, **kw: _fake_completed(returncode=1, stderr="Illegal instruction (core dumped)"),
- )
+ with caplog.at_level("INFO", logger=rt.__name__):
+ assert rt.ensure_daemon_and_url({"profile": "test-profile", "port_health_grace_timeout": grace}, restart=True) == "http://127.0.0.1:54321/test-profile"
+ child = json.loads(receipt.read_text(encoding="utf-8"))
+ assert child["config"] == {}
+ assert child["profile"] == child["stopped"] == "test-profile"
+ assert Path(child["prefix"]) == side_root
+ assert child["env"].get("HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT") == expected
+ assert child["env"]["HINDSIGHT_EMBED_API_VERSION"] == rt._API_SLIM_VERSION
+ assert not set(markers).intersection(child["env"])
+ assert dict(os.environ) == parent
+ assert not {"hindsight_embed", "hindsight_api", "sentence_transformers"}.intersection(sys.modules)
+ assert "daemon ready" in caplog.text and "starting side-env daemon manager" in caplog.text
+ (site / "sentence_transformers.py").write_text("raise RuntimeError('NumPy SIMD unavailable')", encoding="utf-8")
ok, reason = rt.check_local_runtime()
- assert ok is False
- assert "Illegal instruction" in reason
-
-
-def test_check_local_runtime_missing_env_names_the_fix(side_root):
+ assert not ok and "NumPy SIMD unavailable" in reason
+
+
[email protected]("outcome,message", [
+ (SimpleNamespace(returncode=1, stdout="", stderr="illegal instruction"), "illegal instruction"),
+ (SimpleNamespace(returncode=0, stdout='__HERMES_HINDSIGHT_BRIDGE__{"ok": false, "error": "daemon refused"}', stderr=""), "daemon refused"),
+ (SimpleNamespace(returncode=0, stdout="noise only", stderr=""), "no bridge result"),
+ (subprocess.TimeoutExpired("side-python", 5), "timed out"),
+ (OSError("cannot execute"), "could not run"),
+])
+def test_bridge_failure_is_actionable(side_root, monkeypatch, caplog, outcome, message):
+ monkeypatch.setattr(rt, "sideenv_python", lambda: side_root / "python")
+ def run(*args, **kwargs):
+ if isinstance(outcome, Exception):
+ raise outcome
+ return outcome
+ monkeypatch.setattr(rt, "subprocess", SimpleNamespace(run=run, TimeoutExpired=subprocess.TimeoutExpired))
+ with pytest.raises(RuntimeError, match=message):
+ rt.ensure_daemon_and_url({})
+ if not isinstance(outcome, OSError):
+ assert caplog.records
+
+
[email protected]("mode,available", [("cloud", False), ("local_external", False), ("local_embedded", True), ("local_embedded", False)])
+def test_provider_unavailable_reason(side_root, monkeypatch, mode, available):
+ import plugins.memory.hindsight as hs
+
+ monkeypatch.setattr(hs, "_load_config", lambda: {"mode": mode})
+ def probe():
+ assert mode == "local_embedded"
+ return available, "NumPy SIMD unavailable"
+ monkeypatch.setattr(hs, "_check_local_runtime", probe)
+ reason = hs.HindsightMemoryProvider().unavailable_reason()
+ if mode != "local_embedded" or available:
+ assert reason == ""
+ else:
+ assert reason == reason.strip()
+ assert "NumPy SIMD unavailable" in reason and "hermes memory setup" in reason
+ assert str(side_root) in reason
+ assert all(requirement in reason for requirement in rt._REQUIREMENTS)
+ assert "uv pip install --python" not in reason
+
+
+def test_missing_side_environment_never_starts_daemon(side_root):
ok, reason = rt.check_local_runtime()
- assert ok is False
- assert "hermes memory setup" in reason
- assert str(side_root) in reason
-
-
-# -- daemon bridge: URL from the side env, loopback-proven --------------------
-
-
-class _LoopbackHealth(http.server.BaseHTTPRequestHandler):
- def do_GET(self):
- self.send_response(200)
- self.end_headers()
- self.wfile.write(b"ok")
-
- def log_message(self, *args):
- pass
-
-
-def loopback_health():
- server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _LoopbackHealth)
- thread = threading.Thread(target=server.serve_forever, daemon=True)
- thread.start()
- yield f"http://127.0.0.1:{server.server_address[1]}"
- server.shutdown()
- server.server_close()
-
-
-def _install_side_python(side_root, monkeypatch):
- """A daemon/probe test needs a selected interpreter, not PM's record format."""
- from hermes_constants import venv_python_path
-
- python = venv_python_path(side_root / "selected")
- monkeypatch.setattr(rt, "sideenv_python", lambda root=None: python)
- return python
-
-
-def test_ensure_daemon_url_from_sideenv_output_is_reachable(side_root, monkeypatch, loopback_health):
- """The bridge subprocess reports the URL the side env resolved (here: a real
- loopback /health server) — the plugin never invents a port."""
- py = _install_side_python(side_root, monkeypatch)
- seen = {}
-
- def fake_run(cmd, *, env=None, **kw):
- seen["cmd"], seen["env"] = list(cmd), env
- # Manager noise on stdout; the marked JSON line is the authoritative tail.
- return _fake_completed(
- stdout=" Loading profile hermes\n"
- f"{rt._BRIDGE_MARKER}" + json.dumps({"ok": True, "url": loopback_health})
- )
-
- monkeypatch.setattr(rt.subprocess, "run", fake_run)
- url = rt.ensure_daemon_and_url({"profile": "hermes"})
- assert url == loopback_health
- # E2E: the reported daemon answers /health 200 on the real loopback.
- import urllib.request
-
- with urllib.request.urlopen(url + "/health", timeout=5) as resp:
- assert resp.status == 200
- assert seen["cmd"][0] == str(py)
- assert seen["cmd"][3] == "hermes"
-
-
-def test_ensure_daemon_env_carries_grace_and_version_pin(side_root, monkeypatch, loopback_health):
- _install_side_python(side_root, monkeypatch)
- captured = {}
-
- def fake_run(cmd, *, env=None, **kw):
- captured["env"] = env
- return _fake_completed(stdout=f"{rt._BRIDGE_MARKER}" + json.dumps({"ok": True, "url": loopback_health}))
-
- monkeypatch.setattr(rt.subprocess, "run", fake_run)
- monkeypatch.delenv("HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT", raising=False)
- monkeypatch.delenv("HINDSIGHT_EMBED_API_VERSION", raising=False)
-
- rt.ensure_daemon_and_url({"profile": "hermes", "port_health_grace_timeout": 60})
-
- # The grace window is read at IMPORT time of the side manager process, so it
- # rides the subprocess env (not Hermes' own environment).
- assert captured["env"]["HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT"] == "60.0"
- assert captured["env"]["HINDSIGHT_EMBED_API_VERSION"] == "0.9.2"
- # Main-env interpreter markers are stripped so the side python resolves only
- # its own environment.
- assert "VIRTUAL_ENV" not in captured["env"]
- assert "PYTHONPATH" not in captured["env"]
-
-
-def test_ensure_daemon_missing_runtime_raises_with_hint(side_root, monkeypatch):
+ assert not ok and "hermes memory setup" in reason and str(side_root) in reason
with pytest.raises(RuntimeError, match="hermes memory setup"):
- rt.ensure_daemon_and_url({"profile": "hermes"})
-
-
-def test_ensure_daemon_bridge_failure_surfaces(side_root, monkeypatch):
- _install_side_python(side_root, monkeypatch)
- monkeypatch.setattr(
- rt.subprocess, "run",
- lambda cmd, **kw: _fake_completed(returncode=1, stderr="boom inside side env"),
- )
- with pytest.raises(RuntimeError, match="boom inside side env"):
- rt.ensure_daemon_and_url({"profile": "hermes"})
-
-
-def test_ensure_daemon_not_ok_surfaces_bridge_error(side_root, monkeypatch):
- _install_side_python(side_root, monkeypatch)
- monkeypatch.setattr(
- rt.subprocess, "run",
- lambda cmd, **kw: _fake_completed(
- stdout=f"{rt._BRIDGE_MARKER}" + json.dumps({"ok": False, "url": None, "error": "daemon did not start"})),
- )
- with pytest.raises(RuntimeError, match="daemon did not start"):
- rt.ensure_daemon_and_url({"profile": "hermes"})
-
-
-# -- local hint ---------------------------------------------------------------
-
-
-def test_local_runtime_hint_points_at_isolated_install(side_root):
- hint = rt._local_runtime_hint("No module named 'hindsight'")
- assert "hermes memory setup" in hint
- assert "hindsight-embed==0.9.2" in hint
- assert "hindsight-api-slim[all]==0.9.2" in hint
- assert str(side_root) in hint
- # The main Hermes environment is never the target of the fix.
- assert "uv pip install --python" not in hint
-
-
-# -- trace logging on every local_embedded path -------------------------------
-
-
-def test_trace_logs_on_daemon_start_and_ready(side_root, monkeypatch, caplog, loopback_health):
- _install_side_python(side_root, monkeypatch)
- monkeypatch.setattr(
- rt.subprocess, "run",
- lambda cmd, **kw: _fake_completed(stdout=f"{rt._BRIDGE_MARKER}" + json.dumps({"ok": True, "url": loopback_health})),
- )
- with caplog.at_level("INFO", logger="plugins.memory.hindsight.embedded_runtime"):
- rt.ensure_daemon_and_url({"profile": "hermes"})
- messages = [r.getMessage() for r in caplog.records]
- assert any("starting side-env daemon manager" in m for m in messages)
- assert any("daemon ready" in m for m in messages)
-
-
-def test_trace_logs_on_startup_failure(side_root, monkeypatch, caplog):
- _install_side_python(side_root, monkeypatch)
- monkeypatch.setattr(
- rt.subprocess, "run",
- lambda cmd, **kw: _fake_completed(returncode=1, stderr="no dice"),
- )
- with caplog.at_level("WARNING", logger="plugins.memory.hindsight.embedded_runtime"):
- with pytest.raises(RuntimeError):
- rt.ensure_daemon_and_url({"profile": "hermes"})
- assert any("bridge failed" in r.getMessage() for r in caplog.records)
-
-
-def test_no_in_process_import_of_the_embedded_stack():
- # The isolation contract: importing the plugin must not pull the heavy
- # embedded stack into the boot env (it lives only in the side env).
- import sys
-
- import plugins.memory.hindsight # noqa: F401
-
- assert "hindsight_embed" not in sys.modules
- assert "hindsight_api" not in sys.modules
- assert "hindsight" not in sys.modules
+ rt.ensure_daemon_and_url({})
diff --git a/tests/plugins/memory/test_hindsight_local_runtime_hint.py b/tests/plugins/memory/test_hindsight_local_runtime_hint.py
deleted file mode 100644
index 7742a4c8672..00000000000
--- a/tests/plugins/memory/test_hindsight_local_runtime_hint.py
+++ /dev/null
@@ -1,47 +0,0 @@
-"""The install hint for an unavailable local_embedded side runtime.
-
-The embedded stack lives in the isolated side env (embedded_runtime); the fix
-is always 'hermes memory setup' (Local Embedded) — the main Hermes environment
-is never a pip target for it.
-"""
-
-import plugins.memory.hindsight as hs
-from plugins.memory.hindsight import HindsightMemoryProvider, _local_runtime_hint
-
-
-def test_hint_for_missing_runtime_names_the_isolated_install():
- hint = _local_runtime_hint("No module named 'hindsight'")
- assert "hermes memory setup" in hint
- assert "hindsight-embed==0.9.2" in hint
- assert "hindsight-api-slim[all]==0.9.2" in hint
-
-
-def test_hint_includes_probe_reason():
- hint = _local_runtime_hint("Illegal instruction (NumPy SIMD)")
- assert "NumPy SIMD" in hint # truthful: reinstall may not fix a CPU limit
- assert "hermes memory setup" in hint
-
-
-def test_hint_without_reason_still_actionable():
- assert "hermes memory setup" in _local_runtime_hint(None)
-
-
-def test_unavailable_reason_surfaces_hint_for_local_embedded(monkeypatch):
- monkeypatch.setattr(hs, "_load_config", lambda: {"mode": "local_embedded"})
- monkeypatch.setattr(hs, "_check_local_runtime", lambda: (False, "No module named 'hindsight'"))
- reason = HindsightMemoryProvider().unavailable_reason()
- assert "hermes memory setup" in reason
- assert reason == reason.strip() # no leading/trailing whitespace
-
-
-def test_unavailable_reason_empty_for_cloud(monkeypatch):
- monkeypatch.setattr(hs, "_load_config", lambda: {"mode": "cloud"})
- # Should not even probe the runtime for a cloud provider.
- monkeypatch.setattr(hs, "_check_local_runtime", lambda: (_ for _ in ()).throw(AssertionError("probed")))
- assert HindsightMemoryProvider().unavailable_reason() == ""
-
-
-def test_unavailable_reason_empty_when_runtime_present(monkeypatch):
- monkeypatch.setattr(hs, "_load_config", lambda: {"mode": "local_embedded"})
- monkeypatch.setattr(hs, "_check_local_runtime", lambda: (True, None))
- assert HindsightMemoryProvider().unavailable_reason() == ""
diff --git a/tests/plugins/memory/test_hindsight_provider.py b/tests/plugins/memory/test_hindsight_provider.py
index b0b16a6742e..1f4052bc102 100644
--- a/tests/plugins/memory/test_hindsight_provider.py
+++ b/tests/plugins/memory/test_hindsight_provider.py
@@ -1521,31 +1521,19 @@ class TestSharedEventLoopLifecycle:
provider_b.shutdown()
- def test_client_aclose_called_on_cloud_mode_shutdown(self, provider):
+ @pytest.mark.parametrize("mode", ["cloud", "local_embedded"])
+ def test_client_aclose_called_on_shutdown(self, provider, mode):
"""Per-provider session cleanup still runs even though the shared
loop is preserved. Each provider's own aiohttp session is closed
via ``self._client.aclose()``; only the (empty) shared loop survives.
"""
assert provider._client is not None
mock_client = provider._client
+ provider._mode = mode
provider.shutdown()
- mock_client.aclose.assert_called_once()
- assert provider._client is None
-
-
-class TestShutdown:
- def test_local_embedded_shutdown_closes_client_on_shared_loop(self, provider):
- """The embedded client is hindsight_client.Hindsight (HTTP to the side-env
- daemon): same aclose-on-shared-loop path as cloud."""
- client = _make_mock_client()
- provider._mode = "local_embedded"
- provider._client = client
-
- provider.shutdown()
-
- client.aclose.assert_awaited_once()
+ mock_client.aclose.assert_awaited_once()
assert provider._client is None
diff --git a/tests/plugins/memory/test_hindsight_setup_deps.py b/tests/plugins/memory/test_hindsight_setup_deps.py
index 1490d43bb07..83b9082b09c 100644
--- a/tests/plugins/memory/test_hindsight_setup_deps.py
+++ b/tests/plugins/memory/test_hindsight_setup_deps.py
@@ -4,7 +4,6 @@ local_embedded wizard must ACTUALLY install the isolated side-env runtime via
embedded_runtime.ensure_sideenv (hindsight-embed + hindsight-api-slim[all],
pinned, built by PM's isolated-environment operation). Never the deleted ``tools.lazy_deps``."""
-import sys
from types import SimpleNamespace
from unittest.mock import MagicMock
@@ -36,26 +35,26 @@ def _no_network_setup(monkeypatch, setup_mod, tmp_path, mode):
return _fake_provider(), str(tmp_path / "home"), {"memory": {}}
-class TestClientModeUsesDeclaredExtra:
- def test_cloud_mode_syncs_hindsight_extra(self, monkeypatch, setup_mod, tmp_path):
- calls = []
- import pm
- monkeypatch.setattr(pm, "sync_venv", lambda extras=None, *, explicit=False: calls.append((extras, explicit)))
- provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "cloud")
-
- setup_mod.run_setup(provider, home, config)
-
- assert calls == [(["hindsight"], True)]
-
- def test_local_external_mode_syncs_hindsight_extra(self, monkeypatch, setup_mod, tmp_path):
- calls = []
- import pm
- monkeypatch.setattr(pm, "sync_venv", lambda extras=None, *, explicit=False: calls.append((extras, explicit)))
- provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "local_external")
-
- setup_mod.run_setup(provider, home, config)
-
- assert calls == [(["hindsight"], True)]
[email protected]("mode", ["cloud", "local_external", "local_embedded"])
+def test_setup_installs_selected_mode_and_saves(monkeypatch, setup_mod, tmp_path, capsys, mode):
+ import pm
+ import plugins.memory.hindsight.embedded_runtime as rt
+
+ sync = MagicMock()
+ side = MagicMock(return_value=rt.sideenv_root())
+ monkeypatch.setattr(pm, "sync_venv", sync)
+ monkeypatch.setattr(rt, "ensure_sideenv", side)
+ provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, mode)
+ setup_mod.run_setup(provider, home, config)
+ sync.assert_called_once_with(["hindsight"], explicit=True)
+ assert side.call_count == (1 if mode == "local_embedded" else 0)
+ assert config["memory"]["provider"] == "hindsight"
+ saved = provider.save_config.call_args.args[0]
+ assert saved["mode"] == mode
+ assert saved["bank_id"] == "hermes"
+ if mode == "local_embedded":
+ out = capsys.readouterr().out
+ assert "Isolated Hindsight runtime installed" in out and "not modified" in out
class TestSyncFailureSurfaces:
@@ -76,25 +75,6 @@ class TestSyncFailureSurfaces:
class TestEmbeddedInstallsIsolatedSideEnv:
- def test_embedded_installs_isolated_runtime_not_shared_venv(self, monkeypatch, setup_mod, tmp_path, capsys):
- calls = []
- import pm
- monkeypatch.setattr(pm, "sync_venv", lambda extras=None, *, explicit=False: calls.append(extras))
- installed = []
- import plugins.memory.hindsight.embedded_runtime as rt
- monkeypatch.setattr(rt, "ensure_sideenv", lambda: installed.append("gen") or rt.sideenv_root())
- provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "local_embedded")
-
- setup_mod.run_setup(provider, home, config)
-
- out = capsys.readouterr().out
- # The client extra goes through pm; the heavy stack installs into the
- # isolated side env — never the shared venv.
- assert calls == [["hindsight"]]
- assert installed == ["gen"]
- assert "Isolated Hindsight runtime installed" in out
- assert "not modified" in out
-
def test_embedded_install_failure_is_truthful_and_non_fatal(self, monkeypatch, setup_mod, tmp_path, capsys):
import pm
monkeypatch.setattr(pm, "sync_venv", lambda extras=None, *, explicit=False: None)
@@ -110,27 +90,3 @@ class TestEmbeddedInstallsIsolatedSideEnv:
assert "disk full" in out
provider.save_config.assert_not_called()
assert config["memory"] == {}
-
- def test_embedded_config_still_saved(self, monkeypatch, setup_mod, tmp_path):
- import pm
- monkeypatch.setattr(pm, "sync_venv", lambda extras=None, *, explicit=False: None)
- import plugins.memory.hindsight.embedded_runtime as rt
- monkeypatch.setattr(rt, "ensure_sideenv", lambda: rt.sideenv_root())
- provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "local_embedded")
-
- setup_mod.run_setup(provider, home, config)
-
- saved = provider.save_config.call_args[0][0]
- assert saved["mode"] == "local_embedded"
- assert saved["bank_id"] == "hermes"
-
-
-class TestNoLazyDeps:
- def test_tools_lazy_deps_absent_after_setup(self, monkeypatch, setup_mod, tmp_path):
- import pm
- monkeypatch.setattr(pm, "sync_venv", lambda extras=None, *, explicit=False: None)
- provider, home, config = _no_network_setup(monkeypatch, setup_mod, tmp_path, "cloud")
-
- setup_mod.run_setup(provider, home, config)
-
- assert "tools.lazy_deps" not in sys.modules
diff --git a/tests/plugins/memory/test_memory_lazy_install.py b/tests/plugins/memory/test_memory_lazy_install.py
index bc967450e06..84514079442 100644
--- a/tests/plugins/memory/test_memory_lazy_install.py
+++ b/tests/plugins/memory/test_memory_lazy_install.py
@@ -1,125 +1,55 @@
-"""Regression tests: supermemory + mem0 memory providers must lazy-install
-their SDKs like honcho/hindsight.
-
-Both providers ship a third-party SDK (``supermemory`` / ``mem0ai``) that is
-NOT a core dependency. Before this fix they imported the SDK directly with no
-``pm.ensure_import()`` preflight and had no extras mapping, so on hosted
-instances the SDK was never installed and the provider silently reported
-itself unavailable.
-
-These tests pin the contract:
-
-1. Both features are pyproject extras with an anchor in ``pm.extras.ANCHORS``
- (without a mapping, ``ensure_import()`` can't resolve the anchor import
- that proves the extra is installed — the original silent-dark bug).
-2. Each provider's SDK-import chokepoint actually calls
- ``ensure_import(<extra>)``.
-3. supermemory's ``is_available()`` no longer gates on the SDK being
- importable (the chicken-and-egg trap that stopped the provider loading at
- all on a sealed venv, so ``initialize()``/``ensure_import()`` never ran).
-"""
-
-from __future__ import annotations
+"""Memory callers cross real PM admission before importing their optional SDK."""
+import importlib.machinery
+import importlib.abc
+import sys
+from types import ModuleType
import pytest
-import pm
-from pm.extras import ANCHORS
-
-
-MEMORY_EXTRAS = {"supermemory": "supermemory", "mem0": "mem0"}
-
-
-# ---------------------------------------------------------------------------
-# 1. Extras contract — the core regression.
-# ---------------------------------------------------------------------------
-
-
-class TestExtrasAnchors:
- @pytest.mark.parametrize("extra,anchor", sorted(MEMORY_EXTRAS.items()))
- def test_extra_has_anchor(self, extra, anchor):
- # Without an anchor mapping, pm can't tell whether the extra is
- # installed, and ensure_import() can't prove a successful install.
- assert ANCHORS.get(extra) == anchor, (
- f"{extra!r} missing/wrong in pm.extras.ANCHORS — its SDK can "
- f"never lazy-install on a hosted instance."
- )
-
-
-# ---------------------------------------------------------------------------
-# 2. Import sites call ensure_import().
-# ---------------------------------------------------------------------------
-
-
-class TestSupermemoryEnsureCalled:
- def test_client_construction_calls_ensure(self, monkeypatch):
- """_SupermemoryClient.__init__ must call ensure_import('supermemory')
- before importing the SDK."""
- from plugins.memory.supermemory import _SupermemoryClient
-
- calls = []
- monkeypatch.setattr(
- pm, "ensure_import",
- lambda extra: calls.append(extra),
- )
-
- # Stub the SDK so construction doesn't need the real package. The
- # client does ``from supermemory import Supermemory`` right after
- # ensure_import(); inject a fake module.
- import sys
- import types
-
- fake = types.ModuleType("supermemory")
- fake.Supermemory = lambda **kw: object()
- monkeypatch.setitem(sys.modules, "supermemory", fake)
-
- _SupermemoryClient(api_key="k", timeout=5.0, container_tag="hermes")
-
- assert "supermemory" in calls, (
- "supermemory client did not call ensure_import('supermemory'); "
- f"calls={calls}"
- )
-
-
-class TestMem0EnsureCalled:
- def test_create_backend_calls_ensure(self, monkeypatch):
- """The mem0 provider must call ensure_import('mem0') in
- _create_backend before importing the SDK."""
- from plugins.memory.mem0 import Mem0MemoryProvider
-
- calls = []
- monkeypatch.setattr(
- pm, "ensure_import",
- lambda extra: calls.append(extra),
- )
-
- prov = Mem0MemoryProvider()
- # Platform mode is the default; force a known mode and stub the backend
- # import so we isolate the ensure_import() call.
- prov._mode = "platform"
- prov._api_key = "k"
-
- import sys
- import types
-
- fake = types.ModuleType("mem0")
- fake.MemoryClient = lambda **kw: object()
- fake.Memory = object
- monkeypatch.setitem(sys.modules, "mem0", fake)
- # _backend imports ``from mem0 import MemoryClient`` lazily inside
- # PlatformBackend.__init__, so the fake module satisfies it.
-
- prov._create_backend()
-
- assert "mem0" in calls, (
- f"mem0 _create_backend did not call ensure_import('mem0'); "
- f"calls={calls}"
- )
-
-# ---------------------------------------------------------------------------
-# 3. supermemory is_available() chicken-and-egg fix.
-# ---------------------------------------------------------------------------
[email protected]("extra", ["supermemory", "mem0"])
[email protected]("state", ["present", "absent", "failed"])
+def test_provider_sdk_admission(monkeypatch, tmp_path, extra, state):
+ import pm.client
+ from pm import paths
+ from plugins.memory.supermemory import _SupermemoryClient
+ from plugins.memory.mem0 import Mem0MemoryProvider
+
+ sdk = ModuleType(extra)
+ sdk.__spec__ = importlib.machinery.ModuleSpec(extra, loader=None)
+ sdk.Supermemory = sdk.MemoryClient = lambda **kwargs: object()
+ sdk.Memory = object
+ monkeypatch.delitem(sys.modules, extra, raising=False)
+ if state == "present":
+ monkeypatch.setitem(sys.modules, extra, sdk)
+ class MissingSDK(importlib.abc.MetaPathFinder):
+ def find_spec(self, fullname, path=None, target=None):
+ if fullname == extra:
+ raise ModuleNotFoundError("SDK unavailable")
+ monkeypatch.setattr(sys, "meta_path", [MissingSDK(), *sys.meta_path])
+ monkeypatch.setattr(paths, "runtime_facts_path", lambda: tmp_path / "unselected-facts")
+ calls = []
+ def sync(extras):
+ calls.append(extras)
+ if state == "failed":
+ raise RuntimeError("SDK install refused")
+ monkeypatch.setitem(sys.modules, extra, sdk)
+ monkeypatch.setattr(pm.client, "sync_venv", sync)
+ def construct():
+ if extra == "supermemory":
+ return _SupermemoryClient(api_key="k", timeout=5, container_tag="hermes")
+ provider = Mem0MemoryProvider()
+ provider._mode, provider._api_key = "platform", "k"
+ return provider._create_backend()
+ if state == "failed":
+ if extra == "mem0":
+ assert construct() is None
+ else:
+ with pytest.raises(ModuleNotFoundError, match="SDK unavailable"):
+ construct()
+ else:
+ assert construct() is not None
+ assert calls == ([] if state == "present" else [[extra]])
class TestSupermemoryIsAvailable:
diff --git a/tests/plugins/platforms/photon/test_presence_watchdog.py b/tests/plugins/platforms/photon/test_presence_watchdog.py
index 24ab5b597e4..5b204edc344 100644
--- a/tests/plugins/platforms/photon/test_presence_watchdog.py
+++ b/tests/plugins/platforms/photon/test_presence_watchdog.py
@@ -13,7 +13,10 @@ spawning Node, binding ports, or hitting the network.
from __future__ import annotations
import time
-from typing import Any, List
+from typing import Any
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
import pytest
@@ -67,60 +70,38 @@ def test_note_activity_resets_failures(monkeypatch: pytest.MonkeyPatch) -> None:
@pytest.mark.asyncio
-async def test_respawn_after_max_failures(monkeypatch: pytest.MonkeyPatch) -> None:
- """The core fix: N consecutive dead probes -> exactly one respawn."""
- a = _make_adapter(monkeypatch, probe_max_failures=3)
-
- respawns: List[str] = []
-
- async def _fake_respawn(reason: str) -> None:
- respawns.append(reason)
- a._note_upstream_activity() # mirror real respawn (clears failures)
-
- async def _hung_probe() -> str:
- return "hung"
-
- monkeypatch.setattr(a, "_respawn_sidecar", _fake_respawn)
- monkeypatch.setattr(a, "_probe_once", _hung_probe)
-
- # Simulate the watchdog's per-iteration decision logic directly (no sleeps).
- a._last_upstream_activity = time.monotonic() - 999 # force a probe each time
- for _ in range(3):
- verdict = await a._probe_once()
- assert verdict == "hung"
- a._probe_failures += 1
- if a._probe_failures >= a._probe_max_failures:
- await a._respawn_sidecar("test")
-
- assert respawns == ["test"]
- assert a._probe_failures == 0 # reset by the (faked) respawn
-
-
-async def test_success_resets_failure_count(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """A live probe between dead ones prevents a respawn (failures reset)."""
- a = _make_adapter(monkeypatch, probe_max_failures=3)
-
- respawns: List[str] = []
-
- async def _fake_respawn(reason: str) -> None:
- respawns.append(reason)
-
- monkeypatch.setattr(a, "_respawn_sidecar", _fake_respawn)
-
- # Two failures, then a success, then two more failures: never hits 3 in a row.
- sequence = [False, False, True, False, False]
- for alive in sequence:
- if alive:
- a._note_upstream_activity()
- else:
- a._probe_failures += 1
- if a._probe_failures >= a._probe_max_failures:
- await a._respawn_sidecar("should-not-fire")
-
- assert respawns == []
- assert a._probe_failures == 2
-
-
[email protected]("sequence,respawns,failures", [
+ (["hung", "hung", "hung"], 1, 3),
+ (["hung", "hung", "alive", "hung", "hung"], 0, 2),
+ (["hung", "inconclusive", "hung"], 0, 2),
+ (["recent", "hung"], 0, 1),
+])
+async def test_watchdog_decisions(monkeypatch, sequence, respawns, failures):
+ import plugins.platforms.photon.adapter as module
+
+ adapter = _make_adapter(monkeypatch, probe_max_failures=3)
+ adapter._watchdog_running = True
+ steps = iter(sequence)
+ verdicts = iter([step for step in sequence if step != "recent"])
+ probe = AsyncMock(side_effect=lambda: next(verdicts))
+ respawn = AsyncMock()
+
+ async def tick(_delay):
+ step = next(steps, None)
+ if step is None:
+ raise asyncio.CancelledError
+ adapter._last_upstream_activity = time.monotonic() - (0 if step == "recent" else 999)
+
+ monkeypatch.setattr(module, "asyncio", SimpleNamespace(sleep=tick, CancelledError=asyncio.CancelledError))
+ monkeypatch.setattr(adapter, "_probe_once", probe)
+ monkeypatch.setattr(adapter, "_respawn_sidecar", respawn)
+ task = asyncio.create_task(adapter._presence_watchdog())
+ try:
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert respawn.await_count == respawns
+ assert probe.await_count == len(sequence) - sequence.count("recent")
+ assert adapter._probe_failures == failures
+ finally:
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
diff --git a/tests/plugins/test_hindsight_health_grace_timeout.py b/tests/plugins/test_hindsight_health_grace_timeout.py
deleted file mode 100644
index 108ec6480ef..00000000000
--- a/tests/plugins/test_hindsight_health_grace_timeout.py
+++ /dev/null
@@ -1,50 +0,0 @@
-"""Embedded-daemon health grace timeout (issue #13125 comment thread).
-
-On resource-contended hosts the embedded Hindsight daemon can exceed a single
-2s /health check and get needlessly killed + restarted. Upstream exposes the
-grace window via HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT, read at import
-time of the process that runs DaemonEmbedManager — which is now the SIDE-env
-daemon bridge process, so the value must ride the subprocess environment
-built by embedded_runtime (never Hermes' own os.environ).
-"""
-
-import plugins.memory.hindsight.embedded_runtime as rt
-
-_ENV = rt._PORT_HEALTH_GRACE_ENV
-
-
-def test_configured_value_rides_subprocess_env():
- env = rt._daemon_subprocess_env({"port_health_grace_timeout": 60})
- assert float(env[_ENV]) == 60.0
-
-
-def test_string_value_parsed():
- env = rt._daemon_subprocess_env({"port_health_grace_timeout": "45"})
- assert float(env[_ENV]) == 45.0
-
-
-def test_blank_and_missing_are_noops():
- env = rt._daemon_subprocess_env({})
- assert _ENV not in env
- assert _ENV not in rt._daemon_subprocess_env({"port_health_grace_timeout": ""})
- assert _ENV not in rt._daemon_subprocess_env({"port_health_grace_timeout": None})
-
-
-def test_invalid_and_negative_ignored():
- assert _ENV not in rt._daemon_subprocess_env({"port_health_grace_timeout": "not-a-number"})
- assert _ENV not in rt._daemon_subprocess_env({"port_health_grace_timeout": -5})
-
-
-def test_explicit_env_wins_over_config(monkeypatch):
- monkeypatch.setenv(_ENV, "99")
- env = rt._daemon_subprocess_env({"port_health_grace_timeout": 60})
- # setdefault must not clobber an operator-set env override.
- assert env[_ENV] == "99"
-
-
-def test_main_env_interpreter_markers_stripped(monkeypatch):
- monkeypatch.setenv("VIRTUAL_ENV", "/some/main-venv")
- monkeypatch.setenv("PYTHONPATH", "/some/shim")
- env = rt._daemon_subprocess_env({})
- assert "VIRTUAL_ENV" not in env
- assert "PYTHONPATH" not in env
diff --git a/tests/run_agent/test_create_openai_client_ssl_verify.py b/tests/run_agent/test_create_openai_client_ssl_verify.py
deleted file mode 100644
index 359892acd50..00000000000
--- a/tests/run_agent/test_create_openai_client_ssl_verify.py
+++ /dev/null
@@ -1,62 +0,0 @@
-"""Regression: the keepalive httpx client must carry the resolved TLS trust.
-
-Trust is the OS certificate store; a per-provider ``ssl_ca_cert`` replaces it
-for that one client. Both shapes have to survive the trip into httpx's
-transport, which is what these assert.
-"""
-
-import ssl
-
-import certifi
-import httpx
-import pytest
-
-from agent.ssl_verify import resolve_httpx_verify
-from run_agent import AIAgent
-
-_CA_ENV_VARS = ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "HTTPS_PROXY")
-
-
-def clean_tls_env(monkeypatch):
- for var in _CA_ENV_VARS:
- monkeypatch.delenv(var, raising=False)
-
-
-def test_build_keepalive_http_client_uses_the_platform_trust_store(clean_tls_env):
- verify = resolve_httpx_verify()
- assert verify is True
-
- client = AIAgent._build_keepalive_http_client(
- "https://ollama.example.com/v1", verify=verify,
- )
- assert isinstance(client, httpx.Client)
- # httpx builds its own context from the patched ssl.SSLContext, so the
- # pool's context IS the platform-verified one.
- ctx = client._transport._pool._ssl_context
- assert type(ctx).__module__.startswith("truststore")
-
-
-def test_build_keepalive_http_client_honors_per_provider_ssl_ca_cert(clean_tls_env):
- from truststore._ssl_constants import _original_SSLContext
-
- verify = resolve_httpx_verify(ca_bundle=certifi.where())
- client = AIAgent._build_keepalive_http_client(
- "https://ollama.example.com/v1", verify=verify,
- )
- assert isinstance(client, httpx.Client)
- # The pinned bundle must reach the transport UNPATCHED — a truststore
- # context here would mean the pin silently became "trust the machine".
- ctx = client._transport._pool._ssl_context
- assert isinstance(ctx, _original_SSLContext)
- assert not type(ctx).__module__.startswith("truststore")
-
-
-def test_build_keepalive_http_client_ssl_verify_false(clean_tls_env):
- verify = resolve_httpx_verify(ssl_verify=False)
- client = AIAgent._build_keepalive_http_client(
- "https://ollama.example.com/v1", verify=verify,
- )
- assert isinstance(client, httpx.Client)
- assert client._transport._pool._ssl_context.check_hostname is False
- assert client._transport._pool._ssl_context.verify_mode == ssl.CERT_NONE
diff --git a/tests/state/test_state_db_holders.py b/tests/state/test_state_db_holders.py
index d48231d726d..df85beb901f 100644
--- a/tests/state/test_state_db_holders.py
+++ b/tests/state/test_state_db_holders.py
@@ -1,6 +1,7 @@
"""Behavioral tests for the state-holder and repair-admission authority."""
import os
+from types import SimpleNamespace
import pytest
@@ -8,20 +9,25 @@ import hermes_state_holders
@pytest.mark.platforms("linux")
-def test_foreign_holder_accepts_same_inode_reached_through_an_alias(
- tmp_path, monkeypatch
[email protected]("identity", ["alias", "different-inode", "different-device"])
+def test_foreign_holder_uses_device_and_inode_not_path(
+ tmp_path, monkeypatch, identity
):
"""Descriptor identity is authoritative even when /proc spells another path."""
db_path = tmp_path / "state.db"
db_path.touch()
- alias_path = tmp_path / "namespace-alias" / "state.db"
+ alias_path = tmp_path / "namespace-alias" / "state.db" if identity == "alias" else db_path
proc_root = tmp_path / "proc"
for pid in (111, 222):
(proc_root / str(pid) / "fd").mkdir(parents=True)
os.symlink(db_path, proc_root / "222" / "fd" / "3")
- monkeypatch.setattr(hermes_state_holders.os, "getpid", lambda: 111)
+ # Keep the /proc projection local: patching os globally also intercepts
+ # pytest's home guard and pathlib while they inspect these same symlinks.
+ projected_os = SimpleNamespace(**vars(os))
+ projected_os.getpid = lambda: 111
+ monkeypatch.setattr(hermes_state_holders, "os", projected_os)
real_listdir = os.listdir
def _listdir(path):
@@ -40,11 +46,16 @@ def test_foreign_holder_accepts_same_inode_reached_through_an_alias(
real_stat = os.stat
def _stat(path, *args, **kwargs):
- path = str(path).replace("/proc", str(proc_root))
- return real_stat(path, *args, **kwargs)
+ mapped = str(path).replace("/proc", str(proc_root))
+ result = real_stat(mapped, *args, **kwargs)
+ if str(path) == "/proc/222/fd/3" and identity != "alias":
+ values = list(result)
+ values[1 if identity == "different-inode" else 2] += 1
+ return os.stat_result(values)
+ return result
monkeypatch.setattr(hermes_state_holders.os, "stat", _stat)
- assert hermes_state_holders.foreign_state_db_holders(db_path) == [
- (222, str(alias_path))
- ]
+ assert hermes_state_holders.foreign_state_db_holders(db_path) == (
+ [(222, str(alias_path))] if identity == "alias" else []
+ )
diff --git a/tests/tui_gateway/test_bot_relay_methods.py b/tests/tui_gateway/test_bot_relay_methods.py
index f39f2da2720..08e66dc4b9f 100644
--- a/tests/tui_gateway/test_bot_relay_methods.py
+++ b/tests/tui_gateway/test_bot_relay_methods.py
@@ -163,7 +163,7 @@ def test_reply_roundtrip_and_id_validation(home):
assert "error" in err
def test_deliver_write_failure_still_removes_tempfile(home, monkeypatch, tmp_path):
"""A failed payload write must not leak the relay DM tempfile."""
import glob
@@ -180,17 +180,21 @@ def test_deliver_write_failure_still_removes_tempfile(home, monkeypatch, tmp_pat
return fd, path
class _BrokenWriter:
+ def __init__(self, fd):
+ self.fd = fd
+
def __enter__(self):
return self
def __exit__(self, *exc_info):
+ os.close(self.fd)
return False
def write(self, content):
raise OSError("disk full")
monkeypatch.setattr("tempfile.mkstemp", _tracking_mkstemp)
- monkeypatch.setattr("os.fdopen", lambda *a, **k: _BrokenWriter())
+ monkeypatch.setattr("os.fdopen", lambda fd, *a, **k: _BrokenWriter(fd))
err = srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "x"})
assert "error" in err
assert made, "mkstemp was never reached"