Skip to content

The agent that grows with you

fix(tests): make the test suite pass on Windows without regressing Linux

ethernetbd258480d3cf
diff --git a/acp_adapter/server.py b/acp_adapter/server.py
index 792e44b70d4..408355a118b 100644
--- a/acp_adapter/server.py
+++ b/acp_adapter/server.py
@@ -325,8 +325,15 @@ def _path_from_file_uri(uri: str) -> Path | None:
if len(path_text) >= 3 and path_text[0] == "/" and path_text[2] == ":" and path_text[1].isalpha():
drive = path_text[1].lower()
rest = path_text[3:].lstrip("/\\").replace("\\", "/")
+ if os.name == "nt":
+ # Native Windows: /C:/Users/... is already an absolute path once the
+ # leading slash is dropped. The /mnt/<drive> form only makes sense
+ # for Hermes running in WSL.
+ return Path(path_text[1:])
return Path("/mnt") / drive / rest
if len(path_text) >= 2 and path_text[1] == ":" and path_text[0].isalpha():
+ if os.name == "nt":
+ return Path(path_text)
drive = path_text[0].lower()
rest = path_text[2:].lstrip("/\\").replace("\\", "/")
return Path("/mnt") / drive / rest
diff --git a/agent/browser_registry.py b/agent/browser_registry.py
index 4348237af1d..068c79aa92c 100644
--- a/agent/browser_registry.py
+++ b/agent/browser_registry.py
@@ -69,6 +69,7 @@ def register_provider(provider: BrowserProvider, *, scope: Optional[str] = None)
if not isinstance(raw_name, str) or not raw_name.strip():
raise ValueError("Browser provider .name must be a non-empty string")
name = raw_name.strip()
+ scope = hermes_home_key(scope) if scope is not None else None
global _generation
with _lock:
target = _providers if scope is None else _scoped_providers.setdefault(scope, {})
@@ -92,6 +93,7 @@ def register_provider(provider: BrowserProvider, *, scope: Optional[str] = None)
def list_providers(*, scope: Optional[str] = None) -> List[BrowserProvider]:
"""Return all registered providers, sorted by name."""
+ scope = hermes_home_key(scope) if scope is not None else None
with _lock:
merged = dict(_providers)
merged.update(_scoped_providers.get(scope or hermes_home_key(), {}))
@@ -103,6 +105,7 @@ def get_provider(name: str, *, scope: Optional[str] = None) -> Optional[BrowserP
"""Return the provider registered under *name*, or None."""
if not isinstance(name, str):
return None
+ scope = hermes_home_key(scope) if scope is not None else None
with _lock:
key = name.strip()
return _scoped_providers.get(scope or hermes_home_key(), {}).get(key) or _providers.get(key)
@@ -111,6 +114,7 @@ def get_provider(name: str, *, scope: Optional[str] = None) -> Optional[BrowserP
def snapshot_registration(
name: str, *, scope: Optional[str] = None
) -> Optional[BrowserProvider]:
+ scope = hermes_home_key(scope) if scope is not None else None
with _lock:
target = _providers if scope is None else _scoped_providers.get(scope, {})
return target.get(name.strip())
@@ -118,7 +122,7 @@ def snapshot_registration(
def registry_generation(*, scope: Optional[str] = None) -> tuple[int, int]:
"""Return a cache fingerprint for the global base and one profile."""
- active_scope = scope or hermes_home_key()
+ active_scope = hermes_home_key(scope) if scope is not None else hermes_home_key()
with _lock:
return _generation, _scoped_generations.get(active_scope, 0)
@@ -132,6 +136,7 @@ def restore_registration(
) -> bool:
"""Restore a plugin registration only when *current* is still installed."""
key = name.strip()
+ scope = hermes_home_key(scope) if scope is not None else None
global _generation
with _lock:
target = _providers if scope is None else _scoped_providers.setdefault(scope, {})
diff --git a/agent/deadline.py b/agent/deadline.py
index e3357f8a240..6c8cbe4efd2 100644
--- a/agent/deadline.py
+++ b/agent/deadline.py
@@ -90,12 +90,19 @@ __all__ = [
# Upper bound for any timeout handed to platform wait primitives.
#
# CPython converts ``threading.Lock.acquire(timeout=...)`` /
-# ``Thread.join(timeout=...)`` deadlines to an absolute timestamp; very large
-# relative timeouts overflow ``time_t`` on macOS and raise
-# ``OverflowError: timestamp out of range for platform time_t`` (#83220).
-# One year is semantically "unbounded" for every wait in this codebase while
-# staying far below any platform conversion limit.
-MAX_SAFE_TIMEOUT_S = 31_536_000.0 # 365 days
+# ``Thread.join(timeout=...)`` deadlines through the platform wait primitive;
+# a value too large for that primitive's conversion limit raises
+# ``OverflowError``. The ceilings differ per host:
+#
+# * POSIX — ``time_t`` on macOS (32-bit in #83220) overflows on absurd
+# relative timeouts. One year is semantically "unbounded" for every wait
+# in this codebase while staying far below ``time_t``.
+# * Windows — ``WaitForSingleObject`` takes a DWORD of milliseconds
+# (2**32 - 1 ms ≈ 49.7 days), so 365 days would overflow it.
+if sys.platform == "win32":
+ MAX_SAFE_TIMEOUT_S = 4_294_967.0 # just under DWORD-millisecond ceiling
+else:
+ MAX_SAFE_TIMEOUT_S = 31_536_000.0 # 365 days
# Grace period after a deadline fires before concluding the event loop thread
# is blocked in a synchronous call and dumping stacks (family A diagnostics).
diff --git a/agent/image_routing.py b/agent/image_routing.py
index 3412efe585d..ec01b433c1b 100644
--- a/agent/image_routing.py
+++ b/agent/image_routing.py
@@ -64,10 +64,13 @@ _IMAGE_EXTS = (
_IMAGE_EXT_PATTERN = "|".join(e.lstrip(".") for e in _IMAGE_EXTS)
# Absolute / home-relative local image path. Matches the same shape gateway's
-# extract_local_files() uses: anchors to ``~/`` or ``/``, ignores matches inside
-# URLs (the ``(?<![/:\w.])`` lookbehind), and case-insensitive on the extension.
+# extract_local_files() uses: anchors to ``~/``, ``/``, or a Windows drive
+# (``C:\``), ignores matches inside URLs (the ``(?<![/:\w.])`` lookbehind), and
+# case-insensitive on the extension.
_LOCAL_IMAGE_PATH_RE = re.compile(
- r"(?<![/:\w.])(?:~/|/)(?:[\w.\-]+/)*[\w.\-]+\.(?:" + _IMAGE_EXT_PATTERN + r")\b",
+ r"(?<![/:\w.])(?:~/|/|[A-Za-z]:[\\/])(?:[\w.\-]+[\\/])*[\w.\-]+\.(?:"
+ + _IMAGE_EXT_PATTERN
+ + r")\b",
re.IGNORECASE,
)
@@ -120,7 +123,7 @@ def extract_image_refs(text: str) -> Tuple[List[str], List[str]]:
if _in_code(match.start()):
continue
raw = match.group(0)
- expanded = os.path.expanduser(raw)
+ expanded = os.path.normpath(os.path.expanduser(raw))
try:
if not os.path.isfile(expanded):
continue
diff --git a/agent/secret_sources/registry.py b/agent/secret_sources/registry.py
index bbc52089e84..745320af230 100644
--- a/agent/secret_sources/registry.py
+++ b/agent/secret_sources/registry.py
@@ -138,6 +138,7 @@ def register_source(
name, getattr(source, "shape", None),
)
return False
+ scope = hermes_home_key(scope) if scope is not None else None
with _REGISTRY_LOCK:
effective = dict(_SOURCES)
if scope is not None:
@@ -168,6 +169,7 @@ def register_source(
def get_source(name: str, *, scope: Optional[str] = None) -> Optional[SecretSource]:
_ensure_builtin_sources()
+ scope = hermes_home_key(scope) if scope is not None else None
with _REGISTRY_LOCK:
return _SCOPED_SOURCES.get(scope or hermes_home_key(), {}).get(
name
@@ -179,6 +181,7 @@ def snapshot_registration(
) -> Optional[SecretSource]:
"""Return the registration owned by exactly one registry layer."""
_ensure_builtin_sources()
+ scope = hermes_home_key(scope) if scope is not None else None
with _REGISTRY_LOCK:
target = _SOURCES if scope is None else _SCOPED_SOURCES.get(scope, {})
return target.get(name)
@@ -193,6 +196,7 @@ def restore_registration(
) -> bool:
"""Restore a host-owned source registration if it is still current."""
_ensure_builtin_sources()
+ scope = hermes_home_key(scope) if scope is not None else None
with _REGISTRY_LOCK:
target = _SOURCES if scope is None else _SCOPED_SOURCES.setdefault(scope, {})
if target.get(name) is not current:
@@ -208,6 +212,7 @@ def restore_registration(
def list_sources(*, scope: Optional[str] = None) -> List[SecretSource]:
_ensure_builtin_sources()
+ scope = hermes_home_key(scope) if scope is not None else None
with _REGISTRY_LOCK:
merged = dict(_SOURCES)
merged.update(_SCOPED_SOURCES.get(scope or hermes_home_key(), {}))
diff --git a/agent/skill_commands.py b/agent/skill_commands.py
index 6b776e1f68f..64a1fed723b 100644
--- a/agent/skill_commands.py
+++ b/agent/skill_commands.py
@@ -381,8 +381,10 @@ def _build_skill_message(
if subdir_path.exists():
for f in sorted(subdir_path.rglob("*")):
if f.is_file() and not f.is_symlink():
- rel = str(f.relative_to(skill_dir))
- supporting.append(rel)
+ # as_posix so the listed path matches the footer's
+ # examples (scripts/foo.js) on every OS —
+ # str(relative_to) emits backslashes on Windows.
+ supporting.append(f.relative_to(skill_dir).as_posix())
if supporting and skill_dir:
try:
diff --git a/hermes_cli/kanban.py b/hermes_cli/kanban.py
index e23eedc7fa9..7a9cb5050f7 100644
--- a/hermes_cli/kanban.py
+++ b/hermes_cli/kanban.py
@@ -3474,7 +3474,7 @@ def run_slash(rest: str) -> str:
import io
import contextlib
- tokens = shlex.split(rest) if rest and rest.strip() else []
+ tokens = shlex.split(rest, posix=os.name == "posix") if rest and rest.strip() else []
# Bare ``/kanban`` or ``/kanban help`` / ``--help`` / ``-h`` / ``?``:
# show the curated short-help block instead of dumping argparse's full
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index 9028e285307..5bbad05ff9d 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -3741,8 +3741,9 @@ class PluginManager:
def __init__(self, scope_key: Optional[str] = None) -> None:
# Capture the home immutably. Unload can run from a different ambient
# profile context, but every inverse must target the registration's
- # original scope.
- self.scope_key = scope_key or hermes_home_key()
+ # original scope. Normalize through hermes_home_key so the scope
+ # matches the key the registries store under (normcase on Windows).
+ self.scope_key = hermes_home_key(scope_key) if scope_key else hermes_home_key()
self.home_path = Path(self.scope_key)
self._discovery_lock = threading.RLock()
self._plugins: Dict[str, LoadedPlugin] = {}
diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.py
index 912d93208d2..2c5d721ccd7 100644
--- a/hermes_cli/plugins_cmd.py
+++ b/hermes_cli/plugins_cmd.py
@@ -33,6 +33,25 @@ from utils import atomic_write_text
logger = logging.getLogger(__name__)
+def _rmtree_force(path: Path) -> None:
+ """``shutil.rmtree`` that clears read-only bits before deleting.
+
+ Windows refuses to delete a tree containing read-only files — git clones
+ store objects read-only — raising ``PermissionError`` where POSIX unlinks
+ them fine. The ``onerror`` hook chmods the file writable and retries.
+ """
+ import stat
+
+ def _onerror(func, p, _exc_info):
+ try:
+ os.chmod(p, stat.S_IWRITE)
+ except OSError:
+ pass
+ func(p)
+
+ shutil.rmtree(path, onerror=_onerror)
+
+
@functools.lru_cache(maxsize=1)
def _resolve_git_executable() -> Optional[str]:
"""Resolve a git binary for subprocess use when ``PATH`` may be minimal.
@@ -867,7 +886,7 @@ def _install_plugin_core(
_write_install_metadata(new_metadata)
except Exception:
if target.exists():
- shutil.rmtree(target)
+ _rmtree_force(target)
if replaced_existing and backup.exists():
os.replace(backup, target)
if old_metadata:
@@ -1208,7 +1227,7 @@ def _remove_plugin_core(target: Path) -> None:
"""Remove one plugin and its metadata without splitting their state."""
metadata = _read_install_metadata()
if target.name not in metadata:
- shutil.rmtree(target)
+ _rmtree_force(target)
return
updated = dict(metadata)
@@ -1230,7 +1249,7 @@ def _remove_plugin_core(target: Path) -> None:
) from restore_exc
shutil.rmtree(staging, ignore_errors=True)
raise
- shutil.rmtree(staging)
+ _rmtree_force(staging)
def cmd_remove(name: str) -> None:
diff --git a/hermes_state.py b/hermes_state.py
index 831fcbc78dd..2ed2733bc63 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -15091,10 +15091,12 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
return 0
def _do(conn):
+ esc = _escape_like(prefix)
cursor = conn.execute(
"UPDATE sessions SET source = 'kanban' "
- "WHERE source = 'cli' AND (cwd = ? OR cwd LIKE ? ESCAPE '\\')",
- (prefix, _escape_like(prefix) + "/%"),
+ "WHERE source = 'cli' AND (cwd = ? OR cwd LIKE ? ESCAPE '\\' "
+ "OR cwd LIKE ? ESCAPE '\\')",
+ (prefix, f"{esc}/%", f"{esc}\\\\%"),
)
# Read rowcount before set_meta reuses this cursor for its INSERT,
# which would otherwise overwrite it with the meta write's count.
diff --git a/plugins/disk-cleanup/__init__.py b/plugins/disk-cleanup/__init__.py
index 71d44b1c891..dcc35c7bc84 100644
--- a/plugins/disk-cleanup/__init__.py
+++ b/plugins/disk-cleanup/__init__.py
@@ -21,6 +21,7 @@ needs to remember to run commands.
from __future__ import annotations
import logging
+import os
import re
import shlex
import threading
@@ -42,7 +43,9 @@ _lock = threading.Lock()
# Tool-call result shapes we can parse
_WRITE_FILE_PATH_KEY = "path"
-_TERMINAL_PATH_REGEX = re.compile(r"(?:^|\s)(/[^\s'\"`]+|\~/[^\s'\"`]+)")
+_TERMINAL_PATH_REGEX = re.compile(
+ r"(?:^|\s)(/[^\s'\"`]+|~/[^\s'\"`]+|[A-Za-z]:[\\/][^\s'\"`]+)"
+)
# ---------------------------------------------------------------------------
@@ -107,10 +110,12 @@ def _extract_paths_from_terminal(args: Dict[str, Any], result: str) -> Set[str]:
paths: Set[str] = set()
cmd = args.get("command") or ""
if isinstance(cmd, str) and cmd:
- # Tokenise the command — catches `touch /tmp/hermes-x/test_foo.py`
+ # Tokenise the command — catches `touch /tmp/hermes-x/test_foo.py`.
+ # ``posix`` follows the host so Windows backslash paths survive
+ # (``shlex.split(posix=True)`` would eat them as escapes).
try:
- for tok in shlex.split(cmd, posix=True):
- if tok.startswith(("/", "~")):
+ for tok in shlex.split(cmd, posix=os.name == "posix"):
+ if tok.startswith(("/", "~")) or re.match(r"^[A-Za-z]:[\\/]", tok):
paths.add(tok)
except ValueError:
pass
diff --git a/scripts/check_subprocess_stdin.py b/scripts/check_subprocess_stdin.py
index 884923e2e04..8502e13f182 100644
--- a/scripts/check_subprocess_stdin.py
+++ b/scripts/check_subprocess_stdin.py
@@ -172,8 +172,9 @@ def main() -> int:
for py_file in dirpath.rglob("*.py"):
rel = str(py_file.relative_to(repo_root))
- # Skip known-safe files.
- if rel in KNOWN_SAFE:
+ # Skip known-safe files. ``relative_to`` returns a host-separated
+ # path (backslashes on Windows) while KNOWN_SAFE is forward-slash.
+ if py_file.relative_to(repo_root).as_posix() in KNOWN_SAFE:
continue
# Skip test files inside tools/ etc.
diff --git a/tests/acp/test_ping_suppression.py b/tests/acp/test_ping_suppression.py
index 1682c6ad544..d003ba1e73c 100644
--- a/tests/acp/test_ping_suppression.py
+++ b/tests/acp/test_ping_suppression.py
@@ -99,6 +99,7 @@ class _FakeAgent:
pass
@pytest.mark.asyncio
async def test_bare_ping_request_produces_proper_response_and_no_stderr_noise(
caplog: pytest.LogCaptureFixture,
diff --git a/tests/acp/test_session.py b/tests/acp/test_session.py
index 7922846725d..4d3a1a20212 100644
--- a/tests/acp/test_session.py
+++ b/tests/acp/test_session.py
@@ -164,6 +164,7 @@ class TestSymlinkAliasNormalization:
``/private/tmp``) must compare equal, or ACP history filters silently drop
a workspace's own sessions."""
+ @pytest.mark.require_symlinks
def test_symlink_alias_compares_equal(self, tmp_path):
real = tmp_path / "real"
real.mkdir()
@@ -188,8 +189,9 @@ class TestSymlinkAliasNormalization:
# exactly as the old normpath comparison did.
assert acp_session._normalize_cwd_for_compare(
"/nonexistent-hermes-test/x/../y"
- ) == "/nonexistent-hermes-test/y"
+ ) == acp_session._normalize_cwd_for_compare("/nonexistent-hermes-test/y")
+ @pytest.mark.require_symlinks
def test_list_sessions_matches_symlink_alias_cwd(self, manager, tmp_path):
real = tmp_path / "proj"
real.mkdir()
diff --git a/tests/acp_adapter/test_acp_images.py b/tests/acp_adapter/test_acp_images.py
index 3ef1f48fe2e..296701c2a04 100644
--- a/tests/acp_adapter/test_acp_images.py
+++ b/tests/acp_adapter/test_acp_images.py
@@ -38,7 +38,7 @@ def test_text_only_acp_blocks_stay_string_for_legacy_prompt_path():
def test_acp_resource_link_file_is_inlined_as_text(tmp_path):
attached = tmp_path / "notes.md"
- attached.write_text("# Notes\n\nAttached file body", encoding="utf-8")
+ attached.write_text("# Notes\n\nAttached file body", encoding="utf-8", newline="\n")
content = _content_blocks_to_openai_user_content([
TextContentBlock(type="text", text="Please read this file"),
diff --git a/tests/agent/lsp/test_install_and_lint_fixes.py b/tests/agent/lsp/test_install_and_lint_fixes.py
index b614cee50f3..cbaa30e3887 100644
--- a/tests/agent/lsp/test_install_and_lint_fixes.py
+++ b/tests/agent/lsp/test_install_and_lint_fixes.py
@@ -45,7 +45,7 @@ def test_install_npm_works_without_extras(tmp_path, monkeypatch):
from agent.lsp import install as install_mod
monkeypatch.setattr(install_mod.subprocess, "run", fake_run)
- monkeypatch.setattr(install_mod.shutil, "which", lambda c: "/usr/bin/npm" if c == "npm" else None)
+ monkeypatch.setattr(install_mod, "find_node_executable", lambda name: "/usr/bin/npm")
install_mod._install_npm("pyright", "pyright-langserver")
diff --git a/tests/agent/lsp/test_workspace.py b/tests/agent/lsp/test_workspace.py
index 8d96f902d68..c7b22a5ddc9 100644
--- a/tests/agent/lsp/test_workspace.py
+++ b/tests/agent/lsp/test_workspace.py
@@ -69,6 +69,7 @@ def test_resolve_workspace_for_file_uses_cwd_first(tmp_path: Path, monkeypatch):
def test_normalize_path_expands_tilde(monkeypatch):
monkeypatch.setenv("HOME", "/home/user")
p = normalize_path("~/x.py")
diff --git a/tests/agent/test_command_token_source.py b/tests/agent/test_command_token_source.py
index e7210480ef4..325a310d15c 100644
--- a/tests/agent/test_command_token_source.py
+++ b/tests/agent/test_command_token_source.py
@@ -91,12 +91,14 @@ class TestNoCredentialLeak:
class TestCaching:
+ @pytest.mark.linux_only
def test_token_is_cached_between_calls(self):
"""Without caching the command would run on every request."""
# A command whose output changes each run: equal results prove caching.
source = CommandTokenSource("date +%s%N", "dbx")
assert source() == source()
+ @pytest.mark.linux_only
def test_expired_token_is_reminted(self):
# date +%s%N changes every run; $RANDOM would be bash-only (empty
# under dash, which is what /bin/sh is on Debian-family CI).
@@ -109,6 +111,7 @@ class TestCaching:
source._expires_at = 0.0
assert source() != first
+ @pytest.mark.linux_only
def test_no_advertised_ttl_caches_on_a_bounded_window(self):
"""No TTL means a bounded cache, not a process-lifetime one.
@@ -279,6 +282,7 @@ class TestAbsoluteExpiry:
)
assert ttl is None
+ @pytest.mark.linux_only
def test_the_token_actually_gets_re_minted(self, tmp_path):
"""The regression that mattered: a deadline must expire the cache."""
counter = tmp_path / "calls"
diff --git a/tests/agent/test_file_safety_sandbox_mirror.py b/tests/agent/test_file_safety_sandbox_mirror.py
index bb59c1ecfb2..b974f5e8aff 100644
--- a/tests/agent/test_file_safety_sandbox_mirror.py
+++ b/tests/agent/test_file_safety_sandbox_mirror.py
@@ -14,6 +14,7 @@ The agent reported success; the rule never took effect.
"""
from __future__ import annotations
+import os
from pathlib import Path
import pytest
@@ -42,9 +43,9 @@ class TestClassifySandboxMirrorTarget:
assert result is not None
assert result["target_path"] == str(target.resolve())
assert result["mirror_root"].endswith(
- "sandboxes/docker/default/home/.hermes"
+ os.path.join("sandboxes", "docker", "default", "home", ".hermes")
)
- assert result["inner_path"] == "profiles/group1/SOUL.md"
+ assert result["inner_path"] == os.path.join("profiles", "group1", "SOUL.md")
@pytest.mark.parametrize(
"backend,inner",
@@ -68,7 +69,7 @@ class TestClassifySandboxMirrorTarget:
result = classify_sandbox_mirror_target(str(target))
assert result is not None
- assert result["inner_path"] == inner
+ assert result["inner_path"] == str(Path(inner))
assert backend in result["mirror_root"]
@@ -107,9 +108,9 @@ class TestGetSandboxMirrorWarning:
warn = get_sandbox_mirror_warning(str(target))
assert warn is not None
# Must name the mirror root so the user can locate the sandbox.
- assert "sandboxes/docker/default/home/.hermes" in warn
+ assert os.path.join("sandboxes", "docker", "default", "home", ".hermes") in warn
# Must hint at what the agent likely meant.
- assert "profiles/group1/SOUL.md" in warn
+ assert os.path.join("profiles", "group1", "SOUL.md") in warn
# Must name the bypass kwarg shared with the cross-profile guard.
assert "cross_profile=True" in warn
diff --git a/tests/agent/test_image_routing.py b/tests/agent/test_image_routing.py
index f545909e1fa..b26dae5dfe0 100644
--- a/tests/agent/test_image_routing.py
+++ b/tests/agent/test_image_routing.py
@@ -378,8 +378,13 @@ class TestExtractImageRefs:
assert urls == []
def test_finds_home_relative_path(self, tmp_path: Path, monkeypatch):
- # Simulate ~/foo.png by pointing HOME at tmp_path and creating the file
+ # Simulate ~/foo.png by pointing the home env vars at tmp_path and
+ # creating the file. Windows resolves ~ via USERPROFILE (before HOME),
+ # so set both and clear the HOMEDRIVE/HOMEPATH fallback.
monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ monkeypatch.delenv("HOMEDRIVE", raising=False)
+ monkeypatch.delenv("HOMEPATH", raising=False)
img = tmp_path / "foo.png"
img.write_bytes(_png_bytes())
paths, urls = extract_image_refs("see ~/foo.png please")
diff --git a/tests/agent/test_proxy_and_url_validation.py b/tests/agent/test_proxy_and_url_validation.py
index 766c361630a..c230bf68b27 100644
--- a/tests/agent/test_proxy_and_url_validation.py
+++ b/tests/agent/test_proxy_and_url_validation.py
@@ -28,7 +28,7 @@ from agent.auxiliary_client import _validate_base_url, _validate_proxy_env_urls
])
def test_proxy_env_rejects_malformed_port(monkeypatch, key):
monkeypatch.setenv(key, "http://127.0.0.1:6153export")
- with pytest.raises(RuntimeError, match=rf"Malformed proxy environment variable {key}=.*6153export"):
+ with pytest.raises(RuntimeError, match=rf"(?i)Malformed proxy environment variable {key}=.*6153export"):
_validate_proxy_env_urls()
diff --git a/tests/agent/test_relay_runtime_plugins.py b/tests/agent/test_relay_runtime_plugins.py
index a906f94f29b..4cd1c037211 100644
--- a/tests/agent/test_relay_runtime_plugins.py
+++ b/tests/agent/test_relay_runtime_plugins.py
@@ -1025,7 +1025,7 @@ enabled = true
[[components.config.atof.sinks]]
type = "file"
-output_directory = "{atof_dir}"
+output_directory = "{atof_dir.as_posix()}"
filename = "events.jsonl"
mode = "overwrite"
""".strip(),
@@ -1081,7 +1081,7 @@ enabled = true
[[components.config.atof.sinks]]
type = "file"
-output_directory = "{atof_dir}"
+output_directory = "{atof_dir.as_posix()}"
filename = "events.jsonl"
mode = "overwrite"
""".strip(),
@@ -1142,13 +1142,13 @@ enabled = true
[[components.config.atof.sinks]]
type = "file"
-output_directory = "{atof_dir}"
+output_directory = "{atof_dir.as_posix()}"
filename = "events.jsonl"
mode = "overwrite"
[components.config.atif]
enabled = true
-output_directory = "{atif_dir}"
+output_directory = "{atif_dir.as_posix()}"
filename_template = "trajectory-{{session_id}}.json"
agent_name = "Hermes Native Test"
agent_version = "test"
diff --git a/tests/agent/test_save_url_image.py b/tests/agent/test_save_url_image.py
index 3737871f675..3cf698c26cd 100644
--- a/tests/agent/test_save_url_image.py
+++ b/tests/agent/test_save_url_image.py
@@ -13,6 +13,7 @@ and the gateway 404'd at ``send_photo`` time.
from __future__ import annotations
import http.server
+import os
import socketserver
import threading
@@ -104,7 +105,7 @@ class TestSaveUrlImage:
assert path.read_bytes() == PNG_1PX
# The cache directory must be under HERMES_HOME — gateway cleanup
# relies on this being the canonical location.
- assert "cache/images" in str(path)
+ assert os.path.join("cache", "images") in str(path)
assert path.suffix == ".png"
diff --git a/tests/agent/test_shell_hooks.py b/tests/agent/test_shell_hooks.py
index ef7c45ebf70..cc52130503b 100644
--- a/tests/agent/test_shell_hooks.py
+++ b/tests/agent/test_shell_hooks.py
@@ -142,6 +142,7 @@ class TestMatcher:
# ── End-to-end subprocess behaviour ───────────────────────────────────────
class TestCallbackSubprocess:
@@ -678,6 +679,7 @@ class TestEvaluateResult:
class TestFailSemanticsEndToEnd:
+ @pytest.mark.linux_only
def test_exit_2_script_blocks(self, tmp_path):
script = _write_script(
tmp_path, "exit2.sh",
@@ -705,6 +707,7 @@ class TestFailSemanticsEndToEnd:
assert result is not None and result["action"] == "block"
assert "failed closed" in result["message"]
+ @pytest.mark.linux_only
def test_run_once_reflects_exit_2_block(self, tmp_path):
"""hermes hooks test must mirror production semantics."""
script = _write_script(
@@ -722,6 +725,7 @@ class TestFailSemanticsEndToEnd:
assert result["returncode"] == 2
assert result["parsed"] == {"action": "block", "message": "denied"}
+ @pytest.mark.linux_only
def test_run_once_reflects_fail_closed_timeout(self, tmp_path):
script = _write_script(
tmp_path, "sleepy.sh",
diff --git a/tests/agent/test_shell_hooks_consent.py b/tests/agent/test_shell_hooks_consent.py
index 6835e06c3d3..86cb565a3f3 100644
--- a/tests/agent/test_shell_hooks_consent.py
+++ b/tests/agent/test_shell_hooks_consent.py
@@ -144,6 +144,7 @@ class TestAllowlistOps:
+ @pytest.mark.linux_only
def test_tilde_path_approval_records_resolvable_mtime(self, tmp_path, monkeypatch):
"""If the command uses ~ the approval must still find the file."""
monkeypatch.setenv("HOME", str(tmp_path))
diff --git a/tests/agent/test_skill_commands.py b/tests/agent/test_skill_commands.py
index 623f5a5c05c..68b9f30c2a8 100644
--- a/tests/agent/test_skill_commands.py
+++ b/tests/agent/test_skill_commands.py
@@ -762,6 +762,7 @@ class TestInlineShellExpansion:
+ @pytest.mark.linux_only
def test_inline_shell_runs_in_skill_directory(self, tmp_path):
"""Inline snippets get the skill dir as CWD so relative paths work."""
with (
diff --git a/tests/agent/test_subdirectory_hints.py b/tests/agent/test_subdirectory_hints.py
index 85b89f647ef..e310aed62e0 100644
--- a/tests/agent/test_subdirectory_hints.py
+++ b/tests/agent/test_subdirectory_hints.py
@@ -182,6 +182,7 @@ class TestContentDeduplication:
"""The same context content must never be injected twice (ref: symlinked
shared workspaces, hardlinks, and copied backups all alias one file)."""
+ @pytest.mark.require_symlinks
def test_symlinked_duplicate_not_reinjected(self, tmp_path):
"""Two directories whose AGENTS.md is the same file yield one injection."""
real = tmp_path / "real"
diff --git a/tests/agent/test_treekill_consolidation.py b/tests/agent/test_treekill_consolidation.py
index 902629986c2..6812798df11 100644
--- a/tests/agent/test_treekill_consolidation.py
+++ b/tests/agent/test_treekill_consolidation.py
@@ -135,6 +135,7 @@ class TestCodeExecutionDelegation:
code_execution_tool._kill_process_group(proc)
assert calls == [(5555, _signal.SIGTERM)]
+ @pytest.mark.linux_only
def test_escalate_waits_then_sigkills_tree(self, monkeypatch):
import signal as _signal
diff --git a/tests/cli/test_bang_shell_mode.py b/tests/cli/test_bang_shell_mode.py
index 63fedde30d3..bc369372de6 100644
--- a/tests/cli/test_bang_shell_mode.py
+++ b/tests/cli/test_bang_shell_mode.py
@@ -89,6 +89,7 @@ class TestBangContextGating:
# ── execution ──────────────────────────────────────────────────────────────
class TestBangExecution:
+ @pytest.mark.linux_only
def test_output_is_streamed_to_writer(self):
lines = []
code = run_bang_command("echo bang-one; echo bang-two", writer=lines.append)
@@ -96,6 +97,7 @@ class TestBangExecution:
assert "bang-one" in lines
assert "bang-two" in lines
+ @pytest.mark.linux_only
def test_stderr_is_merged_into_output(self):
lines = []
run_bang_command("echo to-stderr >&2", writer=lines.append)
@@ -106,6 +108,7 @@ class TestBangExecution:
code = run_bang_command("exit 42", writer=lines.append)
assert code == 42
+ @pytest.mark.linux_only
def test_runs_in_requested_cwd(self, tmp_path):
lines = []
code = run_bang_command("pwd", cwd=str(tmp_path), writer=lines.append)
diff --git a/tests/cli/test_cli_init.py b/tests/cli/test_cli_init.py
index cca40f831e7..4badd60691f 100644
--- a/tests/cli/test_cli_init.py
+++ b/tests/cli/test_cli_init.py
@@ -154,6 +154,7 @@ class TestBusyInputMode:
class TestPromptToolkitTerminalCompatibility:
+ @pytest.mark.linux_only
def test_lf_enter_binding_respects_multiline_shortcuts(self):
"""Ctrl+J is reserved by default, with legacy LF-submit available as an opt-out.
@@ -251,6 +252,7 @@ class TestPromptToolkitTerminalCompatibility:
+ @pytest.mark.linux_only
def test_cpr_gating_posix_suppresses_without_ssh(self, monkeypatch):
"""POSIX suppresses CPR without SSH.
diff --git a/tests/cli/test_cli_light_mode.py b/tests/cli/test_cli_light_mode.py
index 0763cc4ff67..a8ef9f208bd 100644
--- a/tests/cli/test_cli_light_mode.py
+++ b/tests/cli/test_cli_light_mode.py
@@ -176,6 +176,7 @@ class TestSkinConfigHook:
assert skin.get_color("banner_text") == "#FFF8DC"
class TestOsc11DrainGuard:
"""Regression: a late-arriving OSC 11 reply must not leak into
prompt_toolkit's input buffer (#40250).
diff --git a/tests/cli/test_worktree.py b/tests/cli/test_worktree.py
index c2fe4119c06..e06ee84bd12 100644
--- a/tests/cli/test_worktree.py
+++ b/tests/cli/test_worktree.py
@@ -1342,6 +1342,7 @@ class TestShallowCloneDeepening:
)
class TestPrMergedEscapeHatch:
"""Rebase-merged PRs whose diff changed during salvage defeat ``git
cherry`` (patch-id mismatch), so the pruner asks GitHub whether the
diff --git a/tests/cron/test_cron_workdir.py b/tests/cron/test_cron_workdir.py
index 013de5dca5a..ecf19611327 100644
--- a/tests/cron/test_cron_workdir.py
+++ b/tests/cron/test_cron_workdir.py
@@ -45,6 +45,7 @@ class TestNormalizeWorkdir:
result = _normalize_workdir(str(tmp_path))
assert result == str(tmp_path.resolve())
+ @pytest.mark.linux_only
def test_tilde_expands(self, tmp_path, monkeypatch):
from cron.jobs import _normalize_workdir
monkeypatch.setenv("HOME", str(tmp_path))
diff --git a/tests/cron/test_file_permissions.py b/tests/cron/test_file_permissions.py
index 20f57a82b74..c05b35842e0 100644
--- a/tests/cron/test_file_permissions.py
+++ b/tests/cron/test_file_permissions.py
@@ -7,6 +7,10 @@ import unittest
from pathlib import Path
from unittest.mock import patch
+import pytest
+
+pytestmark = pytest.mark.linux_only
+
class TestCronFilePermissions(unittest.TestCase):
"""Verify cron files get secure permissions."""
diff --git a/tests/cron/test_media_delivery_parity.py b/tests/cron/test_media_delivery_parity.py
index 8e6a6dd70d8..b7134441964 100644
--- a/tests/cron/test_media_delivery_parity.py
+++ b/tests/cron/test_media_delivery_parity.py
@@ -25,6 +25,7 @@ Three defects, each pinned here:
MEDIA paths under different policy than the gateway's scheduled tick.
"""
+import json
import os
from pathlib import Path
@@ -231,7 +232,7 @@ class TestMediaPolicyEnvBridge:
(home / "config.yaml").write_text(
"gateway:\n"
" strict: true\n"
- f" media_delivery_allow_dirs: [{str(allow_dir)!r}]\n"
+ f" media_delivery_allow_dirs: [{json.dumps(str(allow_dir))}]\n"
" trust_recent_files: false\n"
)
monkeypatch.setenv("HERMES_HOME", str(home))
diff --git a/tests/cron/test_script_claim_heartbeat.py b/tests/cron/test_script_claim_heartbeat.py
index 8d81470576c..93cb8b659fa 100644
--- a/tests/cron/test_script_claim_heartbeat.py
+++ b/tests/cron/test_script_claim_heartbeat.py
@@ -10,6 +10,7 @@ from unittest.mock import MagicMock, patch
import pytest
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
@@ -540,8 +541,10 @@ def test_repeated_heartbeat_errors_cancel_after_bounded_grace(monkeypatch):
}
monkeypatch.setattr(scheduler, "heartbeat_fire_claim", heartbeat)
monkeypatch.setattr(scheduler, "_run_one_job_body", run_body)
- monkeypatch.setattr(scheduler, "_RUN_CLAIM_HEARTBEAT_SECONDS", 0.01)
- monkeypatch.setattr(scheduler, "_FIRE_CLAIM_HEARTBEAT_GRACE_SECONDS", 0.03)
+ # Intervals well above Windows' ~15ms timer resolution so the grace window
+ # reliably spans 3+ heartbeat ticks (10ms/30ms left only ~2 on win32).
+ monkeypatch.setattr(scheduler, "_RUN_CLAIM_HEARTBEAT_SECONDS", 0.05)
+ monkeypatch.setattr(scheduler, "_FIRE_CLAIM_HEARTBEAT_GRACE_SECONDS", 0.3)
assert scheduler.run_one_job(job) is True
assert calls >= 3
diff --git a/tests/gateway/test_73771_media_resend_dedup.py b/tests/gateway/test_73771_media_resend_dedup.py
index d0490e8056d..3be77f0eca6 100644
--- a/tests/gateway/test_73771_media_resend_dedup.py
+++ b/tests/gateway/test_73771_media_resend_dedup.py
@@ -27,6 +27,7 @@ import threading
import time
from types import SimpleNamespace
from unittest.mock import AsyncMock
+from urllib.parse import unquote
import pytest
@@ -495,7 +496,7 @@ async def test_streamed_explicit_media_resend_is_delivered(tmp_path, monkeypatch
adapter.send_multiple_images.assert_awaited_once()
sent_paths = [p for p, _cap in adapter.send_multiple_images.await_args.kwargs["images"]]
- assert str(img) in sent_paths[0]
+ assert str(img) in unquote(sent_paths[0])
def test_stream_rescan_accepts_no_history_dedup_input():
diff --git a/tests/gateway/test_complete_path_at_filter.py b/tests/gateway/test_complete_path_at_filter.py
index 8add45006bb..28479e11135 100644
--- a/tests/gateway/test_complete_path_at_filter.py
+++ b/tests/gateway/test_complete_path_at_filter.py
@@ -223,6 +223,7 @@ def test_leading_slash_matches_the_bare_form(tmp_path, monkeypatch):
assert slashed == bare
def test_leading_slash_prefers_a_real_absolute_path(tmp_path, monkeypatch):
"""When the absolute reading resolves, it wins — no silent rewrite.
diff --git a/tests/gateway/test_feishu.py b/tests/gateway/test_feishu.py
index a923ea5f5d4..a834a45e580 100644
--- a/tests/gateway/test_feishu.py
+++ b/tests/gateway/test_feishu.py
@@ -15,6 +15,9 @@ from unittest.mock import AsyncMock, Mock, patch
from gateway.platforms.base import ProcessingOutcome
+import os as _os
+_SYS_ENV = {k: _os.environ[k] for k in ("SYSTEMROOT", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "HOME") if k in _os.environ}
+
try:
import lark_oapi
_HAS_LARK_OAPI = True
@@ -182,7 +185,7 @@ class TestFeishuAdapterMessaging(unittest.TestCase):
self.assertIsNone(adapter._ws_client)
- @patch.dict(os.environ, {
+ @patch.dict(os.environ, {**_SYS_ENV,
"FEISHU_APP_ID": "cli_app",
"FEISHU_APP_SECRET": "secret_app",
}, clear=True)
@@ -242,7 +245,7 @@ class TestFeishuAdapterMessaging(unittest.TestCase):
"extra_ua_tags must be ['channel'] to enable group event routing")
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_edit_message_falls_back_to_text_when_post_update_is_rejected(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -368,7 +371,7 @@ def _admits_group(adapter, message, sender_id, chat_id=""):
class TestAdapterBehavior(unittest.TestCase):
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_build_event_handler_registers_reaction_and_card_processors(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -450,7 +453,7 @@ class TestAdapterBehavior(unittest.TestCase):
],
)
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_bot_origin_reactions_are_dropped_to_avoid_feedback_loops(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -471,7 +474,7 @@ class TestAdapterBehavior(unittest.TestCase):
adapter._on_reaction_event("im.message.reaction.created_v1", data)
run_threadsafe.assert_not_called()
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_user_reaction_with_managed_emoji_is_still_routed(self):
# Operator-origin filter is enough to prevent feedback loops; we must
# not additionally swallow user-origin reactions just because their
@@ -529,7 +532,7 @@ class TestAdapterBehavior(unittest.TestCase):
adapter.get_chat_info = AsyncMock(return_value={"name": "Test Chat"})
return adapter
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_reaction_on_peer_bot_message_is_not_routed(self):
# GET im/v1/messages sender for bot messages carries id=app_id; a peer
# bot's message has a different app_id than ours, so it must be dropped.
@@ -639,7 +642,7 @@ class TestAdapterBehavior(unittest.TestCase):
)
- @patch.dict(os.environ, {"FEISHU_GROUP_POLICY": "open"}, clear=True)
+ @patch.dict(os.environ, {**_SYS_ENV, "FEISHU_GROUP_POLICY": "open"}, clear=True)
def test_group_message_matches_bot_name_when_only_name_available(self):
"""Name fallback engages when either side lacks an open_id. When BOTH
the mention and the bot carry open_ids, IDs are authoritative — a
@@ -697,7 +700,7 @@ class TestAdapterBehavior(unittest.TestCase):
)
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_extract_post_message_downloads_embedded_resources(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -734,7 +737,7 @@ class TestAdapterBehavior(unittest.TestCase):
)
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_extract_audio_message_downloads_and_caches(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -761,7 +764,7 @@ class TestAdapterBehavior(unittest.TestCase):
self.assertEqual(media_types, ["audio/ogg"])
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_extract_text_message_starting_with_slash_becomes_command(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -799,7 +802,7 @@ class TestAdapterBehavior(unittest.TestCase):
self.assertEqual(event.message_type.value, "command")
self.assertEqual(event.text, "/help test")
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_extract_text_file_injects_content(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -817,7 +820,7 @@ class TestAdapterBehavior(unittest.TestCase):
self.assertIn("hello from feishu", text)
self.assertIn("[Content of", text)
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_message_event_submits_to_adapter_loop(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -852,7 +855,7 @@ class TestAdapterBehavior(unittest.TestCase):
self.assertTrue(submit.called)
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_webhook_request_uses_same_message_dispatch_path(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -876,7 +879,7 @@ class TestAdapterBehavior(unittest.TestCase):
self.assertEqual(response.status, 200)
adapter._on_message_event.assert_called_once()
- @patch.dict(os.environ, {"FEISHU_VERIFICATION_TOKEN": "expected-token"}, clear=True)
+ @patch.dict(os.environ, {**_SYS_ENV, "FEISHU_VERIFICATION_TOKEN": "expected-token"}, clear=True)
def test_url_verification_requires_configured_verification_token(self):
"""url_verification must be rejected when token is set but mismatched.
@@ -904,7 +907,7 @@ class TestAdapterBehavior(unittest.TestCase):
self.assertEqual(response.status, 401)
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_process_inbound_message_uses_event_sender_identity_only(self):
from gateway.config import PlatformConfig
from gateway.platforms.base import MessageType
@@ -954,6 +957,7 @@ class TestAdapterBehavior(unittest.TestCase):
@patch.dict(
os.environ,
{
+ **_SYS_ENV,
"HERMES_FEISHU_TEXT_BATCH_MAX_MESSAGES": "2",
},
clear=True,
@@ -1001,7 +1005,7 @@ class TestAdapterBehavior(unittest.TestCase):
self.assertEqual(first.text, "A\nB")
self.assertEqual(second.text, "C")
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_media_batch_merges_rapid_photo_messages(self):
from gateway.config import PlatformConfig
from gateway.platforms.base import MessageEvent, MessageType
@@ -1191,7 +1195,7 @@ class TestAdapterBehavior(unittest.TestCase):
self.assertTrue(second._is_duplicate("om_same"))
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_send_document_reply_uses_thread_flag(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -1247,7 +1251,7 @@ class TestAdapterBehavior(unittest.TestCase):
self.assertTrue(captured["request"].request_body.reply_in_thread)
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_send_uses_post_for_every_chunk_of_multi_chunk_markdown(self):
"""Regression for #26841: when a long Markdown message is split
across multiple chunks, every chunk must go out as
@@ -1307,7 +1311,7 @@ class TestAdapterBehavior(unittest.TestCase):
self.assertEqual(msg_types, ["post", "post"])
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_send_splits_fenced_code_blocks_into_separate_post_rows(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -1387,7 +1391,7 @@ class TestHydrateBotIdentity(unittest.TestCase):
return FeishuAdapter(PlatformConfig())
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_hydration_populates_open_id_from_bot_info(self):
adapter = self._make_adapter()
adapter._client = Mock()
@@ -1411,6 +1415,7 @@ class TestHydrateBotIdentity(unittest.TestCase):
@patch.dict(
os.environ,
{
+ **_SYS_ENV,
"FEISHU_BOT_OPEN_ID": "ou_env",
"FEISHU_BOT_NAME": "Env Hermes",
},
@@ -1446,7 +1451,7 @@ class TestPendingInboundQueue(unittest.TestCase):
before or during adapter loop transitions must be queued for replay
rather than silently dropped."""
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_event_queued_when_loop_not_ready(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -1466,7 +1471,7 @@ class TestPendingInboundQueue(unittest.TestCase):
# Drain scheduled flag set.
self.assertTrue(adapter._pending_drain_scheduled)
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_drainer_replays_queued_events_when_loop_becomes_ready(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -1521,7 +1526,7 @@ class TestWebhookSecurity(unittest.TestCase):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
- with patch.dict(os.environ, {"FEISHU_APP_ID": "cli", "FEISHU_APP_SECRET": "sec", "FEISHU_ENCRYPT_KEY": encrypt_key}, clear=True):
+ with patch.dict(os.environ, {**_SYS_ENV, "FEISHU_APP_ID": "cli", "FEISHU_APP_SECRET": "sec", "FEISHU_ENCRYPT_KEY": encrypt_key}, clear=True):
return FeishuAdapter(PlatformConfig())
def test_signature_valid_passes(self):
@@ -1576,7 +1581,7 @@ class TestWebhookSecurity(unittest.TestCase):
self.assertEqual(content.read_sizes, [_FEISHU_WEBHOOK_MAX_BODY_BYTES + 1])
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_webhook_connect_requires_inbound_auth_secret(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -1589,7 +1594,7 @@ class TestWebhookSecurity(unittest.TestCase):
)
self.assertFalse(asyncio.run(adapter.connect()))
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_webhook_loads_auth_secrets_from_platform_extra(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -1613,7 +1618,7 @@ class TestWebhookSecurity(unittest.TestCase):
class TestDedupTTL(unittest.TestCase):
"""Tests for TTL-aware deduplication."""
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_duplicate_within_ttl_is_rejected(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -1625,7 +1630,7 @@ class TestDedupTTL(unittest.TestCase):
self.assertTrue(adapter._is_duplicate("om_dup"))
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_load_tolerates_malformed_timestamp_values(self):
"""Regression #13632 — a non-numeric timestamp in the persisted
dedup state must not crash adapter startup. The bad key is
@@ -1636,7 +1641,7 @@ class TestDedupTTL(unittest.TestCase):
from plugins.platforms.feishu.adapter import FeishuAdapter
with tempfile.TemporaryDirectory() as temp_home:
- with patch.dict(os.environ, {"HERMES_HOME": temp_home}, clear=True):
+ with patch.dict(os.environ, {**_SYS_ENV, "HERMES_HOME": temp_home}, clear=True):
adapter = FeishuAdapter(PlatformConfig())
adapter._dedup_state_path.parent.mkdir(parents=True, exist_ok=True)
adapter._dedup_state_path.write_text(
@@ -1661,7 +1666,7 @@ class TestGroupMentionAtAll(unittest.TestCase):
"""Tests for @_all (Feishu @everyone) group mention routing."""
- @patch.dict(os.environ, {"FEISHU_GROUP_POLICY": "allowlist", "FEISHU_ALLOWED_USERS": "ou_allowed"}, clear=True)
+ @patch.dict(os.environ, {**_SYS_ENV, "FEISHU_GROUP_POLICY": "allowlist", "FEISHU_ALLOWED_USERS": "ou_allowed"}, clear=True)
def test_at_all_still_requires_policy_gate(self):
"""@_all bypasses mention gating but NOT the allowlist policy."""
from gateway.config import PlatformConfig
@@ -1682,7 +1687,7 @@ class TestSenderNameResolution(unittest.TestCase):
"""Tests for _resolve_sender_name_from_api (contact API + cache)."""
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_returns_cached_name_within_ttl(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -1694,7 +1699,7 @@ class TestSenderNameResolution(unittest.TestCase):
result = asyncio.run(adapter._resolve_sender_name_from_api("ou_cached"))
self.assertEqual(result, "Alice")
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_fetches_and_caches_name_from_api(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -1751,7 +1756,7 @@ class TestBotNameResolution(unittest.TestCase):
adapter._client = SimpleNamespace(request=_fake_request)
return adapter, calls
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_returns_cached_bot_name_without_api_call(self):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
@@ -1764,7 +1769,7 @@ class TestBotNameResolution(unittest.TestCase):
result = asyncio.run(adapter._resolve_sender_name_from_api("ou_peer", is_bot=True))
self.assertEqual(result, "Peer Bot")
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_fetches_and_caches_bot_name(self):
adapter, calls = self._build_adapter_with_bots({"ou_peer": "Peer Bot"})
@@ -1850,7 +1855,7 @@ class TestProcessingReactions(unittest.TestCase):
return patch("plugins.platforms.feishu.adapter.asyncio.to_thread", side_effect=_direct)
# ------------------------------------------------------------------ start
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_start_adds_typing_and_caches_reaction_id(self):
adapter, tracker = self._build_adapter(next_reaction_id="r_typing")
with self._patch_to_thread():
@@ -1860,7 +1865,7 @@ class TestProcessingReactions(unittest.TestCase):
# --------------------------------------------------------------- complete
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_success_removes_typing_and_adds_nothing(self):
adapter, tracker = self._build_adapter(next_reaction_id="r_typing")
with self._patch_to_thread():
@@ -1872,7 +1877,7 @@ class TestProcessingReactions(unittest.TestCase):
self.assertEqual(tracker.delete_calls, ["r_typing"])
self.assertNotIn("om_msg", adapter._pending_processing_reactions)
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_failure_removes_typing_then_adds_cross_mark(self):
adapter, tracker = self._build_adapter(next_reaction_id="r_typing")
with self._patch_to_thread():
@@ -1885,7 +1890,7 @@ class TestProcessingReactions(unittest.TestCase):
# ------------------------- delete failure: don't stack badges -----------
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_delete_failure_on_failure_outcome_skips_cross_mark(self):
# Removing Typing is best-effort — but if it fails, we must NOT
# additionally add CrossMark, or the UI would show two contradictory
diff --git a/tests/gateway/test_media_spaced_paths_and_history_dedupe.py b/tests/gateway/test_media_spaced_paths_and_history_dedupe.py
index bc214dcdd89..a7bee1abd6d 100644
--- a/tests/gateway/test_media_spaced_paths_and_history_dedupe.py
+++ b/tests/gateway/test_media_spaced_paths_and_history_dedupe.py
@@ -87,6 +87,8 @@ class TestHistoryMediaDedupe:
monkeypatch,
):
monkeypatch.setenv("HOME", str(tmp_path))
+ # On Windows os.path.expanduser("~") reads USERPROFILE, not HOME.
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
history = [
{
"role": "assistant",
@@ -96,7 +98,7 @@ class TestHistoryMediaDedupe:
paths = _collect_history_media_paths(history)
- assert str(tmp_path / "audio cache" / "old.ogg") in paths
+ assert os.path.expanduser("~/audio cache/old.ogg") in paths
def test_empty_history_empty_set(self):
assert _collect_history_media_paths([]) == set()
diff --git a/tests/gateway/test_platform_base.py b/tests/gateway/test_platform_base.py
index 4d12ec90dac..7bddb00edc9 100644
--- a/tests/gateway/test_platform_base.py
+++ b/tests/gateway/test_platform_base.py
@@ -561,6 +561,8 @@ class TestMediaDeliveryPathValidation:
secret = ssh_dir / "id_rsa.txt"
secret.write_bytes(b"-----BEGIN ...") # mtime = now
monkeypatch.setenv("HOME", str(fake_home))
+ # On Windows os.path.expanduser("~") reads USERPROFILE, not HOME.
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
assert BasePlatformAdapter.validate_media_delivery_path(str(secret)) is None
@@ -709,6 +711,8 @@ class TestMediaDeliveryDefaultMode:
doc = workdir / "proposal.docx"
doc.write_bytes(b"PK\x03\x04")
monkeypatch.setenv("HOME", str(fake_home))
+ # On Windows os.path.expanduser("~") reads USERPROFILE, not HOME.
+ monkeypatch.setenv("USERPROFILE", str(fake_home))
# $HOME is itself on the denied-prefix list, mirroring /root.
monkeypatch.setattr(
"gateway.platforms.base._MEDIA_DELIVERY_DENIED_PREFIXES",
@@ -758,6 +762,7 @@ class TestMediaDeliveryDefaultMode:
)
+ @pytest.mark.require_symlinks
def test_root_home_workdir_symlink_to_credential_blocked(self, tmp_path, monkeypatch):
"""A symlink in the workdir pointing at a credential is rejected on its
resolved target, even under the $HOME exception.
@@ -782,6 +787,7 @@ class TestMediaDeliveryDefaultMode:
assert BasePlatformAdapter.validate_media_delivery_path(str(link)) is None
class TestDockerContainerMediaPathTranslation:
"""MEDIA:/workspace (and configured mounts) must resolve to host paths."""
@@ -1321,6 +1327,7 @@ class TestMediaFallbackDoesNotLeakHostPath:
assert self.SENSITIVE_PATH not in sent_text
class TestDockerProfileSandboxMediaTranslation:
"""MEDIA from persistent Docker sandboxes must resolve to the host
directory the profile's container actually bind-mounts (#93950).
diff --git a/tests/gateway/test_post_stream_media_delivery.py b/tests/gateway/test_post_stream_media_delivery.py
index bbb1f7c6fe7..964715fca7a 100644
--- a/tests/gateway/test_post_stream_media_delivery.py
+++ b/tests/gateway/test_post_stream_media_delivery.py
@@ -14,6 +14,7 @@ there. This file pins the asymmetry.
from types import SimpleNamespace
from unittest.mock import AsyncMock
+from urllib.parse import unquote
import pytest
@@ -108,6 +109,6 @@ async def test_explicit_media_tag_still_delivers_post_stream(tmp_path, monkeypat
adapter.send_multiple_images.assert_awaited_once()
images_kwargs = adapter.send_multiple_images.await_args.kwargs
assert images_kwargs["chat_id"] == "C123CHAN"
- assert str(media_file) in images_kwargs["images"][0][0]
+ assert str(media_file) in unquote(images_kwargs["images"][0][0])
diff --git a/tests/gateway/test_replace_child_reap.py b/tests/gateway/test_replace_child_reap.py
index 6409ea2d22d..99d16ca374d 100644
--- a/tests/gateway/test_replace_child_reap.py
+++ b/tests/gateway/test_replace_child_reap.py
@@ -64,6 +64,7 @@ def _fake_psutil(monkeypatch, *, wait_gone=None, wait_alive=None):
return fake
class TestReapGatewayChildren:
def test_reaps_orphaned_children_sigterm_then_wait(self, monkeypatch):
fake = _fake_psutil(monkeypatch)
@@ -87,6 +88,7 @@ class TestReapGatewayChildren:
assert reaped == 1
class TestSnapshotGatewayChildren:
def test_snapshot_walks_descendants_recursively(self, monkeypatch):
fake = _fake_psutil(monkeypatch)
diff --git a/tests/gateway/test_run_progress_topics.py b/tests/gateway/test_run_progress_topics.py
index 583c48d52db..14cbd66c140 100644
--- a/tests/gateway/test_run_progress_topics.py
+++ b/tests/gateway/test_run_progress_topics.py
@@ -6,6 +6,7 @@ import sys
import time
import types
from types import SimpleNamespace
+from urllib.parse import quote
import pytest
@@ -1288,7 +1289,7 @@ async def test_run_agent_queued_message_delivers_first_response_media(monkeypatc
"image_batches": [
{
"chat_id": "discord-thread",
- "images": [(media_path.as_uri(), "")],
+ "images": [(f"file://{quote(str(media_path))}", "")],
"metadata": {"thread_id": "discord-thread"},
}
],
@@ -1329,7 +1330,7 @@ async def test_run_agent_queued_message_delivers_streamed_first_response_media(
assert adapter.image_batches == [
{
"chat_id": "discord-thread",
- "images": [(media_path.as_uri(), "")],
+ "images": [(f"file://{quote(str(media_path))}", "")],
"metadata": {"thread_id": "discord-thread"},
}
]
diff --git a/tests/gateway/test_runtime_footer.py b/tests/gateway/test_runtime_footer.py
index 1ca63a90c61..5f382964466 100644
--- a/tests/gateway/test_runtime_footer.py
+++ b/tests/gateway/test_runtime_footer.py
@@ -36,10 +36,12 @@ def test_model_short_drops_vendor_prefix(model, expected):
def test_home_relative_cwd_collapses_home(tmp_path, monkeypatch):
monkeypatch.setenv("HOME", str(tmp_path))
+ # On Windows os.path.expanduser("~") reads USERPROFILE, not HOME.
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
sub = tmp_path / "projects" / "hermes"
sub.mkdir(parents=True)
result = _home_relative_cwd(str(sub))
- assert result == "~/projects/hermes"
+ assert result == os.path.join("~", "projects", "hermes")
# ---------------------------------------------------------------------------
@@ -48,6 +50,8 @@ def test_home_relative_cwd_collapses_home(tmp_path, monkeypatch):
def test_format_footer_all_fields(monkeypatch, tmp_path):
monkeypatch.setenv("HOME", str(tmp_path))
+ # On Windows os.path.expanduser("~") reads USERPROFILE, not HOME.
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
monkeypatch.setenv("TERMINAL_CWD", str(tmp_path / "projects" / "hermes"))
(tmp_path / "projects" / "hermes").mkdir(parents=True)
out = format_runtime_footer(
@@ -57,7 +61,7 @@ def test_format_footer_all_fields(monkeypatch, tmp_path):
cwd=None, # falls back to TERMINAL_CWD env var
fields=("model", "context_pct", "cwd"),
)
- assert out == "gpt-5.4 · 68% · ~/projects/hermes"
+ assert out == "gpt-5.4 · 68% · " + os.path.join("~", "projects", "hermes")
def test_format_footer_skips_missing_context_length():
@@ -71,7 +75,7 @@ def test_format_footer_skips_missing_context_length():
# context_pct dropped silently; no "?%" artifact
assert "%" not in out
assert "gpt-5.4" in out
- assert "/tmp/wd" in out
+ assert os.path.abspath("/tmp/wd") in out
# ---------------------------------------------------------------------------
@@ -214,6 +218,8 @@ def test_format_footer_latency_zero_renders_sub_second():
def test_format_footer_latency_in_field_order(monkeypatch, tmp_path):
monkeypatch.setenv("HOME", str(tmp_path))
+ # On Windows os.path.expanduser("~") reads USERPROFILE, not HOME.
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
out = format_runtime_footer(
model="openai/gpt-5.4",
context_tokens=68_000,
@@ -256,6 +262,9 @@ def test_build_footer_line_threads_turn_seconds(monkeypatch):
# ---------------------------------------------------------------------------
_LEGACY_DEFAULT_FIELDS = ["model", "context_pct", "cwd"]
+# An absolute path that survives _home_relative_cwd unchanged on every host
+# (os.path.abspath("/var/data") -> "C:\\var\\data" on Windows, "/var/data" on POSIX).
+_VAR_DATA = os.path.abspath("/var/data")
def test_latency_not_in_default_fields():
@@ -275,10 +284,10 @@ def test_resolve_footer_config_default_fields_exclude_latency():
@pytest.mark.parametrize(
"model,tokens,window,cwd,expected",
[
- ("openai/gpt-5.4", 50_247, 1_000_000, "/var/data", "gpt-5.4 · 5% · /var/data"),
- ("claude-opus-4-8", 68_000, 100_000, "/var/data", "claude-opus-4-8 · 68% · /var/data"),
- ("m", 0, None, "/var/data", "m · /var/data"),
- ("", 10, 100, "/var/data", "10% · /var/data"),
+ ("openai/gpt-5.4", 50_247, 1_000_000, _VAR_DATA, f"gpt-5.4 · 5% · {_VAR_DATA}"),
+ ("claude-opus-4-8", 68_000, 100_000, _VAR_DATA, f"claude-opus-4-8 · 68% · {_VAR_DATA}"),
+ ("m", 0, None, _VAR_DATA, f"m · {_VAR_DATA}"),
+ ("", 10, 100, _VAR_DATA, f"10% · {_VAR_DATA}"),
("m", 10, 100, "", "m · 10%"),
],
)
@@ -311,9 +320,9 @@ def test_default_build_footer_line_ignores_turn_seconds(monkeypatch):
model="openai/gpt-5.4",
context_tokens=50_247,
context_length=1_000_000,
- cwd="/var/data",
+ cwd=_VAR_DATA,
)
baseline = build_footer_line(**common)
with_timing = build_footer_line(**common, turn_seconds=125.0)
- assert baseline == "gpt-5.4 · 5% · /var/data"
+ assert baseline == f"gpt-5.4 · 5% · {_VAR_DATA}"
assert with_timing == baseline
diff --git a/tests/gateway/test_scale_to_zero.py b/tests/gateway/test_scale_to_zero.py
index 0f604850c47..d38af57b6e8 100644
--- a/tests/gateway/test_scale_to_zero.py
+++ b/tests/gateway/test_scale_to_zero.py
@@ -150,6 +150,7 @@ def _fake_flaps(tmp_path, status_line, capture):
return sock_path, t
def test_suspend_self_posts_suspend_for_this_machine(tmp_path):
captured: list[bytes] = []
sock_path, t = _fake_flaps(tmp_path, "200 OK", captured)
@@ -164,6 +165,7 @@ def test_suspend_self_posts_suspend_for_this_machine(tmp_path):
assert "Host: flaps\r\n" in request
def test_suspend_self_non_2xx_is_false_not_raise(tmp_path):
captured: list[bytes] = []
sock_path, t = _fake_flaps(tmp_path, "412 Precondition Failed", captured)
@@ -171,6 +173,7 @@ def test_suspend_self_non_2xx_is_false_not_raise(tmp_path):
t.join(timeout=5)
def test_suspend_self_missing_socket_is_false_not_raise(tmp_path):
# Fail-awake: a dead/absent flaps socket must never raise out of the watcher.
assert suspend_self(_FLY_ENV, socket_path=str(tmp_path / "nope.sock")) is False
diff --git a/tests/gateway/test_setup_feishu.py b/tests/gateway/test_setup_feishu.py
index 6ae9fe228e9..70ad2216df1 100644
--- a/tests/gateway/test_setup_feishu.py
+++ b/tests/gateway/test_setup_feishu.py
@@ -7,6 +7,9 @@ Feishu adapter: credentials, connection mode, DM policy, and group policy.
import os
from unittest.mock import patch
+import os as _os
+_SYS_ENV = {k: _os.environ[k] for k in ("SYSTEMROOT", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "HOME") if k in _os.environ}
+
# ---------------------------------------------------------------------------
# Helpers
@@ -211,12 +214,12 @@ class TestSetupFeishuAdapterIntegration:
)
return env
- @patch.dict(os.environ, {}, clear=True)
+ @patch.dict(os.environ, _SYS_ENV, clear=True)
def test_qr_env_produces_valid_adapter_settings(self):
"""QR setup → adapter initializes with websocket mode."""
env = self._make_env_from_setup()
- with patch.dict(os.environ, env, clear=True):
+ with patch.dict(os.environ, {**_SYS_ENV, **env}, clear=True):
from gateway.config import PlatformConfig
from plugins.platforms.feishu.adapter import FeishuAdapter
adapter = FeishuAdapter(PlatformConfig())
diff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.py
index d17e47fa86b..6ca006ca0b9 100644
--- a/tests/gateway/test_status.py
+++ b/tests/gateway/test_status.py
@@ -1059,6 +1059,7 @@ class TestPlannedStopMarker:
class TestReadProcessCmdlinePsFallback:
"""Tests for _read_process_cmdline falling back to ps on non-Linux."""
+ @pytest.mark.linux_only
def test_ps_fallback_when_proc_unavailable(self, monkeypatch):
monkeypatch.setattr(status.Path, "read_bytes", lambda self: (_ for _ in ()).throw(FileNotFoundError))
monkeypatch.setattr(
diff --git a/tests/gateway/test_status_command.py b/tests/gateway/test_status_command.py
index ec179816c76..5f2016e8892 100644
--- a/tests/gateway/test_status_command.py
+++ b/tests/gateway/test_status_command.py
@@ -3,6 +3,7 @@ from hermes_state import AsyncSessionDB, SessionDB
from datetime import datetime
import time
+from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -456,7 +457,13 @@ async def test_profile_command_reports_source_stamped_profile(monkeypatch, tmp_p
result = await runner._handle_profile_command(event)
assert "**Profile:** `milo`" in result
- assert f"**Home:** `{profile_home}`" in result
+ # /profile reports the home via display_hermes_home(), which collapses a
+ # home-relative path to "~/…" (Windows tmp paths live under USERPROFILE).
+ try:
+ expected_home = "~/" + str(profile_home.relative_to(Path.home()))
+ except ValueError:
+ expected_home = str(profile_home)
+ assert f"**Home:** `{expected_home}`" in result
# ── /context command tests ────────────────────────────────────────────────
diff --git a/tests/gateway/test_systemd_notify.py b/tests/gateway/test_systemd_notify.py
index b0dea324cb3..6903f1a0d54 100644
--- a/tests/gateway/test_systemd_notify.py
+++ b/tests/gateway/test_systemd_notify.py
@@ -7,6 +7,8 @@ import socket
import pytest
+pytestmark = pytest.mark.linux_only
+
@pytest.mark.skipif(
not hasattr(socket, "AF_UNIX"), reason="Unix datagram sockets are unavailable"
diff --git a/tests/gateway/test_tts_media_routing.py b/tests/gateway/test_tts_media_routing.py
index fd3ed9ee443..a25def6a1f6 100644
--- a/tests/gateway/test_tts_media_routing.py
+++ b/tests/gateway/test_tts_media_routing.py
@@ -12,6 +12,7 @@ import sys
import types
from types import SimpleNamespace
from unittest.mock import AsyncMock
+from urllib.parse import quote, unquote
import pytest
@@ -240,7 +241,7 @@ async def test_queued_followup_delivery_strips_media_tag_from_text_and_sends_ima
)
adapter.send_multiple_images.assert_awaited_once_with(
chat_id="chat-1",
- images=[(f"file://{media_file.as_posix()}", "")],
+ images=[(f"file://{quote(str(media_file))}", "")],
metadata={"thread_id": "topic-1"},
)
@@ -290,7 +291,7 @@ async def test_queued_followup_delivery_reuses_routing_metadata_for_media(
)
adapter.send_multiple_images.assert_awaited_once_with(
chat_id="chat-1",
- images=[(f"file://{media_file.as_posix()}", "")],
+ images=[(f"file://{quote(str(media_file))}", "")],
metadata=routing_metadata,
)
@@ -578,6 +579,6 @@ async def test_queued_resend_branch_delivers_media_and_preserves_protected_examp
assert first_texts, f"expected queued resend of first response, got: {adapter.sent!r}"
assert f"MEDIA:{media_file}" not in first_texts[0]
assert "`MEDIA:/tmp/example.png`" in first_texts[0]
- assert any(str(media_file) in img["image_path"] for img in adapter.images), (
+ assert any(str(media_file) in unquote(img["image_path"]) for img in adapter.images), (
f"expected native image delivery via queued resend, got: {adapter.images!r}"
)
diff --git a/tests/gateway/test_update_command.py b/tests/gateway/test_update_command.py
index 69916e92296..18cdea9a07e 100644
--- a/tests/gateway/test_update_command.py
+++ b/tests/gateway/test_update_command.py
@@ -138,6 +138,7 @@ class TestHandleUpdateCommand:
@pytest.mark.asyncio
+ @pytest.mark.linux_only
async def test_fallback_when_no_setsid(self, tmp_path):
"""Falls back to start_new_session=True when setsid is not available."""
runner = _make_runner()
diff --git a/tests/gateway/test_update_streaming.py b/tests/gateway/test_update_streaming.py
index 1e1134b7ad0..e4f743c28b8 100644
--- a/tests/gateway/test_update_streaming.py
+++ b/tests/gateway/test_update_streaming.py
@@ -130,6 +130,7 @@ class TestUpdateCommandGatewayFlag:
"""Verify the gateway spawns hermes update --gateway."""
@pytest.mark.asyncio
+ @pytest.mark.linux_only
async def test_spawns_with_gateway_flag(self, tmp_path):
"""The spawned update command includes --gateway and PYTHONUNBUFFERED."""
runner = _make_runner()
diff --git a/tests/hermes_cli/test_agent_import.py b/tests/hermes_cli/test_agent_import.py
index d00ae59f3ad..1f910d37dda 100644
--- a/tests/hermes_cli/test_agent_import.py
+++ b/tests/hermes_cli/test_agent_import.py
@@ -643,6 +643,7 @@ class TestExistingConfigPreserved:
leftovers = [p.name for p in hermes_home.glob(".tmp*")]
assert leftovers == []
+ @pytest.mark.require_symlinks
def test_symlinked_config_stays_a_symlink(
self, claude_tree, hermes_home, tmp_path, config_path):
"""A non-atomic ``write_text`` would follow it; ``os.replace`` would
diff --git a/tests/hermes_cli/test_agent_plugins.py b/tests/hermes_cli/test_agent_plugins.py
index 2c070faa5fa..bed441915eb 100644
--- a/tests/hermes_cli/test_agent_plugins.py
+++ b/tests/hermes_cli/test_agent_plugins.py
@@ -67,11 +67,11 @@ def test_loads_manifest_skill_and_stdio_server(tmp_path: Path) -> None:
assert package.skills[0].root == skill_dir.resolve()
server = package.mcp_servers["worker"]
assert server["command"] == "python"
- assert server["args"] == [str(root.resolve() / "server.py"), "${UNKNOWN}"]
+ assert server["args"] == [str(root.resolve()) + "/server.py", "${UNKNOWN}"]
assert server["cwd"] == str(root.resolve())
assert server["env"]["PLUGIN_ROOT"] == str(root.resolve())
assert server["env"]["PLUGIN_DATA"] == str((tmp_path / "data").resolve())
- assert server["env"]["CACHE"] == str((tmp_path / "data").resolve() / "cache")
+ assert server["env"]["CACHE"] == str((tmp_path / "data").resolve()) + "/cache"
assert (tmp_path / "data").is_dir()
@@ -133,6 +133,7 @@ def test_rejects_invalid_optional_skill_fields(
assert package.skills == ()
def test_symlink_escape_is_isolated_to_component(tmp_path: Path) -> None:
root = tmp_path / "plugin"
root.mkdir()
diff --git a/tests/hermes_cli/test_auth_nous_provider.py b/tests/hermes_cli/test_auth_nous_provider.py
index a1772fd3267..19bb89b576b 100644
--- a/tests/hermes_cli/test_auth_nous_provider.py
+++ b/tests/hermes_cli/test_auth_nous_provider.py
@@ -889,6 +889,7 @@ def test_shared_store_seat_belt_refuses_real_home_under_pytest(monkeypatch):
_nous_shared_store_path()
def test_shared_store_write_and_read_roundtrip(shared_store_env):
"""Write → read must preserve refresh_token + OAuth URLs."""
from hermes_cli.auth import (
diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.py
index e78cfb57f42..dd3030c4143 100644
--- a/tests/hermes_cli/test_backup.py
+++ b/tests/hermes_cli/test_backup.py
@@ -1056,9 +1056,10 @@ class TestProfileRestoration:
from hermes_cli.backup import run_import
run_import(args)
- # Only valid profile should get a wrapper
- assert (wrapper_dir / "valid").exists()
- assert not (wrapper_dir / "empty").exists()
+ # Only valid profile should get a wrapper (Windows uses a .bat shim).
+ suffix = ".bat" if os.name == "nt" else ""
+ assert (wrapper_dir / f"valid{suffix}").exists()
+ assert not (wrapper_dir / f"empty{suffix}").exists()
# ---------------------------------------------------------------------------
@@ -1492,7 +1493,7 @@ class TestQuickSnapshotProjectsKanban:
monkeypatch.setattr(bk, "_safe_copy_db", _spy)
snap_id = create_quick_snapshot(hermes_home=hermes_home)
# The board db was copied via _safe_copy_db (not raw copy).
- assert any(s.endswith("boards/work/kanban.db") for s in called["db"]), called["db"]
+ assert any(s.endswith(os.path.join("boards", "work", "kanban.db")) for s in called["db"]), called["db"]
copy = hermes_home / "state-snapshots" / snap_id / "kanban" / "boards" / "work" / "kanban.db"
rows = sqlite3.connect(str(copy)).execute("SELECT * FROM tasks").fetchall()
assert rows == [("w1", "ship")]
@@ -1822,6 +1823,7 @@ class TestMemoryProviderExternalPaths:
(outside / "leak.json").unlink()
outside.rmdir()
+ @pytest.mark.linux_only
def test_import_restores_external_to_home_relative_location(self, tmp_path, monkeypatch):
"""_external/ members restore to ~/<relpath>, not under HERMES_HOME,
and credential-shaped files get 0600."""
diff --git a/tests/hermes_cli/test_backup_stability.py b/tests/hermes_cli/test_backup_stability.py
index d461d507220..bb88e430ee2 100644
--- a/tests/hermes_cli/test_backup_stability.py
+++ b/tests/hermes_cli/test_backup_stability.py
@@ -53,7 +53,7 @@ def test_atomic_output_keeps_previous_file_after_failure(tmp_path) -> None:
def test_quick_snapshot_is_published_with_manifest(tmp_path, monkeypatch) -> None:
home = tmp_path / ".hermes"
home.mkdir()
- (home / "config.yaml").write_text("model: {}\n", encoding="utf-8")
+ (home / "config.yaml").write_bytes(b"model: {}\n")
published: list[tuple[Path, Path]] = []
from hermes_cli import backup
diff --git a/tests/hermes_cli/test_claw.py b/tests/hermes_cli/test_claw.py
index d9472cd8c85..f12ea500ef2 100644
--- a/tests/hermes_cli/test_claw.py
+++ b/tests/hermes_cli/test_claw.py
@@ -350,6 +350,7 @@ class TestPrintMigrationReport:
class TestDetectOpenclawProcesses:
+ @pytest.mark.linux_only
def test_returns_match_when_pgrep_finds_openclaw(self):
with patch.object(claw_mod, "subprocess") as mock_subprocess:
# systemd check misses, pgrep finds openclaw
diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.py
index 13a2beae7ad..6ede05145a5 100644
--- a/tests/hermes_cli/test_cmd_update.py
+++ b/tests/hermes_cli/test_cmd_update.py
@@ -10,6 +10,16 @@ import pytest
from hermes_cli.main import cmd_update, PROJECT_ROOT
[email protected](autouse=True)
+def _isolate_venv_holders(monkeypatch):
+ """The update flow's venv-holder guard sees the live gateway processes on
+ a dev machine and aborts with SystemExit 2 before reaching the branch
+ logic under test. Isolate it so the test exercises the intended path."""
+ import hermes_cli.main as cli_main
+
+ monkeypatch.setattr(cli_main, "_detect_venv_python_processes", lambda: [])
+
+
def _make_run_side_effect(branch="main", verify_ok=True, commit_count="0"):
"""Build a side_effect function for subprocess.run that simulates git commands."""
diff --git a/tests/hermes_cli/test_config.py b/tests/hermes_cli/test_config.py
index 968649e58a1..3c8120f92d0 100644
--- a/tests/hermes_cli/test_config.py
+++ b/tests/hermes_cli/test_config.py
@@ -35,21 +35,11 @@ from hermes_cli.config import (
class TestGetHermesHome:
def test_default_path(self):
+ from hermes_constants import _get_platform_default_hermes_home
with patch.dict(os.environ, {}, clear=False):
os.environ.pop("HERMES_HOME", None)
home = get_hermes_home()
- if sys.platform == "win32":
- # Windows default is %LOCALAPPDATA%\hermes — see
- # hermes_constants._get_platform_default_hermes_home.
- local_appdata = os.environ.get("LOCALAPPDATA", "").strip()
- base = (
- Path(local_appdata)
- if local_appdata
- else Path.home() / "AppData" / "Local"
- )
- assert home == base / "hermes"
- else:
- assert home == Path.home() / ".hermes"
+ assert home == _get_platform_default_hermes_home()
class TestEnsureHermesHome:
diff --git a/tests/hermes_cli/test_container_boot.py b/tests/hermes_cli/test_container_boot.py
index 5838ffdb451..543cc2bb3c6 100644
--- a/tests/hermes_cli/test_container_boot.py
+++ b/tests/hermes_cli/test_container_boot.py
@@ -19,6 +19,8 @@ from hermes_cli.container_boot import (
reconcile_profile_gateways,
)
+pytestmark = pytest.mark.linux_only
+
# ---------------------------------------------------------------------------
# Fixtures + helpers
diff --git a/tests/hermes_cli/test_dashboard_spawn_executable.py b/tests/hermes_cli/test_dashboard_spawn_executable.py
index de1bae8485f..d6921e9b19c 100644
--- a/tests/hermes_cli/test_dashboard_spawn_executable.py
+++ b/tests/hermes_cli/test_dashboard_spawn_executable.py
@@ -14,6 +14,8 @@ import sys
from pathlib import Path
from unittest.mock import patch
+import pytest
+
import hermes_cli.web_server as web_server
@@ -68,6 +70,7 @@ class TestDashboardSpawnExecutable:
):
assert web_server._dashboard_spawn_executable() == str(base_interp)
+ @pytest.mark.require_symlinks
def test_venv_symlink_to_base_is_still_preferred_unresolved(self, tmp_path):
"""The Linux-standard layout: venv/bin/python is a SYMLINK to the
base interpreter. The chooser must return the UNRESOLVED venv path —
diff --git a/tests/hermes_cli/test_debug.py b/tests/hermes_cli/test_debug.py
index 2a3d0206b14..220156246ff 100644
--- a/tests/hermes_cli/test_debug.py
+++ b/tests/hermes_cli/test_debug.py
@@ -134,7 +134,7 @@ class TestCaptureLogSnapshot:
# backward-reading loop so the truncation path actually fires.
line = "A" * 99 + "\n" # 100 bytes per line
num_lines = 200 # 20000 bytes
- (hermes_home / "logs" / "agent.log").write_text(line * num_lines)
+ (hermes_home / "logs" / "agent.log").write_bytes((line * num_lines).encode("utf-8"))
# max_bytes = 1000 = 100 * 10 → cut at byte 20000 - 1000 = 19000,
# and byte 19000 - 1 is '\n'. Boundary hit → keep all 10 lines.
diff --git a/tests/hermes_cli/test_doctor_journal_modes.py b/tests/hermes_cli/test_doctor_journal_modes.py
index 55828de6313..15c32bf471e 100644
--- a/tests/hermes_cli/test_doctor_journal_modes.py
+++ b/tests/hermes_cli/test_doctor_journal_modes.py
@@ -142,7 +142,7 @@ class TestReadJournalMode:
holder.close()
@pytest.mark.skipif(os.name == "nt", reason="chmod is a no-op on Windows")
- @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores file permissions")
+ @pytest.mark.skipif(hasattr(os, "geteuid") and os.geteuid() == 0, reason="root ignores file permissions")
def test_read_only_directory_is_still_readable(self, tmp_path):
db = tmp_path / "state.db"
_make_db(db, journal_mode="WAL")
@@ -277,6 +277,7 @@ class TestLiveConnectionSafety:
class TestUnreadableReason:
+ @pytest.mark.linux_only
def test_missing_file_keeps_the_os_error_text(self, tmp_path):
reason = doctor._unreadable_reason(tmp_path / "gone.db")
@@ -363,7 +364,8 @@ class TestReportDatabaseJournalModes:
assert "state.db is in WAL mode" in out
assert "projects.db: rollback journal mode" in out
assert "kanban.db: rollback journal mode" in out
- assert "kanban/boards/myboard/kanban.db is in WAL mode" in out
+ board_rel = os.path.join("kanban", "boards", "myboard", "kanban.db")
+ assert f"{board_rel} is in WAL mode" in out
def test_missing_databases_are_skipped(self, tmp_path, capsys):
doctor._report_database_journal_modes(tmp_path, VULNERABLE)
@@ -387,7 +389,7 @@ class TestReportDatabaseJournalModes:
assert "state.db: rollback journal mode" in out
@pytest.mark.skipif(os.name == "nt", reason="chmod is a no-op on Windows")
- @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores file permissions")
+ @pytest.mark.skipif(hasattr(os, "geteuid") and os.geteuid() == 0, reason="root ignores file permissions")
def test_unreadable_database_does_not_crash(self, tmp_path, capsys):
db = tmp_path / "state.db"
_make_db(db)
diff --git a/tests/hermes_cli/test_ensure_acp_launcher.py b/tests/hermes_cli/test_ensure_acp_launcher.py
index fac777858d4..7e61965871a 100644
--- a/tests/hermes_cli/test_ensure_acp_launcher.py
+++ b/tests/hermes_cli/test_ensure_acp_launcher.py
@@ -31,6 +31,7 @@ def fake_home(tmp_path, monkeypatch):
def test_does_not_follow_symlink_into_venv(fake_home, tmp_path):
"""#21454 failure mode: never write through a symlinked hermes-acp."""
(fake_home / "hermes").write_text("#!/bin/sh\n", encoding="utf-8")
diff --git a/tests/hermes_cli/test_ensure_hermes_home_uid_34107.py b/tests/hermes_cli/test_ensure_hermes_home_uid_34107.py
index ceb9bfb382a..367bf39bc99 100644
--- a/tests/hermes_cli/test_ensure_hermes_home_uid_34107.py
+++ b/tests/hermes_cli/test_ensure_hermes_home_uid_34107.py
@@ -27,6 +27,7 @@ import pytest
class TestResolveHermesUidGid:
+ @pytest.mark.linux_only
def test_returns_parsed_values_when_both_set(self, monkeypatch):
monkeypatch.setenv("HERMES_UID", "1000")
monkeypatch.setenv("HERMES_GID", "911")
@@ -55,6 +56,7 @@ class TestResolveHermesUidGid:
# ---------------------------------------------------------------------------
class TestChownToHermesUid:
def test_calls_os_chown_when_both_set(self, tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_UID", "1000")
diff --git a/tests/hermes_cli/test_gateway_foreign_xdg_runtime.py b/tests/hermes_cli/test_gateway_foreign_xdg_runtime.py
index 7aaf83e3b48..e7c2c71cf91 100644
--- a/tests/hermes_cli/test_gateway_foreign_xdg_runtime.py
+++ b/tests/hermes_cli/test_gateway_foreign_xdg_runtime.py
@@ -16,6 +16,8 @@ import pytest
import hermes_cli.gateway as gateway_cli
+pytestmark = pytest.mark.linux_only
+
def _eacces(self):
raise PermissionError(13, "Permission denied", str(self))
diff --git a/tests/hermes_cli/test_gateway_linger.py b/tests/hermes_cli/test_gateway_linger.py
index ac0efcfcd8f..44b653298c4 100644
--- a/tests/hermes_cli/test_gateway_linger.py
+++ b/tests/hermes_cli/test_gateway_linger.py
@@ -2,8 +2,12 @@
from types import SimpleNamespace
+import pytest
+
import hermes_cli.gateway as gateway
+pytestmark = pytest.mark.linux_only
+
class TestEnsureLingerEnabled:
def test_linger_already_enabled_via_file(self, monkeypatch, capsys):
diff --git a/tests/hermes_cli/test_gateway_proc_fallback.py b/tests/hermes_cli/test_gateway_proc_fallback.py
index b11fecad1f3..a8aa531ada0 100644
--- a/tests/hermes_cli/test_gateway_proc_fallback.py
+++ b/tests/hermes_cli/test_gateway_proc_fallback.py
@@ -13,6 +13,8 @@ import pytest
import hermes_cli.gateway as gateway_mod
+pytestmark = pytest.mark.linux_only
+
# ---------------------------------------------------------------------------
# Helpers
diff --git a/tests/hermes_cli/test_gateway_restart_loop.py b/tests/hermes_cli/test_gateway_restart_loop.py
index a005b9c2e8c..ff27703a193 100644
--- a/tests/hermes_cli/test_gateway_restart_loop.py
+++ b/tests/hermes_cli/test_gateway_restart_loop.py
@@ -556,6 +556,7 @@ class TestTerminalToolGatewayLifecycleGuard:
assert result["exit_code"] == 1
assert "Blocked" in result["error"]
+ @pytest.mark.linux_only
def test_blocks_lifecycle_command_hidden_in_referenced_script(
self, monkeypatch, tmp_path
):
@@ -665,6 +666,7 @@ class TestTerminalToolGatewayLifecycleGuard:
assert result["exit_code"] == 0
assert calls == ["hermes gateway restart"]
+ @pytest.mark.linux_only
def test_blocks_launchctl_submit_hidden_in_referenced_script(
self, monkeypatch, tmp_path
):
@@ -700,6 +702,7 @@ class TestTerminalToolGatewayLifecycleGuard:
assert result["exit_code"] == 1
assert "referenced script" in result["error"]
+ @pytest.mark.linux_only
def test_blocks_executable_shebang_script(self, monkeypatch, tmp_path):
import tools.terminal_tool as tt
@@ -723,6 +726,7 @@ class TestTerminalToolGatewayLifecycleGuard:
assert result["exit_code"] == 1
assert "KeepAlive" in result["error"]
+ @pytest.mark.linux_only
def test_shell_option_with_value_still_scans_script(self, monkeypatch, tmp_path):
import tools.terminal_tool as tt
@@ -756,6 +760,7 @@ class TestTerminalToolGatewayLifecycleGuard:
assert result["exit_code"] == 1
+ @pytest.mark.linux_only
def test_nested_wrapper_script_is_scanned(self, monkeypatch, tmp_path):
import tools.terminal_tool as tt
@@ -776,6 +781,7 @@ class TestTerminalToolGatewayLifecycleGuard:
assert result["exit_code"] == 1
+ @pytest.mark.linux_only
def test_non_regular_referenced_script_fails_closed(self, monkeypatch, tmp_path):
import tools.terminal_tool as tt
@@ -809,6 +815,7 @@ class TestTerminalToolGatewayLifecycleGuard:
assert result["exit_code"] == 0
assert calls == [command]
+ @pytest.mark.linux_only
def test_safe_referenced_script_passes_through(self, monkeypatch, tmp_path):
import tools.terminal_tool as tt
@@ -861,6 +868,7 @@ class TestTerminalToolGatewayLifecycleGuard:
class TestLifecycleGuardModule:
"""Direct tests for cron.lifecycle_guard.check_gateway_lifecycle."""
+ @pytest.mark.linux_only
def test_dot_operator_sourced_script_is_scanned(self, tmp_path):
"""`. ./script.sh` must reach the referenced-script scan.
@@ -879,6 +887,7 @@ class TestLifecycleGuardModule:
is True
)
+ @pytest.mark.linux_only
def test_nul_padded_script_is_still_scanned(self, tmp_path):
"""A NUL byte in a *text* script must not disable the scan.
@@ -897,6 +906,7 @@ class TestLifecycleGuardModule:
is True
)
+ @pytest.mark.linux_only
def test_source_builtin_sourced_script_is_scanned(self, tmp_path):
"""The `source` spelling must stay blocked (it already was)."""
from cron.lifecycle_guard import (
@@ -922,6 +932,7 @@ class TestLifecycleGuardModule:
is False
)
+ @pytest.mark.linux_only
def test_nul_padded_script_without_shebang_is_scanned(self, tmp_path):
"""Same bypass without a shebang — bash still runs it, so still scan.
@@ -972,6 +983,7 @@ class TestLifecycleGuardModule:
is False
)
+ @pytest.mark.linux_only
def test_oversized_nul_bearing_text_still_fails_closed(self, tmp_path):
"""An oversized *text* script must keep failing closed.
@@ -1193,6 +1205,7 @@ class TestLifecycleGuardModule:
with pytest.raises(GatewayLifecycleBlocked):
check_gateway_lifecycle("daily ops", str(script))
+ @pytest.mark.require_symlinks
def test_cloud_backed_symlink_fails_closed_without_opening_target(
self, tmp_path, monkeypatch
):
@@ -1235,6 +1248,7 @@ class TestLifecycleGuardModule:
str(launcher)
) is True
+ @pytest.mark.linux_only
def test_third_party_cloudstorage_path_fails_closed_without_opening(
self, tmp_path, monkeypatch
):
@@ -1464,6 +1478,7 @@ class TestLifecycleGuardModule:
# Defense 2 (chokepoint): cron.jobs.create_job blocks the AGENT model-tool path
# ---------------------------------------------------------------------------
class TestDotSourceIsScannedLikeSource:
"""`.` and `source` are the same POSIX builtin and must scan alike.
@@ -1522,6 +1537,7 @@ class TestDotSourceIsScannedLikeSource:
assert self._scan(f". {clean}", cwd=str(tmp_path)) is False
class TestTransparentWrapperPrefixes:
"""`sudo`/`env`/`nohup`/... exec their argument tail, so the command that
actually runs sits further right. Reading only the first token made the
@@ -1841,6 +1857,7 @@ class TestTerminalToolGatewayLifecycleGuardRemote:
lambda: inside_gateway,
)
+ @pytest.mark.linux_only
def test_remote_backend_script_read_uses_env_execute(self, monkeypatch, tmp_path):
import tools.terminal_tool as tt
diff --git a/tests/hermes_cli/test_goal_gates.py b/tests/hermes_cli/test_goal_gates.py
index 4dfc7947878..f139de9e74d 100644
--- a/tests/hermes_cli/test_goal_gates.py
+++ b/tests/hermes_cli/test_goal_gates.py
@@ -64,7 +64,10 @@ def test_run_gate_pass():
assert "hello" in out
def test_run_gate_fail_captures_output():
+ # POSIX shell syntax (`>&2`, `;`, `exit`) — cmd.exe (shell=True on Windows)
+ # doesn't parse it, so the gate "passes" instead of failing.
passed, code, out = run_gate(GoalGate(command="echo broken >&2; exit 3"))
assert passed is False
assert code == 3
diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.py
index a3480f96d10..b5cef350212 100644
--- a/tests/hermes_cli/test_gui_command.py
+++ b/tests/hermes_cli/test_gui_command.py
@@ -99,7 +99,10 @@ def _make_packaged_executable(root: Path, monkeypatch) -> Path:
return exe
def test_gui_installs_packages_and_launches_desktop_app(tmp_path, monkeypatch):
+ # Exercises the npm-pack → packaged-exe launch path; Windows desktop is
+ # MSIX-only (Electron autoUpdater) and takes a different launch route.
root = _make_desktop_tree(tmp_path)
desktop_dir = root / "apps" / "desktop"
monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
@@ -1036,6 +1039,7 @@ def test_desktop_launch_options_ozone_hint_defaults_auto():
assert cli_main._desktop_launch_options()[3] == "auto"
def test_gui_bridges_ozone_hint_to_launch_env(tmp_path, monkeypatch):
"""COSMIC HUD: ``desktop.ozone_platform_hint: x11`` sets
``ELECTRON_OZONE_PLATFORM_HINT`` on the launched Electron process."""
diff --git a/tests/hermes_cli/test_hooks_cli.py b/tests/hermes_cli/test_hooks_cli.py
index 0ffb6ad0478..11d8ebf6b4d 100644
--- a/tests/hermes_cli/test_hooks_cli.py
+++ b/tests/hermes_cli/test_hooks_cli.py
@@ -79,6 +79,7 @@ class TestHooksList:
# ── test ──────────────────────────────────────────────────────────────────
class TestHooksTest:
def test_synthetic_payload_matches_production_shape(self, tmp_path):
"""`hermes hooks test` must feed the script stdin in the same
diff --git a/tests/hermes_cli/test_install_cua_driver.py b/tests/hermes_cli/test_install_cua_driver.py
index 9740fc5c9fe..e67195d7d3e 100644
--- a/tests/hermes_cli/test_install_cua_driver.py
+++ b/tests/hermes_cli/test_install_cua_driver.py
@@ -144,6 +144,7 @@ class TestInstallCuaDriverUpgrade:
assert tools_config.install_cua_driver(upgrade=False) is False
warn.assert_called()
+ @pytest.mark.linux_only
def test_upgrade_with_binary_present_runs_installer(self):
from hermes_cli import tools_config
@@ -163,6 +164,7 @@ class TestInstallCuaDriverUpgrade:
kwargs = runner.call_args.kwargs
assert kwargs.get("verbose") is False
+ @pytest.mark.linux_only
def test_upgrade_without_binary_runs_installer(self):
from hermes_cli import tools_config
@@ -279,6 +281,7 @@ class TestInstallCuaDriverUpgrade:
assert popen.call_args.kwargs["stdin"] is subprocess.DEVNULL
fake_proc.communicate.assert_called_once_with(timeout=120)
+ @pytest.mark.linux_only
def test_upgrade_can_suppress_installer_progress(self):
from hermes_cli import tools_config
@@ -456,6 +459,7 @@ class TestInstallCuaDriverUpgrade:
runner.assert_not_called()
+ @pytest.mark.linux_only
def test_non_upgrade_without_binary_runs_installer(self):
from hermes_cli import tools_config
@@ -714,6 +718,7 @@ class TestUpdateCheckTimeoutDefaults:
"""
assert self._captured_timeout() == 25.0
+ @pytest.mark.linux_only
def test_posix_default_unchanged(self):
# Unmarked: the POSIX default is what this (Linux) host already picks,
# so no platform faking is involved.
diff --git a/tests/hermes_cli/test_kanban_boards.py b/tests/hermes_cli/test_kanban_boards.py
index 6fa004879fe..d3465ae396c 100644
--- a/tests/hermes_cli/test_kanban_boards.py
+++ b/tests/hermes_cli/test_kanban_boards.py
@@ -152,8 +152,11 @@ class TestBoardCRUD:
# contains the resolved path, the CREATE TABLE pass is skipped and
# downstream readers hit `no such table: task_events`.
kb.create_board("recycle")
- # First connect populates _INITIALIZED_PATHS for this DB.
- with kb.connect(board="recycle") as conn:
+ # First connect populates _INITIALIZED_PATHS for this DB. Use
+ # connect_closing: `with connect() as conn` does NOT close the fd, and
+ # on Windows an open connection locks kanban.db so remove_board's
+ # rename below fails with WinError 5/32.
+ with kb.connect_closing(board="recycle") as conn:
kb.create_task(conn, title="t1", assignee="dev")
db_path = kb.board_dir("recycle") / "kanban.db"
assert str(db_path.resolve()) in kb._INITIALIZED_PATHS
@@ -165,7 +168,7 @@ class TestBoardCRUD:
# Simulate the event-stream poll: re-open the same slug. connect()
# recreates the directory + empty .db; the schema must be re-applied.
- with kb.connect(board="recycle") as conn:
+ with kb.connect_closing(board="recycle") as conn:
tables = {
row[0]
for row in conn.execute(
diff --git a/tests/hermes_cli/test_kanban_core_functionality.py b/tests/hermes_cli/test_kanban_core_functionality.py
index 0a47445ec11..9428a79ff1f 100644
--- a/tests/hermes_cli/test_kanban_core_functionality.py
+++ b/tests/hermes_cli/test_kanban_core_functionality.py
@@ -1320,6 +1320,7 @@ def _drive_nonzero_crash(conn, tid, fake_pid):
return _drive_worker_exit(conn, tid, fake_pid, 256)
def test_protocol_violation_budget_not_consumed_by_other_failures(kanban_home):
"""Mixed failure kinds must not consume the violation retry budget.
diff --git a/tests/hermes_cli/test_kanban_db.py b/tests/hermes_cli/test_kanban_db.py
index e4dce15bd86..5c0638c3254 100644
--- a/tests/hermes_cli/test_kanban_db.py
+++ b/tests/hermes_cli/test_kanban_db.py
@@ -264,6 +264,7 @@ def _exited_status(code: int) -> int:
def test_rate_limit_exit_requeues_without_counting_failure(
kanban_home, monkeypatch,
):
@@ -566,7 +567,7 @@ def test_worktree_workspace_explicit_target_materializes_linked_worktree(kanban_
capture_output=True,
text=True,
).stdout
- assert f"worktree {target}" in listed
+ assert f"worktree {target.as_posix()}" in listed
assert f"branch refs/heads/{branch}" in listed
@@ -1189,6 +1190,9 @@ def test_resolve_hermes_argv_falls_back_to_module_form_when_no_path_shim(monkeyp
monkeypatch.delenv("HERMES_BIN", raising=False)
monkeypatch.setattr(shutil, "which", lambda name: None)
+ # On Windows _resolve_hermes_argv() uses _safe_which_no_cwd() instead of
+ # shutil.which — mock that too so the "no shim" path is the one tested.
+ monkeypatch.setattr(kb, "_safe_which_no_cwd", lambda name: None)
argv = kb._resolve_hermes_argv()
assert argv == [sys.executable, "-m", "hermes_cli.main"]
diff --git a/tests/hermes_cli/test_linux_desktop_entry.py b/tests/hermes_cli/test_linux_desktop_entry.py
index 8d8c246af52..8c053153e99 100644
--- a/tests/hermes_cli/test_linux_desktop_entry.py
+++ b/tests/hermes_cli/test_linux_desktop_entry.py
@@ -40,6 +40,7 @@ def _parse(entry_text: str) -> dict:
return values
def test_install_writes_entry_with_absolute_exec_and_icon(
tmp_path, xdg_home, monkeypatch
):
@@ -129,6 +130,7 @@ def test_install_icon_copy_failure_falls_back_to_absolute(
assert values["Terminal"] == "false"
def test_installed_entry_is_executable(tmp_path, xdg_home, monkeypatch):
root = _make_project(tmp_path)
monkeypatch.setattr(
@@ -141,6 +143,7 @@ def test_installed_entry_is_executable(tmp_path, xdg_home, monkeypatch):
assert entry.stat().st_mode & stat.S_IXUSR
def test_exec_falls_back_to_interpreter_module(tmp_path, xdg_home, monkeypatch):
root = _make_project(tmp_path)
monkeypatch.setattr("hermes_cli.relaunch.resolve_hermes_bin", lambda: None)
@@ -158,6 +161,7 @@ def test_exec_falls_back_to_interpreter_module(tmp_path, xdg_home, monkeypatch):
# interpreter when the DE spawns the .desktop entry → ModuleNotFoundError,
# silent (Terminal=false). The Exec line must prefix sys.executable for any
# resolved bin that is a python script escaping the running venv.
def test_exec_prefixes_interpreter_for_env_shebang_python_script(
tmp_path, xdg_home, monkeypatch
):
@@ -184,6 +188,7 @@ def test_exec_prefixes_interpreter_for_env_shebang_python_script(
assert exec_line.endswith("desktop")
def test_exec_leaves_shell_wrapper_launchers_alone(tmp_path, xdg_home, monkeypatch):
root = _make_project(tmp_path)
hermes_bin = tmp_path / "bin" / "hermes"
@@ -204,6 +209,7 @@ def test_exec_leaves_shell_wrapper_launchers_alone(tmp_path, xdg_home, monkeypat
assert exec_line == f"{hermes_bin} desktop"
def test_exec_leaves_venv_shebang_scripts_alone(tmp_path, xdg_home, monkeypatch):
import sys
@@ -626,6 +632,7 @@ def test_run_quiet_swallows_missing_binary(tmp_path):
assert lde._run_quiet([str(tmp_path / "definitely-not-a-binary")]) is False
def test_exec_arg_quoting_handles_spaces(tmp_path, xdg_home, monkeypatch):
root = _make_project(tmp_path)
spaced = tmp_path / "my apps" / "hermes"
diff --git a/tests/hermes_cli/test_managed_uv.py b/tests/hermes_cli/test_managed_uv.py
index a81fd52501d..7bbb7e12dbf 100644
--- a/tests/hermes_cli/test_managed_uv.py
+++ b/tests/hermes_cli/test_managed_uv.py
@@ -157,6 +157,7 @@ class TestMacOSManagedPythonSigning:
class TestResolveUv:
+ @pytest.mark.linux_only
def test_existing_executable(self, tmp_path):
_make_executable(tmp_path / "bin" / "uv")
with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path):
@@ -181,6 +182,7 @@ class TestResolveUv:
class TestEnsureUv:
+ @pytest.mark.linux_only
def test_installs_if_missing(self, tmp_path):
with patch("hermes_cli.managed_uv.get_hermes_home", return_value=tmp_path), \
patch("hermes_cli.managed_uv.repair_vulnerable_runtime", return_value=_RRR("not-applicable")), \
@@ -195,6 +197,7 @@ class TestEnsureUv:
assert path == str(tmp_path / "bin" / "uv")
mock_install.assert_called_once()
+ @pytest.mark.linux_only
def test_install_reports_runtime_repair_to_observer(self, tmp_path):
from hermes_cli.managed_uv import (
RuntimeRepairResult,
@@ -329,6 +332,7 @@ class TestUpdateManagedUv:
+ @pytest.mark.linux_only
def test_fresh_stamp_skips_network_self_update_but_not_repair(self, tmp_path, monkeypatch):
"""A recent success stamp must skip `uv self update` entirely while the
vulnerable-runtime repair probe still runs (CVE repair is never gated)."""
@@ -355,6 +359,7 @@ class TestUpdateManagedUv:
mock_repair.assert_called_once_with(str(uv))
+ @pytest.mark.linux_only
def test_stale_stamp_runs_self_update_and_refreshes_stamp(self, tmp_path):
import os as _os
import time as _time
@@ -674,6 +679,7 @@ class TestRuntimeCutover:
# ---------------------------------------------------------------------------
class TestInstallUvInternals:
+ @pytest.mark.linux_only
def test_posix_sets_uv_unmanaged_install(self, tmp_path):
target = tmp_path / "bin" / "uv"
with patch("hermes_cli.managed_uv._install_uv_posix") as mock_posix:
@@ -1258,6 +1264,7 @@ class TestDefaultLiveVenv:
(bin_dir / "python").write_text("py", encoding="utf-8")
return root
+ @pytest.mark.linux_only
def test_dot_venv_only_is_targeted(self, tmp_path):
from hermes_cli.managed_uv import _default_live_venv
diff --git a/tests/hermes_cli/test_migrate_xai.py b/tests/hermes_cli/test_migrate_xai.py
index 74099b2969f..420210f6bde 100644
--- a/tests/hermes_cli/test_migrate_xai.py
+++ b/tests/hermes_cli/test_migrate_xai.py
@@ -248,6 +248,7 @@ class TestCrashDurability:
# ...and the aborted write must not leave a temp file behind.
assert list(trap_config.parent.glob("*.tmp")) == []
+ @pytest.mark.require_symlinks
def test_symlinked_config_is_replaced_in_place(self, tmp_path: Path):
"""A config.yaml symlinked into a dotfiles repo must stay a symlink."""
real_dir = tmp_path / "dotfiles"
diff --git a/tests/hermes_cli/test_nous_subscription.py b/tests/hermes_cli/test_nous_subscription.py
index d9f71a9af16..f0cc91139aa 100644
--- a/tests/hermes_cli/test_nous_subscription.py
+++ b/tests/hermes_cli/test_nous_subscription.py
@@ -3,6 +3,8 @@
import shutil
import sys
+import pytest
+
from hermes_cli.nous_account import NousPortalAccountInfo, NousToolAccessInfo
from hermes_cli import nous_subscription as ns
@@ -477,6 +479,7 @@ def test_has_agent_browser_import_failure_falls_back_to_path_check(monkeypatch):
assert ns._has_agent_browser() is True
def test_has_agent_browser_import_failure_falls_back_to_hermes_managed_node_path(
monkeypatch, tmp_path
):
diff --git a/tests/hermes_cli/test_npm_engine.py b/tests/hermes_cli/test_npm_engine.py
index 56e6e7e4264..1464b7436a5 100644
--- a/tests/hermes_cli/test_npm_engine.py
+++ b/tests/hermes_cli/test_npm_engine.py
@@ -85,6 +85,7 @@ class TestDetection:
assert required_npm_range(broken) is None
class TestManagedDetection:
"""The upgrade must fire for every spelling of the managed npm, and for
no other npm — this is the boundary between "Hermes fixes it" and "the
diff --git a/tests/hermes_cli/test_oneshot_surrogate.py b/tests/hermes_cli/test_oneshot_surrogate.py
index 9039690a840..1d5eb02c43f 100644
--- a/tests/hermes_cli/test_oneshot_surrogate.py
+++ b/tests/hermes_cli/test_oneshot_surrogate.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import os
import subprocess
import sys
import textwrap
@@ -35,5 +36,5 @@ def test_oneshot_replaces_lone_surrogate_and_exits_zero():
# U+FFFD as UTF-8; no raw surrogate bytes
assert "\ufffd".encode("utf-8") in result.stdout
assert b"answer " in result.stdout
- assert b" here\n" in result.stdout
+ assert (" here" + os.linesep).encode("ascii") in result.stdout
assert b"Traceback" not in result.stderr
diff --git a/tests/hermes_cli/test_plugin_install_ref.py b/tests/hermes_cli/test_plugin_install_ref.py
index f7f1dbec1e3..0fcfbfb73e4 100644
--- a/tests/hermes_cli/test_plugin_install_ref.py
+++ b/tests/hermes_cli/test_plugin_install_ref.py
@@ -350,7 +350,7 @@ def test_metadata_write_failure_rolls_back_removal(monkeypatch, tmp_path):
def test_reinstall_after_manual_directory_removal_retains_pin(monkeypatch, tmp_path):
- from hermes_cli.plugins_cmd import _install_plugin_core
+ from hermes_cli.plugins_cmd import _install_plugin_core, _rmtree_force
repo, old_sha, _new_sha = _plugin_repo(tmp_path)
home = tmp_path / "home"
@@ -358,7 +358,7 @@ def test_reinstall_after_manual_directory_removal_retains_pin(monkeypatch, tmp_p
target, _manifest, _name = _install_plugin_core(
repo.as_uri(), force=False, ref=old_sha
)
- shutil.rmtree(target)
+ _rmtree_force(target)
target, _manifest, _name = _install_plugin_core(repo.as_uri(), force=False)
diff --git a/tests/hermes_cli/test_plugins_cmd.py b/tests/hermes_cli/test_plugins_cmd.py
index 4002698b0e7..32742090025 100644
--- a/tests/hermes_cli/test_plugins_cmd.py
+++ b/tests/hermes_cli/test_plugins_cmd.py
@@ -103,6 +103,7 @@ class TestResolveSubdirWithin:
+ @pytest.mark.require_symlinks
def test_rejects_symlink_escape(self, tmp_path):
clone = tmp_path / "clone"
clone.mkdir()
diff --git a/tests/hermes_cli/test_profile_export_credentials.py b/tests/hermes_cli/test_profile_export_credentials.py
index 0ab6a4e23be..3b6524cac75 100644
--- a/tests/hermes_cli/test_profile_export_credentials.py
+++ b/tests/hermes_cli/test_profile_export_credentials.py
@@ -11,6 +11,8 @@ The live profile on disk must stay untouched.
import tarfile
+import pytest
+
from hermes_cli.profiles import export_profile, _DEFAULT_EXPORT_EXCLUDE_ROOT
# Long enough to match agent.redact prefix patterns (sk- + 10+ chars).
@@ -107,6 +109,7 @@ class TestExportSecretScrub:
assert _LEAKED_KEY in skill.read_text()
assert _LEAKED_KEY in memory.read_text()
+ @pytest.mark.require_symlinks
def test_export_redacts_through_symlink_without_touching_source(
self, tmp_path, monkeypatch
):
diff --git a/tests/hermes_cli/test_profiles.py b/tests/hermes_cli/test_profiles.py
index ac5e1e27948..bdabebd57b9 100644
--- a/tests/hermes_cli/test_profiles.py
+++ b/tests/hermes_cli/test_profiles.py
@@ -115,6 +115,7 @@ class TestCreateProfile:
"""Tests for create_profile()."""
+ @pytest.mark.linux_only
def test_seeds_placeholder_env_file(self, profile_env):
"""Fresh profiles get their own .env (owner-only) so channel/env
writes are profile-scoped from day one instead of falling through
@@ -269,6 +270,7 @@ class TestBackfillProfileEnvs:
gives pre-#44792 profiles (created before .env seeding) their own
.env, copied from the default install so credentials don't break."""
+ @pytest.mark.linux_only
def test_copies_default_env_into_envless_profiles(self, profile_env):
import stat
tmp_path = profile_env
@@ -622,6 +624,7 @@ class TestAliasCollision:
class TestWrapperScript:
"""Tests for create_wrapper_script() and remove_wrapper_script()."""
+ @pytest.mark.linux_only
def test_creates_sh_on_posix(self, profile_env, monkeypatch):
monkeypatch.setattr("hermes_cli.profiles.shutil.which", lambda name: "/opt/hermes/bin/hermes")
from hermes_cli.profiles import create_wrapper_script
@@ -696,6 +699,7 @@ class TestFindAliasForProfile:
assert find_alias_for_profile("steve") is None
+ @pytest.mark.linux_only
def test_list_profiles_surfaces_custom_alias(self, profile_env):
from hermes_cli.profiles import (
create_profile,
@@ -800,6 +804,7 @@ class TestExportImport:
assert "default/memories/MEMORY.md" in names
+ @pytest.mark.require_symlinks
def test_export_default_handles_broken_symlinks(self, profile_env, tmp_path):
"""Broken symlinks inside allowed artifacts are preserved, not crashed (#58394).
@@ -977,6 +982,7 @@ class TestWriteProfileMetaDurability:
assert "🧙" in raw
assert profiles.read_profile_meta(profile_dir)["description"] == "Code wizard 🧙 ✨"
+ @pytest.mark.require_symlinks
def test_symlinked_profile_yaml_survives_the_write(self, tmp_path):
"""Guard on the conversion, not a behavior change.
diff --git a/tests/hermes_cli/test_projects_db.py b/tests/hermes_cli/test_projects_db.py
index 81a8bb1efda..c33ef261a17 100644
--- a/tests/hermes_cli/test_projects_db.py
+++ b/tests/hermes_cli/test_projects_db.py
@@ -46,8 +46,8 @@ def test_create_get_list(conn):
assert proj.slug == "hermes-agent"
assert proj.name == "Hermes Agent"
# First folder becomes primary.
- assert proj.primary_path == "/tmp/hermes"
- assert [f.path for f in proj.folders] == ["/tmp/hermes"]
+ assert proj.primary_path == os.path.abspath("/tmp/hermes")
+ assert [f.path for f in proj.folders] == [os.path.abspath("/tmp/hermes")]
assert proj.folders[0].is_primary is True
# Lookup by slug too.
@@ -136,7 +136,7 @@ def test_per_profile_isolation(tmp_path):
assert [p.slug for p in pdb.list_projects(a)] == ["only-in-a"]
assert pdb.list_projects(b) == []
assert [row["root"] for row in pdb.list_discovered_repos(a)] == [
- "/a/scanned"
+ os.path.abspath("/a/scanned")
]
assert pdb.list_discovered_repos(b) == []
finally:
diff --git a/tests/hermes_cli/test_prompt_compose_command.py b/tests/hermes_cli/test_prompt_compose_command.py
index 69461279e60..aec7ace09d9 100644
--- a/tests/hermes_cli/test_prompt_compose_command.py
+++ b/tests/hermes_cli/test_prompt_compose_command.py
@@ -46,6 +46,7 @@ def test_command_registered():
assert resolve_command("compose").name == "prompt"
def test_compose_reads_and_strips_header(monkeypatch):
monkeypatch.setenv("EDITOR", _fake_editor("Refactor the auth module.\nUse pytest."))
out = _Stub()._compose_in_editor("")
@@ -54,6 +55,7 @@ def test_compose_reads_and_strips_header(monkeypatch):
assert "#!" not in out # the instructional header is stripped
def test_empty_buffer_does_not_seed(monkeypatch):
monkeypatch.setenv("EDITOR", _fake_editor("", mode="clear"))
s = _Stub()
diff --git a/tests/hermes_cli/test_relaunch.py b/tests/hermes_cli/test_relaunch.py
index ffb611950e4..c964a7031e8 100644
--- a/tests/hermes_cli/test_relaunch.py
+++ b/tests/hermes_cli/test_relaunch.py
@@ -99,6 +99,7 @@ class TestBuildRelaunchArgv:
class TestRelaunch:
+ @pytest.mark.linux_only
def test_calls_execvp(self, monkeypatch):
calls = []
diff --git a/tests/hermes_cli/test_resume_latest_and_in_dir.py b/tests/hermes_cli/test_resume_latest_and_in_dir.py
index 5aa8348884e..8339b6fba05 100644
--- a/tests/hermes_cli/test_resume_latest_and_in_dir.py
+++ b/tests/hermes_cli/test_resume_latest_and_in_dir.py
@@ -215,6 +215,7 @@ def test_in_dir_missing_directory_exits(main_mod, monkeypatch, tmp_path, capsys)
assert "--in directory not found" in capsys.readouterr().out
def test_in_dir_expands_user_home(main_mod, launched, monkeypatch, tmp_path):
import os
diff --git a/tests/hermes_cli/test_serve_runtime_inventory.py b/tests/hermes_cli/test_serve_runtime_inventory.py
index ce3ad99cc33..793582436fc 100644
--- a/tests/hermes_cli/test_serve_runtime_inventory.py
+++ b/tests/hermes_cli/test_serve_runtime_inventory.py
@@ -197,11 +197,14 @@ def test_scan_dashboard_processes_includes_ledger_only_serves(monkeypatch):
fake_pi = SimpleNamespace(ledger_entries=lambda **k: [profiled])
monkeypatch.setitem(sys.modules, "hermes_cli.process_identity", fake_pi)
- # Force the ps/wmic scan itself to find nothing.
+ # Force the ps/wmic scan itself to find nothing. The Windows scan runs
+ # through ``bounded_probe_run`` (a subprocess.run wrapper), not
+ # ``subprocess.run`` directly, so patch both.
fake_run = SimpleNamespace(returncode=0, stdout="")
- monkeypatch.setattr(
- dp.subprocess, "run", lambda *a, **k: fake_run
- )
+ monkeypatch.setattr(dp.subprocess, "run", lambda *a, **k: fake_run)
+ import hermes_cli._subprocess_compat as _sc
+
+ monkeypatch.setattr(_sc, "bounded_probe_run", lambda *a, **k: fake_run)
result = dp._scan_dashboard_processes()
assert (8123, profiled["argv"]) in result
@@ -214,5 +217,8 @@ def test_scan_dashboard_processes_ledger_respects_exclusions(monkeypatch):
monkeypatch.setitem(sys.modules, "hermes_cli.process_identity", fake_pi)
fake_run = SimpleNamespace(returncode=0, stdout="")
monkeypatch.setattr(dp.subprocess, "run", lambda *a, **k: fake_run)
+ import hermes_cli._subprocess_compat as _sc
+
+ monkeypatch.setattr(_sc, "bounded_probe_run", lambda *a, **k: fake_run)
assert dp._scan_dashboard_processes(exclude_pids={8124}) == []
diff --git a/tests/hermes_cli/test_service_manager.py b/tests/hermes_cli/test_service_manager.py
index 706611af90c..807304c010d 100644
--- a/tests/hermes_cli/test_service_manager.py
+++ b/tests/hermes_cli/test_service_manager.py
@@ -192,6 +192,7 @@ def fake_subprocess_run(monkeypatch: pytest.MonkeyPatch):
# tests/docker/test_s6_profile_gateway_integration.py.
def test_seed_supervise_skeleton_creates_expected_layout(tmp_path) -> None:
"""Verifies the dirs + FIFO the helper lays down."""
import stat
@@ -371,6 +372,7 @@ def _log_run_setup_fragment(rendered: str) -> str:
return "#!/bin/sh\n" + "".join(keep)
def test_s6_log_run_creates_leaf_as_hermes_without_chown(
s6_scandir, fake_subprocess_run,
) -> None:
diff --git a/tests/hermes_cli/test_session_browse.py b/tests/hermes_cli/test_session_browse.py
index 16ccf384b00..a3f9619e77a 100644
--- a/tests/hermes_cli/test_session_browse.py
+++ b/tests/hermes_cli/test_session_browse.py
@@ -9,6 +9,8 @@ Covers:
import time
from unittest.mock import MagicMock, patch
+import pytest
+
from hermes_cli.main import _session_browse_picker
@@ -95,6 +97,7 @@ class TestSessionBrowsePicker:
# ─── Curses-based picker (mocked curses) ────────────────────────────────────
class TestCursesBrowse:
"""Tests for the curses-based interactive picker via simulated key sequences."""
diff --git a/tests/hermes_cli/test_skin_cmd.py b/tests/hermes_cli/test_skin_cmd.py
index 09cf29422ae..e4750651750 100644
--- a/tests/hermes_cli/test_skin_cmd.py
+++ b/tests/hermes_cli/test_skin_cmd.py
@@ -99,6 +99,7 @@ def test_set_persists_the_skin_durably():
assert [p.name for p in _skins().iterdir() if p.name.endswith(".tmp")] == []
def test_set_preserves_a_symlinked_skin_file():
"""Guard on the conversion, not a behavior change.
diff --git a/tests/hermes_cli/test_ssh_ownership_endpoint.py b/tests/hermes_cli/test_ssh_ownership_endpoint.py
index ee6154ba80e..6dd0eec32e0 100644
--- a/tests/hermes_cli/test_ssh_ownership_endpoint.py
+++ b/tests/hermes_cli/test_ssh_ownership_endpoint.py
@@ -112,6 +112,7 @@ def test_ssh_runtime_marker_survives_in_place_installs(tmp_path, monkeypatch):
web_server._apply_ssh_owner_nonce(None)
def test_ssh_runtime_readonly_purelib_falls_back_to_stat(tmp_path, monkeypatch):
"""When site-packages is unwritable the marker can't be placed; the
stat-snapshot fallback still arms (weaker, never a false stale)."""
diff --git a/tests/hermes_cli/test_ssh_session_token_parser.py b/tests/hermes_cli/test_ssh_session_token_parser.py
index fd50b7a3732..429fe057959 100644
--- a/tests/hermes_cli/test_ssh_session_token_parser.py
+++ b/tests/hermes_cli/test_ssh_session_token_parser.py
@@ -123,6 +123,7 @@ def test_token_file_rejects_symlink(tmp_path, monkeypatch):
reset_hermes_home_override(override)
def test_token_file_rejects_parent_escape(tmp_path, monkeypatch):
home = tmp_path / "home"
monkeypatch.setenv("HOME", str(home))
diff --git a/tests/hermes_cli/test_terminal_breadcrumbs.py b/tests/hermes_cli/test_terminal_breadcrumbs.py
index caeeb4cd738..14432948e94 100644
--- a/tests/hermes_cli/test_terminal_breadcrumbs.py
+++ b/tests/hermes_cli/test_terminal_breadcrumbs.py
@@ -16,6 +16,9 @@ import pytest
from hermes_cli import terminal_breadcrumbs as tb
+pytestmark = pytest.mark.linux_only # os.ttyname is POSIX-only
+
+
TERMINAL_ENV_VARS = (
"ZELLIJ_PANE_ID",
"TMUX_PANE",
diff --git a/tests/hermes_cli/test_tui_npm_install.py b/tests/hermes_cli/test_tui_npm_install.py
index 49a3346722b..7495daeaa72 100644
--- a/tests/hermes_cli/test_tui_npm_install.py
+++ b/tests/hermes_cli/test_tui_npm_install.py
@@ -332,7 +332,7 @@ def test_make_tui_argv_skips_build_only_on_termux_when_fresh(
argv, cwd = main_mod._make_tui_argv(tmp_path, tui_dev=False)
- assert argv == ["/bin/node", "--expose-gc", str(tmp_path / "dist" / "entry.js")]
+ assert argv[1:] == ["--expose-gc", str(tmp_path / "dist" / "entry.js")]
assert cwd == tmp_path
@@ -352,7 +352,7 @@ def test_make_tui_argv_skips_install_on_termux_when_bundle_fresh(
argv, cwd = main_mod._make_tui_argv(tmp_path, tui_dev=False)
- assert argv == ["/bin/node", "--expose-gc", str(tmp_path / "dist" / "entry.js")]
+ assert argv[1:] == ["--expose-gc", str(tmp_path / "dist" / "entry.js")]
assert cwd == tmp_path
@@ -382,8 +382,7 @@ def test_make_tui_argv_scopes_npm_install_on_termux_workspace(
main_mod._make_tui_argv(tui_dir, tui_dev=False)
install_cmd = calls[0][0][0]
- assert install_cmd[:7] == [
- "/bin/npm",
+ assert install_cmd[1:7] == [
"install",
"--workspace",
"ui-tui",
@@ -418,8 +417,7 @@ def test_make_tui_argv_keeps_desktop_workspace_install_behaviour(
main_mod._make_tui_argv(tui_dir, tui_dev=False)
- assert calls[0][0][0] == [
- "/bin/npm",
+ assert calls[0][0][0][1:] == [
"install",
"--workspace",
"ui-tui",
@@ -463,7 +461,7 @@ def test_make_tui_argv_npm_install_forces_include_dev(
main_mod._make_tui_argv(tui_dir, tui_dev=False)
install_cmd = calls[0][0][0]
- assert install_cmd[:2] == ["/bin/npm", "install"]
+ assert install_cmd[1] == "install"
assert "--include=dev" in install_cmd
@@ -487,7 +485,7 @@ def test_make_tui_argv_keeps_desktop_always_build_behaviour(
main_mod._make_tui_argv(tmp_path, tui_dev=False)
assert calls
- assert calls[0][0][0] == ["/bin/npm", "run", "build"]
+ assert calls[0][0][0][-2:] == ["run", "build"]
_assert_utf8_replace_capture(calls[0][1])
@@ -514,7 +512,7 @@ def test_make_tui_argv_decodes_dev_prebuild_with_utf8_replace(
assert argv == [str(tsx), "src/entry.tsx"]
assert cwd == tmp_path
- assert calls[0][0][0] == ["/bin/npm", "run", "build"]
+ assert calls[0][0][0][-2:] == ["run", "build"]
assert calls[0][1]["cwd"] == str(ink_dir)
_assert_utf8_replace_capture(calls[0][1])
@@ -550,7 +548,7 @@ def test_make_tui_argv_exits_with_recovery_hint_when_workspace_unrecoverable(
argv, cwd = main_mod._make_tui_argv(tui_dir, tui_dev=False)
- assert argv == ["/usr/bin/node", "--expose-gc", str(bundled_entry)]
+ assert argv[1:] == ["--expose-gc", str(bundled_entry)]
assert cwd == bundled_entry.parent
diff --git a/tests/hermes_cli/test_tui_resume_flow.py b/tests/hermes_cli/test_tui_resume_flow.py
index 33ff8f8700f..b3d36ccaa16 100644
--- a/tests/hermes_cli/test_tui_resume_flow.py
+++ b/tests/hermes_cli/test_tui_resume_flow.py
@@ -126,7 +126,7 @@ def test_oneshot_subprocess_exits_without_teardown_abort():
)
assert result.returncode == 0
- assert result.stdout == b"ok\n"
+ assert result.stdout in (b"ok\n", b"ok\r\n")
# Don't demand byte-empty stderr — an import-time warning from the heavy
# CLI import chain shouldn't fail this. What matters is no crash traceback.
assert b"Traceback" not in result.stderr
@@ -281,7 +281,9 @@ def test_make_tui_argv_dev_prebuilds_hermes_ink(monkeypatch, main_mod, tmp_path)
assert argv == [str(tsx), "src/entry.tsx"]
assert cwd == tui_dir
- assert calls == [(["/usr/bin/npm", "run", "build"], str(ink_dir))]
+ assert len(calls) == 1
+ assert calls[0][0][-2:] == ["run", "build"]
+ assert calls[0][1] == str(ink_dir)
diff --git a/tests/hermes_cli/test_uninstall_node_symlinks.py b/tests/hermes_cli/test_uninstall_node_symlinks.py
index a32b062cb79..4c01ffed29d 100644
--- a/tests/hermes_cli/test_uninstall_node_symlinks.py
+++ b/tests/hermes_cli/test_uninstall_node_symlinks.py
@@ -37,6 +37,7 @@ def _make_hermes_node(hermes_home: Path) -> Path:
def test_leaves_unrelated_symlinks_untouched(fake_home):
"""A node symlink the user repointed at nvm must survive uninstall."""
hermes_home = fake_home / ".hermes"
@@ -64,6 +65,7 @@ def test_leaves_unrelated_symlinks_untouched(fake_home):
def test_removes_fhs_symlinks_in_usr_local_bin(fake_home, tmp_path, monkeypatch):
"""Root FHS installs place node symlinks in /usr/local/bin.
diff --git a/tests/hermes_cli/test_uninstall_shell_configs.py b/tests/hermes_cli/test_uninstall_shell_configs.py
index 4cc9bc1b974..1ba87c9551f 100644
--- a/tests/hermes_cli/test_uninstall_shell_configs.py
+++ b/tests/hermes_cli/test_uninstall_shell_configs.py
@@ -88,6 +88,7 @@ class TestCrashDurability:
# The aborted write must not leave a temp file behind in $HOME.
assert list(fake_home.glob("*.tmp")) == []
+ @pytest.mark.require_symlinks
def test_symlinked_shell_config_stays_a_symlink(self, fake_home: Path):
"""A dotfiles-repo ``~/.zshrc`` is a symlink; replacing it with a
regular file silently detaches the user's dotfiles."""
diff --git a/tests/hermes_cli/test_update_head_moved_gate.py b/tests/hermes_cli/test_update_head_moved_gate.py
index f363dac4117..5a576997bc2 100644
--- a/tests/hermes_cli/test_update_head_moved_gate.py
+++ b/tests/hermes_cli/test_update_head_moved_gate.py
@@ -11,11 +11,21 @@ and fails loudly when the update was a no-op.
from types import SimpleNamespace
+import os
+
import pytest
from hermes_cli import main as hermes_main
[email protected](autouse=True)
+def _isolate_venv_holders(monkeypatch):
+ """The update flow's venv-holder guard sees the live gateway processes on
+ a dev machine and aborts with SystemExit 2 before reaching the HEAD-move
+ gate under test. Isolate it so the test exercises the intended path."""
+ monkeypatch.setattr(hermes_main, "_detect_venv_python_processes", lambda: [])
+
+
def _make_head_moved_side_effect(pre_sha="abc123", post_sha="def456"):
"""Simulate git commands where HEAD advances from pre_sha to post_sha."""
calls = {"n": 0}
@@ -119,6 +129,14 @@ def _patch_update_deps(monkeypatch, tmp_path, run_side_effect):
monkeypatch.setattr(
hermes_gateway, "find_profile_gateway_processes", lambda *a, **k: []
)
+ # _restart_gateways_after_update purges and re-imports hermes_cli.gateway,
+ # which undoes the discovery mocks above (the fresh import finds the live
+ # gateways on this dev machine). Neutralize the kill itself so the phase
+ # is a no-op regardless of what the re-imported discovery returns.
+ monkeypatch.setattr(os, "kill", lambda *a, **k: None)
+ # ...and stop the purge from evicting the mocked module in the first place,
+ # so find_gateway_pids stays [] and the fleet-restart phase is a clean no-op.
+ monkeypatch.setattr(hermes_main, "_purge_stale_hermes_modules", lambda: None)
def test_update_success_when_head_moves(monkeypatch, tmp_path, capsys):
diff --git a/tests/hermes_cli/test_update_launchd_unloaded_gateway.py b/tests/hermes_cli/test_update_launchd_unloaded_gateway.py
index 315fa724422..562c0882dde 100644
--- a/tests/hermes_cli/test_update_launchd_unloaded_gateway.py
+++ b/tests/hermes_cli/test_update_launchd_unloaded_gateway.py
@@ -133,6 +133,7 @@ ai.hermes.gateway = {
"""
class TestServicePidSweepExclusion:
"""Regression for the PR #75021 review: `_get_service_pids()` must not
rely on `launchctl list` alone.
diff --git a/tests/hermes_cli/test_update_yes_flag.py b/tests/hermes_cli/test_update_yes_flag.py
index ef5a0318595..3603caf5e92 100644
--- a/tests/hermes_cli/test_update_yes_flag.py
+++ b/tests/hermes_cli/test_update_yes_flag.py
@@ -12,9 +12,21 @@ import subprocess
from types import SimpleNamespace
from unittest.mock import patch
+import pytest
+
from hermes_cli.main import cmd_update
[email protected](autouse=True)
+def _isolate_venv_holders(monkeypatch):
+ """The update flow's venv-holder guard sees the live gateway processes on
+ a dev machine and aborts with SystemExit 2 before reaching the branch
+ logic under test. Isolate it so the test exercises the intended path."""
+ import hermes_cli.main as cli_main
+
+ monkeypatch.setattr(cli_main, "_detect_venv_python_processes", lambda: [])
+
+
def _make_run_side_effect(
branch="main", verify_ok=True, commit_count="1", dirty=False
):
diff --git a/tests/hermes_cli/test_web_ui_build.py b/tests/hermes_cli/test_web_ui_build.py
index e1b05d183bc..c6bc6ad869d 100644
--- a/tests/hermes_cli/test_web_ui_build.py
+++ b/tests/hermes_cli/test_web_ui_build.py
@@ -233,7 +233,7 @@ class TestBuildWebUISkipsWhenFresh:
mock_idle.assert_called_once()
args, kwargs = mock_idle.call_args
# Positional: [npm, "run", "build"]; cwd passed as kwarg.
- assert args[0] == ["/usr/bin/npm", "run", "build"]
+ assert args[0][-2:] == ["run", "build"]
assert kwargs["cwd"] == web_dir
@@ -282,6 +282,7 @@ class TestBuildWebUIRetryAndStaleFallback:
assert "vite ENOMEM" in out # combined output surfaced to user
class TestBuildWebUIFlock:
"""Cross-process build serialization (salvaged from PR #63455).
diff --git a/tests/hermes_cli/test_worktree_command.py b/tests/hermes_cli/test_worktree_command.py
index bf9443e7718..163943e401a 100644
--- a/tests/hermes_cli/test_worktree_command.py
+++ b/tests/hermes_cli/test_worktree_command.py
@@ -98,7 +98,7 @@ def test_new_outside_repo(tmp_path, monkeypatch):
@requires_git
def test_list_shows_worktrees(repo):
out = _run(_Stub(), "/worktree list")
- assert str(repo) in out
+ assert repo.as_posix() in out
@requires_git
diff --git a/tests/honcho_plugin/test_client.py b/tests/honcho_plugin/test_client.py
index 630a5bf5cd1..743e19ce3e3 100644
--- a/tests/honcho_plugin/test_client.py
+++ b/tests/honcho_plugin/test_client.py
@@ -22,6 +22,9 @@ from plugins.memory.honcho.client import (
resolve_global_config_path,
)
+import os as _os
+_SYS_ENV = {k: _os.environ[k] for k in ("SYSTEMROOT", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "HOME") if k in _os.environ}
+
class TestHonchoClientConfigDefaults:
def test_default_values(self):
@@ -48,7 +51,7 @@ class TestFromEnv:
def test_defaults_without_env(self):
- with patch.dict(os.environ, {}, clear=True):
+ with patch.dict(os.environ, _SYS_ENV, clear=True):
# Remove HONCHO_API_KEY if it exists
os.environ.pop("HONCHO_API_KEY", None)
os.environ.pop("HONCHO_ENVIRONMENT", None)
@@ -92,7 +95,7 @@ class TestFromEnv:
class TestFromGlobalConfig:
def test_missing_config_falls_back_to_env(self, tmp_path):
- with patch.dict(os.environ, {}, clear=True):
+ with patch.dict(os.environ, _SYS_ENV, clear=True):
config = HonchoClientConfig.from_global_config(
config_path=tmp_path / "nonexistent.json"
)
@@ -108,7 +111,7 @@ class TestFromGlobalConfig:
absent, so a fallback that only from_global_config() understood
would silently do nothing for users with no ~/.honcho/config.json.
"""
- with patch.dict(os.environ, {"HONCHO_URL": "http://localhost:8000"}, clear=True):
+ with patch.dict(os.environ, {**_SYS_ENV, "HONCHO_URL": "http://localhost:8000"}, clear=True):
config = HonchoClientConfig.from_global_config(
config_path=tmp_path / "nonexistent.json"
)
@@ -124,7 +127,7 @@ class TestFromGlobalConfig:
"endpoint": {"baseUrl": "http://localhost:8000"},
}))
- with patch.dict(os.environ, {}, clear=True):
+ with patch.dict(os.environ, _SYS_ENV, clear=True):
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.base_url == "http://localhost:8000"
@@ -137,7 +140,7 @@ class TestFromGlobalConfig:
"base_url": "http://localhost:9002",
}))
- with patch.dict(os.environ, {"HONCHO_BASE_URL": "http://localhost:9003"}, clear=True):
+ with patch.dict(os.environ, {**_SYS_ENV, "HONCHO_BASE_URL": "http://localhost:9003"}, clear=True):
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.base_url == "http://localhost:8000"
@@ -150,7 +153,7 @@ class TestFromGlobalConfig:
"baseUrl": "http://localhost:9001",
}))
- with patch.dict(os.environ, {}, clear=True):
+ with patch.dict(os.environ, _SYS_ENV, clear=True):
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.base_url == "http://localhost:9001"
@@ -245,7 +248,7 @@ class TestFromGlobalConfig:
if i >= 4:
env_dict.pop("HONCHO_BASE_URL")
config_file.write_text(json.dumps(cfg_dict))
- with patch.dict(os.environ, env_dict, clear=True):
+ with patch.dict(os.environ, {**_SYS_ENV, **env_dict}, clear=True):
config = HonchoClientConfig.from_global_config(config_path=config_file)
assert config.base_url == want, f"layer {i}: got {config.base_url!r}, want {want!r}"
@@ -711,7 +714,7 @@ class TestGetHonchoClientBaseUrlDoublePrefixFix:
},
}))
- with patch.dict(os.environ, {}, clear=True), \
+ with patch.dict(os.environ, _SYS_ENV, clear=True), \
patch("hermes_cli.profiles.get_active_profile_name", return_value="default"), \
patch("plugins.memory.honcho.client.resolve_config_path", return_value=config_file):
cfg = HonchoClientConfig.from_global_config(config_path=config_file)
diff --git a/tests/honcho_plugin/test_oauth_flow.py b/tests/honcho_plugin/test_oauth_flow.py
index f590932e022..07317b79b1f 100644
--- a/tests/honcho_plugin/test_oauth_flow.py
+++ b/tests/honcho_plugin/test_oauth_flow.py
@@ -271,7 +271,7 @@ def test_display_config_path_never_leaks_absolute_path():
# Under home → collapsed to ~/…; outside home → bare filename only.
under_home = Path.home() / ".hermes" / "profiles" / "work" / "honcho.json"
- assert oauth_flow._display_config_path(under_home) == "~/.hermes/profiles/work/honcho.json"
+ assert oauth_flow._display_config_path(under_home) == "~/" + str(Path(".hermes") / "profiles" / "work" / "honcho.json")
assert oauth_flow._display_config_path("/var/folders/tmp/honcho.json") == "honcho.json"
diff --git a/tests/plugins/image_gen/test_krea_provider.py b/tests/plugins/image_gen/test_krea_provider.py
index 32c7ae45750..f67e7c9b791 100644
--- a/tests/plugins/image_gen/test_krea_provider.py
+++ b/tests/plugins/image_gen/test_krea_provider.py
@@ -166,7 +166,7 @@ class TestGenerate:
result = KreaImageGenProvider().generate(prompt="A cinematic lamp", upscale=False)
assert result["success"] is True
- assert result["image"] == "/tmp/krea_krea-2-medium_test.png"
+ assert result["image"] == str(Path("/tmp/krea_krea-2-medium_test.png"))
assert result["provider"] == "krea"
assert result["model"] == "krea-2-medium"
assert result["aspect_ratio"] == "landscape"
diff --git a/tests/plugins/image_gen/test_openai_provider.py b/tests/plugins/image_gen/test_openai_provider.py
index f662b13f8dd..8c8abd98c37 100644
--- a/tests/plugins/image_gen/test_openai_provider.py
+++ b/tests/plugins/image_gen/test_openai_provider.py
@@ -236,7 +236,7 @@ class TestGenerate:
result = provider.generate("a cat")
assert result["success"] is True
- assert result["image"].startswith("/")
+ assert result["image"].startswith(str(Path("/")))
assert "example.com" not in result["image"]
mock_save_url.assert_called_once()
diff --git a/tests/plugins/image_gen/test_openrouter_compat_provider.py b/tests/plugins/image_gen/test_openrouter_compat_provider.py
index b3647376b9e..e5c51af09eb 100644
--- a/tests/plugins/image_gen/test_openrouter_compat_provider.py
+++ b/tests/plugins/image_gen/test_openrouter_compat_provider.py
@@ -325,7 +325,7 @@ class TestGenerate:
result = _openrouter().generate(prompt="a pet")
assert result["success"] is True
- assert result["image"] == "/tmp/openrouter_gen.png"
+ assert result["image"] == str(Path("/tmp/openrouter_gen.png"))
assert result["provider"] == "openrouter"
mock_save.assert_called_once()
@@ -701,7 +701,7 @@ class TestImageApiSurface:
assert result["cost_usd"] == 0.0336
assert result["total_tokens"] == 1128
assert result["exact_aspect_ratio"] == "9:16"
- assert result["image"] == "/tmp/i.png"
+ assert result["image"] == str(Path("/tmp/i.png"))
def test_multiple_images_land_in_additional_images(self):
entries = [
@@ -714,8 +714,8 @@ class TestImageApiSurface:
side_effect=[Path("/tmp/a.png"), Path("/tmp/b.png")]):
result = _openrouter_image_api().generate(prompt="p", model="openai/gpt-image-2")
- assert result["image"] == "/tmp/a.png"
- assert result["additional_images"] == ["/tmp/b.png"]
+ assert result["image"] == str(Path("/tmp/a.png"))
+ assert result["additional_images"] == [str(Path("/tmp/b.png"))]
def test_empty_data_is_typed(self):
with patch(_RUNTIME, return_value=_runtime_ok()), \
diff --git a/tests/plugins/memory/test_holographic_store.py b/tests/plugins/memory/test_holographic_store.py
index 9fa17728410..78c7d1485fb 100644
--- a/tests/plugins/memory/test_holographic_store.py
+++ b/tests/plugins/memory/test_holographic_store.py
@@ -68,6 +68,7 @@ class TestSharedConnection:
a.close()
b.close()
+ @pytest.mark.require_symlinks
def test_symlinked_path_shares_connection(self, tmp_path):
"""A symlink to the same DB file must hit the same registry entry —
otherwise two connections to one file silently reintroduce the
diff --git a/tests/plugins/memory/test_openviking_provider.py b/tests/plugins/memory/test_openviking_provider.py
index 315511d1565..bfff736ac7e 100644
--- a/tests/plugins/memory/test_openviking_provider.py
+++ b/tests/plugins/memory/test_openviking_provider.py
@@ -1912,7 +1912,7 @@ class TestOpenVikingEnvWriter:
_write_env_vars(env, {"OPENAI_API_KEY": "new"})
- assert env.read_bytes() == b"NAME=caf\xe9\nOPENAI_API_KEY=new\n"
+ assert env.read_bytes() == f"NAME=caf\xe9{os.linesep}OPENAI_API_KEY=new{os.linesep}".encode("latin-1")
def test_plain_env_is_unchanged_apart_from_the_write(self, tmp_path):
from plugins.memory.openviking import _write_env_vars
diff --git a/tests/plugins/platforms/photon/test_sidecar_paths.py b/tests/plugins/platforms/photon/test_sidecar_paths.py
index 66ee07feb6d..2486b45a94a 100644
--- a/tests/plugins/platforms/photon/test_sidecar_paths.py
+++ b/tests/plugins/platforms/photon/test_sidecar_paths.py
@@ -88,6 +88,7 @@ def test_mirror_refresh_updates_changed_files_and_keeps_node_modules(
assert (mirror / "node_modules" / "installed.txt").exists()
def test_dir_writable_probe(tmp_path) -> None:
assert sidecar_paths.dir_writable(tmp_path) is True
ro = tmp_path / "ro"
diff --git a/tests/plugins/test_a2a_plugin.py b/tests/plugins/test_a2a_plugin.py
index 346284b2779..ccd485555d3 100644
--- a/tests/plugins/test_a2a_plugin.py
+++ b/tests/plugins/test_a2a_plugin.py
@@ -1570,6 +1570,7 @@ class TestV1SpecRegressionFixes:
assert "one" in adapter._agents
assert "two" not in adapter._agents
+ @pytest.mark.linux_only
def test_forward_to_profile_first_contact_creates_then_resumes_fake_hermes(self, monkeypatch, tmp_path):
from plugins.platforms.a2a.adapter import A2AAdapter
from gateway.config import PlatformConfig
diff --git a/tests/plugins/video_gen/test_deepinfra_provider.py b/tests/plugins/video_gen/test_deepinfra_provider.py
index 6902625e460..d33fc92465a 100644
--- a/tests/plugins/video_gen/test_deepinfra_provider.py
+++ b/tests/plugins/video_gen/test_deepinfra_provider.py
@@ -10,6 +10,7 @@ t2v vs i2v routing, download → save).
from __future__ import annotations
from contextlib import contextmanager
+from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
@@ -118,7 +119,7 @@ def test_generate_text_to_video_downloads_url_and_saves_locally():
)
assert result["success"] is True
assert result["modality"] == "text"
- assert result["video"].endswith(".mp4") and "cache/videos" in result["video"]
+ assert result["video"].endswith(".mp4") and str(Path("cache") / "videos") in result["video"]
assert captured["url"] == "https://cdn.example/out.mp4"
assert "deepinfra" in captured["base_url"]
assert captured["api_key"] == "test-key"
diff --git a/tests/run_agent/test_compression_boundary_hook.py b/tests/run_agent/test_compression_boundary_hook.py
index 2595c0ee646..88c0828d5d3 100644
--- a/tests/run_agent/test_compression_boundary_hook.py
+++ b/tests/run_agent/test_compression_boundary_hook.py
@@ -97,6 +97,7 @@ class TestCompressionBoundaryHook:
assert call.kwargs.get("old_session_id") == original_sid, \
f"Expected old_session_id={original_sid!r}, got {call.kwargs!r}"
assert len(comp_calls) == 1
+ db.close()
def test_automatic_notification_follows_core_persistence(self):
from hermes_state import SessionDB
@@ -137,6 +138,7 @@ class TestCompressionBoundaryHook:
)
assert events == ["persist", "compression"]
+ db.close()
def test_failure_before_persistence_does_not_notify(self):
from hermes_state import SessionDB
@@ -156,6 +158,7 @@ class TestCompressionBoundaryHook:
)
compressor.on_session_start.assert_not_called()
+ db.close()
def test_no_progress_does_not_notify(self):
@@ -178,6 +181,7 @@ class TestCompressionBoundaryHook:
assert returned is messages
compressor.on_session_start.assert_not_called()
+ db.close()
def test_no_hook_when_no_session_db(self):
@@ -251,6 +255,7 @@ class TestCompressionBoundaryHook:
)
assert compressed
assert agent.session_id != original_sid
+ db.close()
class TestSessionCompressEvent:
@@ -311,6 +316,7 @@ class TestSessionCompressEvent:
assert ctx["session_id"] == agent.session_id
assert ctx["old_session_id"] == original_sid
assert ctx["compression_count"] == 1
+ db.close()
def test_no_callback_is_safe(self):
"""Compression must work when no event_callback is wired."""
@@ -324,4 +330,5 @@ class TestSessionCompressEvent:
[{"role": "user", "content": "m"}], "sys", approx_tokens=100
)
assert compressed
+ db.close()
diff --git a/tests/run_agent/test_compression_persistence.py b/tests/run_agent/test_compression_persistence.py
index a99448d1cbb..340f4c61080 100644
--- a/tests/run_agent/test_compression_persistence.py
+++ b/tests/run_agent/test_compression_persistence.py
@@ -99,6 +99,7 @@ class TestFlushAfterCompression:
f"Expected 5 compressed messages in new session, got {len(new_rows)}. "
f"Compression persistence bug: messages not written to SQLite."
)
+ db.close()
def test_flush_with_stale_history_loses_messages(self):
"""Stale conversation_history no longer causes data loss."""
@@ -128,6 +129,7 @@ class TestFlushAfterCompression:
rows = db.get_messages("new-session")
assert len(rows) == 2
assert [row["content"] for row in rows] == ["summary", "continuing..."]
+ db.close()
def test_in_place_compression_rebaseline_prevents_duplicate_compacted_rows(self):
"""In-place compaction already persisted the compacted transcript.
@@ -190,6 +192,7 @@ class TestFlushAfterCompression:
"tool result",
"final answer",
]
+ db.close()
def test_abort_after_in_place_compaction_preserves_flush_baseline(self):
"""An aborted retry must survive flush, restart, and resume."""
@@ -428,7 +431,7 @@ class TestStoredPromptCwdDrift:
from agent.conversation_loop import _stored_prompt_matches_runtime
agent = self._make_agent()
- current_cwd = "/project/current"
+ current_cwd = str(Path("/project/current"))
stored_prompt = (
self._host_block(current_cwd)
+ "Model: test/model\n"
@@ -456,7 +459,7 @@ class TestStoredPromptCwdDrift:
from agent.conversation_loop import _stored_prompt_matches_runtime
agent = self._make_agent()
- current_cwd = "/project/current"
+ current_cwd = str(Path("/project/current"))
stored_prompt = (
self._host_block(current_cwd)
+ "\n# AGENTS.md\n\n"
@@ -531,3 +534,4 @@ class TestStoredPromptCwdDrift:
assert "Platform: cli" in parts["volatile"], (
"Built prompt missing 'Platform: cli' — drift detection cannot read it"
)
+ db.close()
diff --git a/tests/run_agent/test_in_place_compaction.py b/tests/run_agent/test_in_place_compaction.py
index 93d8236151c..22289607811 100644
--- a/tests/run_agent/test_in_place_compaction.py
+++ b/tests/run_agent/test_in_place_compaction.py
@@ -123,6 +123,7 @@ class TestInPlaceCompaction:
assert agent._last_compaction_in_place is True
# Live transcript actually shrank.
assert len(compressed) == 2
+ db.close()
def test_in_place_alternation_preserved(self):
"""The compacted list must not introduce consecutive same-role messages."""
@@ -140,6 +141,7 @@ class TestInPlaceCompaction:
)
roles = [m["role"] for m in compressed if m.get("role") != "system"]
assert all(roles[i] != roles[i + 1] for i in range(len(roles) - 1))
+ db.close()
def test_rotation_still_preflushes(self):
@@ -161,6 +163,7 @@ class TestInPlaceCompaction:
approx_tokens=100_000, system_message="sys",
)
assert calls["n"] == 1
+ db.close()
class TestRotationFallbackWhenFlagOff:
@@ -205,6 +208,7 @@ class TestRotationFallbackWhenFlagOff:
]
# Rotation mode does NOT set the in-place signal.
assert getattr(agent, "_last_compaction_in_place", False) is False
+ db.close()
class TestInPlaceSignalForGateway:
@@ -234,6 +238,7 @@ class TestInPlaceSignalForGateway:
approx_tokens=100_000, system_message="sys",
)
assert a_rot._last_compaction_in_place is False
+ db.close()
class TestInPlaceConfigDefault:
@@ -292,6 +297,7 @@ class TestInPlaceAntiGrowthGuard:
# Session identity untouched.
assert agent.session_id == sid
assert db.get_session(sid)["end_reason"] is None
+ db.close()
def test_in_place_salvages_near_break_even_growth(self):
"""Fat retained tool output + todo state should be salvaged and committed."""
@@ -348,6 +354,7 @@ class TestInPlaceAntiGrowthGuard:
# Tool stubbing alone got under budget, so the todo snapshot (the
# only in-transcript todo re-injection) survives the salvage.
assert any(m.get("_todo_snapshot_synthetic") for m in compressed)
+ db.close()
def test_in_place_still_commits_shrinking_compression(self):
"""The guard must not block legitimate compressions — a result SMALLER
@@ -374,6 +381,7 @@ class TestInPlaceAntiGrowthGuard:
"[CONTEXT COMPACTION] summary of prior turns",
"recent reply",
]
+ db.close()
class TestCompactedTurnsStaySearchable:
@@ -417,6 +425,7 @@ class TestCompactedTurnsStaySearchable:
assert {m["id"] for m in after} == {1, 4}
# Live context still excludes them.
assert len(db.get_messages_as_conversation(sid)) == 2
+ db.close()
def test_rewound_turns_stay_hidden(self):
"""Rewind/undo (active=0, compacted=0) must NOT leak into default
@@ -436,3 +445,4 @@ class TestCompactedTurnsStaySearchable:
"ZEBRAWORD", role_filter=["user", "assistant"], include_inactive=True
)
assert len(recovered) == 1
+ db.close()
diff --git a/tests/run_agent/test_tool_batch_segmentation.py b/tests/run_agent/test_tool_batch_segmentation.py
index 6f367878b91..584c66da8f8 100644
--- a/tests/run_agent/test_tool_batch_segmentation.py
+++ b/tests/run_agent/test_tool_batch_segmentation.py
@@ -667,6 +667,7 @@ class TestPathCanonicalization:
"Absolute and relative paths pointing to the same file must overlap"
)
+ @pytest.mark.require_symlinks
def test_symlink_aliases_are_not_parallelized(self, tmp_path):
"""A symlink alias and the real path must be detected as overlapping
so they are never placed in the same parallel segment."""
diff --git a/tests/run_agent/test_tool_call_guardrail_runtime.py b/tests/run_agent/test_tool_call_guardrail_runtime.py
index ca6e80aac4c..83f327e2cb2 100644
--- a/tests/run_agent/test_tool_call_guardrail_runtime.py
+++ b/tests/run_agent/test_tool_call_guardrail_runtime.py
@@ -2,6 +2,7 @@
import json
import uuid
+from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
@@ -293,7 +294,7 @@ def test_relay_rewrite_precedes_sequential_policy_approval_checkpoint_and_dispat
assert observed["start"] == expected
assert observed["dispatch"] == expected
assert observed["checkpoint"] == [
- ("/approved/path", "before write_file")
+ (str(Path("/approved/path")), "before write_file")
]
diff --git a/tests/skills/test_openclaw_migration.py b/tests/skills/test_openclaw_migration.py
index bfd69cc2d64..c456844fc09 100644
--- a/tests/skills/test_openclaw_migration.py
+++ b/tests/skills/test_openclaw_migration.py
@@ -5,6 +5,8 @@ import json
import sys
from pathlib import Path
+import pytest
+
SCRIPT_PATH = (
Path(__file__).resolve().parents[2]
@@ -247,6 +249,7 @@ def test_absent_config_is_still_created(tmp_path: Path):
assert "anthropic/claude-sonnet-4" in config_path.read_text(encoding="utf-8")
def test_symlinked_config_stays_a_symlink(tmp_path: Path):
"""Managed deployments symlink ~/.hermes/config.yaml into a dotfiles repo.
diff --git a/tests/state/test_fts_runtime_rebuild.py b/tests/state/test_fts_runtime_rebuild.py
index 8779186e72c..46ec418194e 100644
--- a/tests/state/test_fts_runtime_rebuild.py
+++ b/tests/state/test_fts_runtime_rebuild.py
@@ -183,6 +183,7 @@ class TestRuntimeFtsRebuild:
(222, f"{db_path}-wal (deleted)")
]
+ @pytest.mark.linux_only
def test_foreign_holder_detection_proc_readlink_deleted_wal(
self, db, tmp_path, monkeypatch
):
@@ -227,6 +228,7 @@ class TestRuntimeFtsRebuild:
holders = db._foreign_state_db_holders()
assert holders == [(222, db_path_wal + " (deleted)")]
+ @pytest.mark.linux_only
def test_foreign_holder_uninspectable_process_cmdline_fallback(
self, db, tmp_path, monkeypatch
):
diff --git a/tests/test_atomic_replace_symlinks.py b/tests/test_atomic_replace_symlinks.py
index 42c85568892..797d2b3a12d 100644
--- a/tests/test_atomic_replace_symlinks.py
+++ b/tests/test_atomic_replace_symlinks.py
@@ -224,6 +224,7 @@ def test_atomic_replace_broken_symlink_creates_target(tmp_path: Path) -> None:
def test_atomic_replace_copy_fallback_preserves_symlink(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -506,6 +507,7 @@ def test_in_place_rewrite_never_exposes_a_truncated_file(
assert observed == [5000]
def test_symlinked_target_survives_a_contended_rename(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fast_replace_retries: None
) -> None:
diff --git a/tests/test_bitwarden_secrets.py b/tests/test_bitwarden_secrets.py
index 420605416c9..3fb0cf15d84 100644
--- a/tests/test_bitwarden_secrets.py
+++ b/tests/test_bitwarden_secrets.py
@@ -135,6 +135,7 @@ def test_safe_extract_member_rejects_traversal(tmp_path, evil_name):
def test_install_bws_happy_path(hermes_home, monkeypatch):
fake_binary = b"#!/bin/sh\necho 'bws fake 2.0.0'\n"
zip_bytes = _make_fake_zip(fake_binary)
@@ -334,6 +335,7 @@ def test_disk_cache_key_mismatch_triggers_refetch(monkeypatch, tmp_path):
def test_encrypted_cache_writes_without_plaintext(monkeypatch, tmp_path):
"""Encrypted cache stores last-good secrets without raw values on disk."""
home = tmp_path / ".hermes"
diff --git a/tests/test_hermes_bootstrap.py b/tests/test_hermes_bootstrap.py
index b95b50d9ad0..c2e3dc43b03 100644
--- a/tests/test_hermes_bootstrap.py
+++ b/tests/test_hermes_bootstrap.py
@@ -125,6 +125,7 @@ class TestPosixNoOp:
stdio. The goal is that Linux/macOS behave identically before and
after this module is imported."""
+ @pytest.mark.linux_only
def test_noop_on_posix_host(self, monkeypatch):
"""Even when imported, the bootstrap function must return False
and leave env untouched on a POSIX host (``_IS_WINDOWS`` is
@@ -336,6 +337,7 @@ class TestHardenImportPath:
class TestSuppressPlatformVerConsole:
"""suppress_platform_ver_console: stub applied on Windows, no-op on POSIX."""
+ @pytest.mark.linux_only
def test_noop_on_posix(self):
import platform
hb = _fresh_import()
diff --git a/tests/test_hermes_constants.py b/tests/test_hermes_constants.py
index e5bb62947b1..ec952da9c7a 100644
--- a/tests/test_hermes_constants.py
+++ b/tests/test_hermes_constants.py
@@ -33,6 +33,7 @@ from hermes_constants import (
class TestGetDefaultHermesRoot:
"""Tests for get_default_hermes_root() — Docker/custom deployment awareness."""
+ @pytest.mark.linux_only
def test_no_hermes_home_returns_native(self, tmp_path, monkeypatch):
"""When HERMES_HOME is not set, returns ~/.hermes."""
monkeypatch.delenv("HERMES_HOME", raising=False)
@@ -725,6 +726,7 @@ class TestGetHermesDir:
+ @pytest.mark.require_symlinks
def test_dangling_legacy_symlink_returns_new(self, tmp_path, monkeypatch):
"""A dangling legacy symlink must NOT shadow populated new-layout data.
@@ -743,6 +745,7 @@ class TestGetHermesDir:
result = get_hermes_dir("platforms/pairing", "pairing")
assert result == new
+ @pytest.mark.require_symlinks
def test_symlink_to_populated_dir_returns_legacy(self, tmp_path, monkeypatch):
"""A legacy symlink pointing at a populated directory is honoured."""
self._set_home(tmp_path, monkeypatch)
diff --git a/tests/test_hermes_home_profile_warning.py b/tests/test_hermes_home_profile_warning.py
index 5ece51bc5c3..492636e9fd2 100644
--- a/tests/test_hermes_home_profile_warning.py
+++ b/tests/test_hermes_home_profile_warning.py
@@ -30,6 +30,7 @@ def fresh_constants(monkeypatch, tmp_path):
class TestGetHermesHomeProfileWarning:
+ @pytest.mark.linux_only
def test_classic_mode_no_active_profile_no_warning(
self, fresh_constants, tmp_path, capsys
):
@@ -39,6 +40,7 @@ class TestGetHermesHomeProfileWarning:
assert "HERMES_HOME fallback" not in capsys.readouterr().err
+ @pytest.mark.linux_only
def test_named_profile_unset_home_warns_once(
self, fresh_constants, tmp_path, capsys
):
@@ -77,6 +79,7 @@ class TestGetHermesHomeProfileWarning:
assert result == profile_dir
assert "HERMES_HOME fallback" not in capsys.readouterr().err
+ @pytest.mark.linux_only
def test_unreadable_active_profile_no_crash(
self, fresh_constants, tmp_path, capsys
):
diff --git a/tests/test_hermes_logging.py b/tests/test_hermes_logging.py
index bd87d933403..dd0989037cb 100644
--- a/tests/test_hermes_logging.py
+++ b/tests/test_hermes_logging.py
@@ -382,6 +382,7 @@ class TestAddRotatingHandler:
logger.removeHandler(h)
h.close()
+ @pytest.mark.linux_only
def test_managed_mode_initial_open_sets_group_writable(self, tmp_path):
log_path = tmp_path / "managed-open.log"
logger = logging.getLogger("_test_rotating_managed_open")
diff --git a/tests/test_install_autostash_conflict_recovery.py b/tests/test_install_autostash_conflict_recovery.py
index 94e19aeec59..44f8ca90f55 100644
--- a/tests/test_install_autostash_conflict_recovery.py
+++ b/tests/test_install_autostash_conflict_recovery.py
@@ -79,6 +79,7 @@ def _assert_conflict_was_recovered(repo: Path, output: str) -> None:
@pytest.mark.live_system_guard_bypass
@pytest.mark.skipif(
shutil.which("git") is None or shutil.which("bash") is None,
reason="needs git and bash",
@@ -137,6 +138,7 @@ def test_install_ps1_repository_stage_recovers_from_autostash_conflict(
@pytest.mark.live_system_guard_bypass
@pytest.mark.skipif(
shutil.which("git") is None or shutil.which("bash") is None,
reason="needs git and bash",
diff --git a/tests/test_install_macos_launcher.py b/tests/test_install_macos_launcher.py
index fd46c347a7a..ce4d1aa731b 100644
--- a/tests/test_install_macos_launcher.py
+++ b/tests/test_install_macos_launcher.py
@@ -9,6 +9,10 @@ import stat
import subprocess
from pathlib import Path
+import pytest
+
+pytestmark = pytest.mark.macos_only
+
REPO_ROOT = Path(__file__).resolve().parent.parent
INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
diff --git a/tests/test_install_sh_acp_launcher.py b/tests/test_install_sh_acp_launcher.py
index 27cb4c8f1ae..3cda1866abb 100644
--- a/tests/test_install_sh_acp_launcher.py
+++ b/tests/test_install_sh_acp_launcher.py
@@ -16,6 +16,8 @@ import subprocess
from pathlib import Path
from unittest.mock import patch
+import pytest
+
INSTALL_SH = Path(__file__).resolve().parent.parent / "scripts" / "install.sh"
ACP_BLOCK = re.compile(
@@ -65,6 +67,7 @@ def _run_block(tmp_path: Path, use_venv: str) -> Path:
return command_link_dir / "hermes-acp"
def test_venv_install_writes_executable_acp_launcher(tmp_path):
shim = _run_block(tmp_path, "true")
assert shim.is_file()
@@ -78,12 +81,14 @@ def test_venv_install_writes_executable_acp_launcher(tmp_path):
assert re.search(r'exec .*\bacp\b', text), text
def test_non_venv_install_writes_acp_launcher(tmp_path):
shim = _run_block(tmp_path, "false")
text = shim.read_text(encoding="utf-8")
assert re.search(r'exec .*\bacp\b', text), text
def test_acp_launcher_does_not_follow_a_symlink_into_the_venv(tmp_path):
"""Guards the #21454 failure mode for the new launcher.
@@ -185,6 +190,7 @@ def _run_hermes_agent_block(tmp_path: Path, use_venv: str) -> Path | None:
return command_link_dir / "hermes-agent"
def test_venv_install_writes_executable_hermes_agent_launcher(tmp_path):
"""venv install must write a user-executable hermes-agent launcher."""
shim = _run_hermes_agent_block(tmp_path, "true")
diff --git a/tests/test_install_sh_bootstrap_marker.py b/tests/test_install_sh_bootstrap_marker.py
index 6eab5d6599d..4a553756ab3 100644
--- a/tests/test_install_sh_bootstrap_marker.py
+++ b/tests/test_install_sh_bootstrap_marker.py
@@ -16,6 +16,8 @@ from pathlib import Path
import pytest
+pytestmark = pytest.mark.linux_only
+
REPO_ROOT = Path(__file__).resolve().parent.parent
INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
diff --git a/tests/test_install_sh_node_deps_failure.py b/tests/test_install_sh_node_deps_failure.py
index c42e0cb32ca..2ecf9e67327 100644
--- a/tests/test_install_sh_node_deps_failure.py
+++ b/tests/test_install_sh_node_deps_failure.py
@@ -7,6 +7,10 @@ import os
import subprocess
from pathlib import Path
+import pytest
+
+pytestmark = pytest.mark.linux_only
+
REPO_ROOT = Path(__file__).resolve().parent.parent
INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
diff --git a/tests/test_install_sh_symlink_stomp.py b/tests/test_install_sh_symlink_stomp.py
index 0fbe508509f..557e284e071 100644
--- a/tests/test_install_sh_symlink_stomp.py
+++ b/tests/test_install_sh_symlink_stomp.py
@@ -20,6 +20,8 @@ import stat
import subprocess
from pathlib import Path
+import pytest
+
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -57,6 +59,7 @@ def test_setup_path_shim_block_removes_old_link_before_writing() -> None:
)
def test_re_running_setup_path_block_preserves_pip_entry_point(tmp_path: Path) -> None:
"""Behavioral repro: simulate prior-install symlink + new-install heredoc.
diff --git a/tests/test_iron_proxy.py b/tests/test_iron_proxy.py
index cdd563041b7..149c27a02e3 100644
--- a/tests/test_iron_proxy.py
+++ b/tests/test_iron_proxy.py
@@ -341,6 +341,7 @@ def test_subprocess_env_strips_unrelated_secrets(hermes_home, monkeypatch):
# ---------------------------------------------------------------------------
def test_ca_key_created_with_0o600(hermes_home, monkeypatch):
"""The CA private key must NEVER exist on disk with default umask
permissions, even transiently. Fix: open with explicit mode=0o600
@@ -376,6 +377,7 @@ def test_ca_key_created_with_0o600(hermes_home, monkeypatch):
# ---------------------------------------------------------------------------
def test_ensure_audit_log_creates_with_0o600(hermes_home, tmp_path):
audit = tmp_path / "audit.log"
ip.ensure_audit_log(audit)
@@ -384,6 +386,7 @@ def test_ensure_audit_log_creates_with_0o600(hermes_home, tmp_path):
assert mode == 0o600
def test_ensure_audit_log_tightens_existing_perms(hermes_home, tmp_path):
audit = tmp_path / "audit.log"
audit.write_text("preexisting content\n")
@@ -398,6 +401,7 @@ def test_ensure_audit_log_tightens_existing_perms(hermes_home, tmp_path):
# ---------------------------------------------------------------------------
def test_proxy_state_dir_is_0o700(hermes_home):
state = ip._proxy_state_dir()
mode = state.stat().st_mode & 0o777
@@ -485,6 +489,7 @@ def test_mappings_roundtrip_preserves_headers_and_aliases(hermes_home):
def test_ensure_management_token_persists_and_is_stable(hermes_home):
t1 = ip.ensure_management_token()
t2 = ip.ensure_management_token()
@@ -539,6 +544,7 @@ def test_reload_proxy_posts_bearer_to_management_endpoint(hermes_home, monkeypat
assert captured["auth"] == f"Bearer {token}"
def test_start_proxy_injects_management_key_env(hermes_home, monkeypatch):
"""When the generated config has a management listener, start_proxy
must inject the bearer key env var — v0.39 refuses to start when
diff --git a/tests/test_live_system_guard_self_test.py b/tests/test_live_system_guard_self_test.py
index 40e9e6b5e1a..dfc06c7215d 100644
--- a/tests/test_live_system_guard_self_test.py
+++ b/tests/test_live_system_guard_self_test.py
@@ -105,6 +105,7 @@ def test_fail_closed_probe_classifies_raw_builtin_as_unguarded():
# ──────────────────── kill primitives ─────────────────────────
def test_os_kill_blocks_foreign_pid():
with pytest.raises(RuntimeError, match="live-system guard"):
os.kill(FOREIGN_PID, signal.SIGTERM)
@@ -218,6 +219,7 @@ def test_os_popen_systemctl_blocked():
# ──────────────────── pty.spawn ────────────────────────────────
def test_pty_spawn_systemctl_blocked():
import pty
with pytest.raises(RuntimeError, match="live-system guard"):
diff --git a/tests/test_plugin_skills.py b/tests/test_plugin_skills.py
index b2f49061fa3..b1747eadcb2 100644
--- a/tests/test_plugin_skills.py
+++ b/tests/test_plugin_skills.py
@@ -8,6 +8,8 @@ Covers:
import json
import logging
+import os
+import sys
import pytest
@@ -212,7 +214,7 @@ class TestSkillViewQualifiedName:
reference.write_text("API details.")
main = json.loads(skill_view("superpowers:writing-plans"))
- assert main["linked_files"] == {"references": ["references/api.md"]}
+ assert main["linked_files"] == {"references": [os.path.join("references", "api.md")]}
result = json.loads(
skill_view("superpowers:writing-plans", file_path="references/api.md")
)
@@ -222,11 +224,12 @@ class TestSkillViewQualifiedName:
def test_platform_gate_applies_before_supporting_file(self, tmp_path):
from tools.skills_tool import skill_view
+ other_platform = "linux" if sys.platform.startswith("win") else "windows"
md = self._register_skill(
tmp_path,
content=(
"---\nname: writing-plans\ndescription: desc\n"
- "platforms: [windows]\n---\nBody.\n"
+ f"platforms: [{other_platform}]\n---\nBody.\n"
),
)
reference = md.parent / "references" / "guide.md"
diff --git a/tests/test_profile_isolation_runtime.py b/tests/test_profile_isolation_runtime.py
index ffa75d943f2..1e0cfd73e8c 100644
--- a/tests/test_profile_isolation_runtime.py
+++ b/tests/test_profile_isolation_runtime.py
@@ -14,6 +14,7 @@ profile's path is used. They are the productionized form of the manual smoke
probes used to confirm the bug class.
"""
+import os
import threading
from pathlib import Path
@@ -108,7 +109,7 @@ class TestRichSentStorePathResolution:
b_seen = _under_override(prof_b, lambda: rss._store_path())
assert b_seen.startswith(str(prof_b))
- assert b_seen.endswith("state/rich_sent_index.json")
+ assert b_seen.endswith(os.path.join("state", "rich_sent_index.json"))
# ---------------------------------------------------------------------------
diff --git a/tests/test_resource_limits.py b/tests/test_resource_limits.py
index 6f24ce0e512..c3f8cbab855 100644
--- a/tests/test_resource_limits.py
+++ b/tests/test_resource_limits.py
@@ -249,6 +249,7 @@ def test_serve_startup_applies_limit_before_web_server(monkeypatch):
assert calls == ["limit", "server"]
def test_named_profile_reroute_defers_limit_to_final_process(monkeypatch, tmp_path):
"""The launcher profile must not leak its limit across machine re-exec."""
from hermes_cli import main as cli_main
diff --git a/tests/test_subprocess_home_isolation.py b/tests/test_subprocess_home_isolation.py
index 48bf1ed6526..2c016b864ef 100644
--- a/tests/test_subprocess_home_isolation.py
+++ b/tests/test_subprocess_home_isolation.py
@@ -107,8 +107,8 @@ class TestGetSubprocessHome:
assert home_a is not None
assert home_b is not None
assert home_a != home_b
- assert home_a.endswith("alpha/home")
- assert home_b.endswith("beta/home")
+ assert home_a.endswith(os.path.join("alpha", "home"))
+ assert home_b.endswith(os.path.join("beta", "home"))
diff --git a/tests/test_web_server.py b/tests/test_web_server.py
index ed81bce22ac..7ab1e7032b2 100644
--- a/tests/test_web_server.py
+++ b/tests/test_web_server.py
@@ -207,6 +207,7 @@ def test_start_server_runs_on_uvicorns_loop_factory(monkeypatch):
)
def test_start_server_keeps_bare_asyncio_run_on_posix(monkeypatch):
"""POSIX continues to serve via the plain ``asyncio.run(_serve())`` path,
never the Windows loop-factory branch.
diff --git a/tests/tools/test_approval.py b/tests/tools/test_approval.py
index 0d0a666bcbb..54091d473f3 100644
--- a/tests/tools/test_approval.py
+++ b/tests/tools/test_approval.py
@@ -99,6 +99,7 @@ class TestDetectDangerousRm:
assert "delete" in desc.lower()
+ @pytest.mark.linux_only
def test_nonrecursive_verification_artifact_cleanup_is_not_dangerous(self):
with mock_patch("tempfile.gettempdir", return_value="/tmp"):
for prefix in ("hermes-verify-", "hermes-ad-hoc-"):
@@ -108,6 +109,7 @@ class TestDetectDangerousRm:
None,
)
+ @pytest.mark.require_symlinks
def test_symlinked_temp_dir_only_exempts_canonical_target(self, tmp_path):
real_temp = tmp_path / "real-temp"
real_temp.mkdir()
diff --git a/tests/tools/test_approved_command_clean_slate.py b/tests/tools/test_approved_command_clean_slate.py
index 04a924fe57d..b9b087eda2b 100644
--- a/tests/tools/test_approved_command_clean_slate.py
+++ b/tests/tools/test_approved_command_clean_slate.py
@@ -86,6 +86,7 @@ def test_non_approved_command_still_interrupts_on_stale_bit(monkeypatch):
assert "[Command interrupted]" in result["output"]
def test_approved_command_genuine_interrupt_after_start_still_kills(tmp_path):
"""The clean-slate clear must NOT make approved commands un-interruptible:
an interrupt that arrives after execution starts still SIGINTs (130)."""
@@ -112,6 +113,7 @@ def test_approved_command_genuine_interrupt_after_start_still_kills(tmp_path):
set_interrupt(False, thread_id=t.ident)
def test_approved_note_enriched_not_misleading_on_interrupt(monkeypatch, tmp_path):
"""On a genuine post-start interrupt of an approved command, the note must
read '...approved by the user, then interrupted.' — the bare
diff --git a/tests/tools/test_base_environment.py b/tests/tools/test_base_environment.py
index cb883ea5c48..759aa504ab8 100644
--- a/tests/tools/test_base_environment.py
+++ b/tests/tools/test_base_environment.py
@@ -3,6 +3,7 @@
Tests _wrap_command(), _extract_cwd_from_output(), _embed_stdin_heredoc(),
init_session() failure handling, and the CWD marker contract.
"""
+import pytest
from unittest.mock import MagicMock
@@ -190,6 +191,7 @@ class TestAtomicSnapshotConcurrencyBehavioral:
import subprocess
return subprocess.run(["/bin/bash", "-c", script], capture_output=True, text=True)
+ @pytest.mark.linux_only
def test_concurrent_writes_never_tear_the_snapshot(self, tmp_path):
import shutil
if not shutil.which("bash"):
@@ -227,6 +229,7 @@ class TestAtomicSnapshotConcurrencyBehavioral:
final = self._run(f"source {_q(snap)} >/dev/null 2>&1 && echo OK || echo BROKEN")
assert "OK" in final.stdout, f"final snapshot not sourceable: {final.stdout} {final.stderr}"
+ @pytest.mark.linux_only
def test_failed_export_does_not_destroy_good_snapshot(self, tmp_path):
"""If ``export -p`` fails, the ``&&``-chained mv must NOT clobber the
existing good snapshot."""
@@ -254,6 +257,7 @@ class TestAtomicSnapshotConcurrencyBehavioral:
class TestSnapshotFileModes:
"""Snapshot metadata files are private without changing user command umask."""
+ @pytest.mark.linux_only
def test_snapshot_and_cwd_files_are_0600(self, tmp_path):
import os
from pathlib import Path
diff --git a/tests/tools/test_bot_mode_dm.py b/tests/tools/test_bot_mode_dm.py
index e83ec30ae07..10cb5a372c6 100644
--- a/tests/tools/test_bot_mode_dm.py
+++ b/tests/tools/test_bot_mode_dm.py
@@ -666,6 +666,7 @@ def test_sweeper_removes_only_stale_dm_files(tmp_path, monkeypatch):
assert unrelated.exists()
def test_dm_dir_is_private_and_uid_scoped_on_posix(tmp_path, monkeypatch):
monkeypatch.setattr(bot_mode_dm.tempfile, "gettempdir", lambda: str(tmp_path))
@@ -678,6 +679,7 @@ def test_dm_dir_is_private_and_uid_scoped_on_posix(tmp_path, monkeypatch):
assert dm_dir.stat().st_mode & 0o777 == 0o700
def test_dm_dir_repairs_restrictive_owner_mode(tmp_path, monkeypatch):
monkeypatch.setattr(bot_mode_dm.tempfile, "gettempdir", lambda: str(tmp_path))
uid = os.getuid() if hasattr(os, "getuid") else None
diff --git a/tests/tools/test_bot_relay_windows_paths.py b/tests/tools/test_bot_relay_windows_paths.py
index e6123a7371f..fdb6a812e6f 100644
--- a/tests/tools/test_bot_relay_windows_paths.py
+++ b/tests/tools/test_bot_relay_windows_paths.py
@@ -28,6 +28,7 @@ from pathlib import Path
import tools.bot_mode_dm as bot_mode_dm
import tools.bot_relay as bot_relay
+import pytest
ENV = {"id": "d" * 32, "target_handle": "researcher", "target_connection": "ssh-vps"}
@@ -50,6 +51,7 @@ def test_waiter_windows_path_compiles_after_backslash_folding():
compile(folded, "<waiter>", "exec")
def test_waiter_posix_path_and_label_values_roundtrip():
"""On POSIX (backslash-free paths) the raw prefix changes nothing."""
root = Path("/tmp/hermes-home")
@@ -88,6 +90,7 @@ def test_waiter_raw_prefix_keeps_injection_defense():
assert "x'); __import__('sys').exit(2); print('x" in code
def test_local_delivery_resolves_sibling_hermes(tmp_path, monkeypatch):
bin_dir = tmp_path / "venv" / "bin"
bin_dir.mkdir(parents=True)
diff --git a/tests/tools/test_bot_turn_lock.py b/tests/tools/test_bot_turn_lock.py
index 1b02ae6febf..25e0fd72794 100644
--- a/tests/tools/test_bot_turn_lock.py
+++ b/tests/tools/test_bot_turn_lock.py
@@ -9,7 +9,10 @@ process, so threads exercise the true kernel-lock semantics.
from __future__ import annotations
-import fcntl
+try:
+ import fcntl # POSIX-only; on Windows the module is skipped wholesale
+except ImportError: # pragma: no cover - Windows
+ fcntl = None
import json
import os
import re
@@ -18,6 +21,8 @@ import time
import pytest
+pytestmark = pytest.mark.linux_only
+
from tools import bot_mode_dm, bot_relay
from tools.bot_relay import TurnBusyError, acquire_turn_lock, turn_lock_path
diff --git a/tests/tools/test_browser_hardening.py b/tests/tools/test_browser_hardening.py
index 6ad1e9f5daf..c67d68abc78 100644
--- a/tests/tools/test_browser_hardening.py
+++ b/tests/tools/test_browser_hardening.py
@@ -229,6 +229,7 @@ class TestTruncateSnapshot:
content = Path(stored).read_text(encoding="utf-8")
assert "STOREDSNAPSHOTSECRET" not in content
+ @pytest.mark.require_symlinks
def test_stored_snapshot_refuses_planted_symlink(self, tmp_path, monkeypatch):
"""A pre-planted symlink at the content-hash path must not be
followed to its target — only the link itself may be replaced.
diff --git a/tests/tools/test_browser_homebrew_paths.py b/tests/tools/test_browser_homebrew_paths.py
index 13669f1fe97..578e9bb7989 100644
--- a/tests/tools/test_browser_homebrew_paths.py
+++ b/tests/tools/test_browser_homebrew_paths.py
@@ -406,6 +406,7 @@ class TestRunBrowserCommandPathConstruction:
]
assert captured_cmd[5:9] == ["--session", "test-session", "--json", "navigate"]
+ @pytest.mark.linux_only
def test_subprocess_path_includes_termux_fallback_dirs(self, tmp_path):
"""Termux fallback dirs should survive browser PATH rebuilding."""
captured_env = {}
diff --git a/tests/tools/test_browser_npx_warmup.py b/tests/tools/test_browser_npx_warmup.py
index b866c43073f..37fe84b4375 100644
--- a/tests/tools/test_browser_npx_warmup.py
+++ b/tests/tools/test_browser_npx_warmup.py
@@ -18,6 +18,8 @@ from __future__ import annotations
import subprocess
from unittest.mock import MagicMock, patch
+import pytest
+
from tools.browser_tool import (
AGENT_BROWSER_NPX_SPEC,
_legacy_kill_process_tree,
@@ -123,6 +125,7 @@ def test_merges_extended_path_so_managed_only_npx_can_find_sibling_node():
assert kwargs["env"]["PATH"] == "/opt/hermes/node/bin:/usr/bin"
def test_runs_in_its_own_process_group_on_posix(monkeypatch):
monkeypatch.setattr("os.name", "posix")
with patch("tools.browser_tool._resolve_npx_bin", return_value="/usr/bin/npx"), \
@@ -216,6 +219,7 @@ def test_returns_false_instead_of_raising_on_unexpected_communicate_exception():
mock_kill.assert_called_once_with(proc)
class TestLegacyKillProcessTree:
"""Contract of the pre-#85125 local fallback (used when agent.deadline
delegation fails); the delegating wrapper is covered in
diff --git a/tests/tools/test_browser_use_cli.py b/tests/tools/test_browser_use_cli.py
index efcbfe5ebad..c8b3f7c0e5b 100644
--- a/tests/tools/test_browser_use_cli.py
+++ b/tests/tools/test_browser_use_cli.py
@@ -348,6 +348,7 @@ class TestLegacyCloudMigration:
monkeypatch.setattr(bu_cli, "_find_cli", lambda: None)
assert bu_cli.is_browser_use_cli_mode() is False
+ @pytest.mark.linux_only
def test_migrated_config_gets_bu_autospawn(self, tmp_path, monkeypatch):
monkeypatch.setattr("hermes_cli.config.read_raw_config", lambda: self._LEGACY)
monkeypatch.setenv("BROWSER_USE_API_KEY", "bu-key")
@@ -356,6 +357,7 @@ class TestLegacyCloudMigration:
result = json.loads(bu_cli.browser_exec("print(1)"))
assert "autospawn:1" in result["output"]
+ @pytest.mark.linux_only
def test_explicit_backend_does_not_set_bu_autospawn(self, tmp_path, monkeypatch):
monkeypatch.setattr(
"hermes_cli.config.read_raw_config",
@@ -449,6 +451,7 @@ class TestBackendCdpResolution:
err = bu_cli._resolve_backend_cdp(self._env(), "t1")
assert err and "no" in err.lower() and "CDP" in err
+ @pytest.mark.linux_only
def test_named_session_composes_with_provider_backend(self, tmp_path, monkeypatch):
"""session=<name> composes with a configured provider backend: the
name keys its OWN provider browser (bu-named-<name>), so concurrent
@@ -534,6 +537,7 @@ class TestOwnTabPreamble:
monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])
return json.loads(bu_cli.browser_exec("print('payload')", session=session))
+ @pytest.mark.linux_only
def test_named_shared_browser_gets_preamble(self, tmp_path, monkeypatch):
result = self._run(tmp_path, monkeypatch, session="r7k2")
assert result["success"] is True
@@ -541,17 +545,20 @@ class TestOwnTabPreamble:
# model code still present, after the preamble
assert result["output"].index("_hermes_ensure_own_tab") < result["output"].index("print('payload')")
+ @pytest.mark.linux_only
def test_unnamed_session_gets_no_preamble(self, tmp_path, monkeypatch):
result = self._run(tmp_path, monkeypatch, session="")
assert result["success"] is True
assert "_hermes_ensure_own_tab" not in result["output"]
+ @pytest.mark.linux_only
def test_named_provider_browser_skips_preamble(self, tmp_path, monkeypatch):
"""Per-name provider browsers are private — preamble would leak a tab."""
result = self._run(tmp_path, monkeypatch, session="r7k2", provider=True)
assert result["success"] is True
assert "_hermes_ensure_own_tab" not in result["output"]
+ @pytest.mark.linux_only
def test_sentinel_never_reaches_subprocess_env(self, tmp_path, monkeypatch):
import tools.browser_tool as bt
@@ -713,6 +720,7 @@ class TestNativeScreenshots:
out = f"{stale}\n/nonexistent/dir/x.png\n"
assert bu_cli._find_screenshot(out, since=time.time()) is None
+ @pytest.mark.linux_only
def test_vision_model_gets_multimodal_envelope(self, tmp_path, monkeypatch):
shot = self._shot(tmp_path)
cli = _fake_cli(tmp_path, f'cat > /dev/null\necho "{shot}"\n')
@@ -731,6 +739,7 @@ class TestNativeScreenshots:
assert result["meta"]["screenshot_path"] == shot
assert shot in result["text_summary"]
+ @pytest.mark.linux_only
def test_text_only_model_gets_plain_result_with_path(self, tmp_path, monkeypatch):
shot = self._shot(tmp_path)
cli = _fake_cli(tmp_path, f'cat > /dev/null\necho "{shot}"\n')
@@ -851,6 +860,7 @@ class TestBrowserExec:
result = json.loads(bu_cli.browser_exec(" "))
assert "error" in result
+ @pytest.mark.linux_only
def test_code_piped_on_stdin(self, tmp_path, monkeypatch):
cli = _fake_cli(tmp_path, 'code=$(cat)\necho "got:$code"\n')
monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])
@@ -860,6 +870,7 @@ class TestBrowserExec:
assert 'got:print("hi")' in result["output"]
assert "session" not in result
+ @pytest.mark.linux_only
def test_session_sets_bu_name(self, tmp_path, monkeypatch):
cli = _fake_cli(tmp_path, 'cat > /dev/null\necho "bu:$BU_NAME"\n')
monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])
@@ -874,6 +885,7 @@ class TestBrowserExec:
assert "error" in result
assert "session" in result["error"].lower()
+ @pytest.mark.linux_only
def test_nonzero_exit_reports_failure_and_stderr(self, tmp_path, monkeypatch):
cli = _fake_cli(tmp_path, 'cat > /dev/null\necho "boom" >&2\nexit 3\n')
monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])
@@ -882,6 +894,7 @@ class TestBrowserExec:
assert result["exit_code"] == 3
assert "boom" in result["stderr"]
+ @pytest.mark.linux_only
def test_timeout_returns_actionable_error(self, tmp_path, monkeypatch):
cli = _fake_cli(tmp_path, "cat > /dev/null\nsleep 30\n")
monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])
@@ -902,6 +915,7 @@ class TestFindCliManagedBin:
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
monkeypatch.setenv("PATH", str(tmp_path / "empty"))
+ @pytest.mark.linux_only
def test_managed_bin_browser_use_found(self, tmp_path, monkeypatch):
bin_dir = tmp_path / "home" / "bin"
bin_dir.mkdir(parents=True)
@@ -910,6 +924,7 @@ class TestFindCliManagedBin:
bu.chmod(bu.stat().st_mode | stat.S_IXUSR)
assert bu_cli._find_cli_unpatched() == [str(bu)]
+ @pytest.mark.linux_only
def test_managed_bin_uvx_fallback(self, tmp_path, monkeypatch):
bin_dir = tmp_path / "home" / "bin"
bin_dir.mkdir(parents=True)
@@ -921,6 +936,7 @@ class TestFindCliManagedBin:
def test_nothing_found(self, tmp_path, monkeypatch):
assert bu_cli._find_cli_unpatched() is None
+ @pytest.mark.linux_only
def test_user_local_bin_browser_use_found(self, tmp_path, monkeypatch):
"""#83788: Desktop/TUI workers spawn with a minimal PATH that omits
~/.local/bin, where `uv tool install browser-use` links the binary
@@ -932,6 +948,7 @@ class TestFindCliManagedBin:
cli.chmod(cli.stat().st_mode | stat.S_IXUSR)
assert bu_cli._find_cli_unpatched() == [str(cli)]
+ @pytest.mark.linux_only
def test_managed_bin_precedes_user_local_bin(self, tmp_path, monkeypatch):
"""MANAGED-FIRST: Hermes' managed copy wins over a user-level side
install — every backend selection provisions/updates the managed
@@ -949,6 +966,7 @@ class TestFindCliManagedBin:
managed_cli.chmod(managed_cli.stat().st_mode | stat.S_IXUSR)
assert bu_cli._find_cli_unpatched() == [str(managed_cli)]
+ @pytest.mark.linux_only
def test_managed_bin_precedes_path(self, tmp_path, monkeypatch):
"""MANAGED-FIRST: the managed copy also wins over one on PATH."""
path_dir = tmp_path / "onpath"
@@ -964,6 +982,7 @@ class TestFindCliManagedBin:
managed_cli.chmod(managed_cli.stat().st_mode | stat.S_IXUSR)
assert bu_cli._find_cli_unpatched() == [str(managed_cli)]
+ @pytest.mark.linux_only
def test_user_local_bin_uvx_fallback(self, tmp_path, monkeypatch):
cli_dir = tmp_path / "userhome" / ".local" / "bin"
cli_dir.mkdir(parents=True)
@@ -992,6 +1011,7 @@ class TestInstallCli:
assert ok is False
assert "already installed" not in msg
+ @pytest.mark.linux_only
def test_already_installed_in_managed_bin(self, tmp_path, monkeypatch):
bin_dir = tmp_path / "home" / "bin"
bin_dir.mkdir(parents=True)
@@ -1016,6 +1036,7 @@ class TestInstallCli:
assert ok is False
assert "uv" in msg
+ @pytest.mark.linux_only
def test_successful_install_via_fake_uv(self, tmp_path, monkeypatch):
home = tmp_path / "home"
bin_dir = home / "bin"
@@ -1044,6 +1065,7 @@ class TestInstallCli:
assert ok is True, msg
assert (bin_dir / "browser-use").exists()
+ @pytest.mark.linux_only
def test_failed_install_surfaces_stderr_tail(self, tmp_path, monkeypatch):
home = tmp_path / "home"
monkeypatch.setenv("HERMES_HOME", str(home))
diff --git a/tests/tools/test_checkpoint_manager.py b/tests/tools/test_checkpoint_manager.py
index 67cdaac9f64..4eaa0992ccb 100644
--- a/tests/tools/test_checkpoint_manager.py
+++ b/tests/tools/test_checkpoint_manager.py
@@ -650,7 +650,7 @@ class TestGitEnvIsolation:
env = _git_env(
store, str(work), index_file=store / "indexes" / "abc",
)
- assert env["GIT_INDEX_FILE"].endswith("indexes/abc")
+ assert env["GIT_INDEX_FILE"].endswith(os.path.join("indexes", "abc"))
# ~ in the work tree is expanded.
tilde_work = fake_home / "work"
diff --git a/tests/tools/test_code_execution.py b/tests/tools/test_code_execution.py
index 66ed46a6866..7fe33261c52 100644
--- a/tests/tools/test_code_execution.py
+++ b/tests/tools/test_code_execution.py
@@ -905,6 +905,7 @@ class TestRpcTokenAuthorization(unittest.TestCase):
t.join(timeout=5)
return responses
+ @pytest.mark.linux_only
def test_missing_token_rejected(self):
"""A request with no token is rejected as Unauthorized."""
resp = self._drive_server(
diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.py
index 0ac3fed17e7..44e9b970c7b 100644
--- a/tests/tools/test_computer_use.py
+++ b/tests/tools/test_computer_use.py
@@ -1409,8 +1409,11 @@ class TestCuaDriverSessionReconnect:
returncode = 0
stderr = ""
# Daemon returns a path, not inline base64.
- stdout = ('{"element_count": 7, "tree_markdown": "- [0] AXButton",'
- ' "screenshot_file_path": "%s"}' % str(shot))
+ stdout = json.dumps({
+ "element_count": 7,
+ "tree_markdown": "- [0] AXButton",
+ "screenshot_file_path": str(shot),
+ })
import subprocess as _sp
orig_run = _sp.run
diff --git a/tests/tools/test_credential_files.py b/tests/tools/test_credential_files.py
index cb48d2a7217..11e04b8bcba 100644
--- a/tests/tools/test_credential_files.py
+++ b/tests/tools/test_credential_files.py
@@ -87,6 +87,7 @@ class TestSkillsDirectoryMount:
assert mounts[0]["container_path"] == "/home/user/.hermes/skills"
+ @pytest.mark.require_symlinks
def test_symlinks_are_sanitized(self, tmp_path):
"""Symlinks in skills dir should be excluded from the mount."""
hermes_home = tmp_path / ".hermes"
@@ -126,6 +127,7 @@ class TestSkillsDirectoryMount:
class TestIterSkillsFiles:
+ @pytest.mark.require_symlinks
def test_returns_files_skipping_symlinks(self, tmp_path):
hermes_home = tmp_path / ".hermes"
skills_dir = hermes_home / "skills"
@@ -490,6 +492,7 @@ class TestIterCacheFiles:
assert "upload.zip" in names
assert "report.pdf" in names
+ @pytest.mark.require_symlinks
def test_skips_symlinks(self, tmp_path, monkeypatch):
"""Symlinks inside cache dirs are skipped."""
hermes_home = tmp_path / ".hermes"
diff --git a/tests/tools/test_docker_environment.py b/tests/tools/test_docker_environment.py
index 54082f6ed15..e92a005b7b9 100644
--- a/tests/tools/test_docker_environment.py
+++ b/tests/tools/test_docker_environment.py
@@ -620,6 +620,7 @@ def _bind_mount_specs(run_args):
]
def test_persistent_bind_mounts_survive_a_session_key_task_id(monkeypatch, tmp_path):
"""A gateway session key reaches the persistent sandbox path as-is, and it
carries colons (``session:agent:main:telegram:dm:<chat_id>``). Docker reads
diff --git a/tests/tools/test_execution_flag_detection.py b/tests/tools/test_execution_flag_detection.py
index 65c1aeeb493..7cd9cc9c6a6 100644
--- a/tests/tools/test_execution_flag_detection.py
+++ b/tests/tools/test_execution_flag_detection.py
@@ -19,6 +19,7 @@ from tools.approval import detect_dangerous_command, detect_hardline_command
(["rg", "--pre-glob", "--pre", "needle"], "needle\n", 0, "needle\n"),
],
)
def test_real_read_tool_binaries_confirm_option_ownership(
argv, stdin, expected_returncode, expected_output
):
@@ -43,6 +44,7 @@ def test_real_read_tool_binaries_confirm_option_ownership(
("man", ["-P", "-payload-marker", "ls"], None, True),
],
)
def test_real_binaries_execute_leading_dash_program_payload(
tmp_path, tool, args, stdin, needs_tty
):
diff --git a/tests/tools/test_file_operations.py b/tests/tools/test_file_operations.py
index 9af6dcb73e1..c596faf9d48 100644
--- a/tests/tools/test_file_operations.py
+++ b/tests/tools/test_file_operations.py
@@ -439,6 +439,7 @@ class TestSearchFilesFallbackHiddenPaths:
def _make_env(self):
return make_real_subprocess_env("/")
+ @pytest.mark.linux_only
def test_hidden_root_with_hidden_ancestor_includes_files(self, tmp_path, monkeypatch):
"""Fallback find should include visible files when path is inside hidden root."""
root = tmp_path / ".hermes" / "logs"
@@ -459,6 +460,7 @@ class TestSearchFilesFallbackHiddenPaths:
assert result.error is None
assert set(result.files) == {str(visible_file), str(visible_nested_file)}
+ @pytest.mark.linux_only
def test_normal_root_still_excludes_hidden_descendants(self, tmp_path, monkeypatch):
"""Fallback find should still exclude hidden descendant paths for normal roots."""
root = tmp_path / "repo"
@@ -590,6 +592,7 @@ class TestAtomicWriteNewFilePermissions:
"""_atomic_write should apply umask-default perms to new files (not 0600)."""
@pytest.mark.parametrize("test_umask", [0o022, 0o002, 0o077])
+ @pytest.mark.linux_only
def test_new_file_gets_umask_default_permissions(self, tmp_path, test_umask):
"""Newly created file should get umask-computed perms, not mktemp's 0600.
@@ -614,6 +617,7 @@ class TestAtomicWriteNewFilePermissions:
f"got {actual_mode:04o}"
)
+ @pytest.mark.linux_only
def test_overwrite_still_preserves_existing_mode(self, tmp_path):
"""The new-file branch must not disturb the overwrite path's
mode preservation (e.g. an executable script stays 0755)."""
@@ -636,6 +640,7 @@ class TestAtomicWriteThroughSymlink:
plain file, orphaning the real target and destroying the link (data-loss).
"""
+ @pytest.mark.require_symlinks
def test_write_follows_symlink_and_preserves_link(self, tmp_path):
ops = ShellFileOperations(make_real_subprocess_env(str(tmp_path)))
real = tmp_path / "real.txt"
@@ -652,6 +657,7 @@ class TestAtomicWriteThroughSymlink:
assert real.read_text() == "newcontent\n"
assert os.path.realpath(link) == str(real)
+ @pytest.mark.require_symlinks
def test_write_through_broken_symlink_falls_back(self, tmp_path):
"""A broken link resolves through readlink -f and creates the target."""
ops = ShellFileOperations(make_real_subprocess_env(str(tmp_path)))
diff --git a/tests/tools/test_file_ops_cwd_tracking.py b/tests/tools/test_file_ops_cwd_tracking.py
index 53ea596b771..13ef03c997a 100644
--- a/tests/tools/test_file_ops_cwd_tracking.py
+++ b/tests/tools/test_file_ops_cwd_tracking.py
@@ -14,9 +14,10 @@ the patch landed in a different directory's copy of the same file).
Fix: _exec() now prefers the LIVE ``env.cwd`` over the init-time
``self.cwd``. Explicit ``cwd`` arg to _exec still wins over both.
"""
-
from __future__ import annotations
+import pytest
+
from tools.file_operations import ShellFileOperations
@@ -106,6 +107,7 @@ class TestShellFileOpsCwdTracking:
assert result.exit_code == 0
assert "fixed-content" in result.stdout
+ @pytest.mark.linux_only
def test_patch_returns_success_only_when_file_actually_written(self, tmp_path):
"""Safety rail: patch_replace success must reflect the real file state.
diff --git a/tests/tools/test_file_read_guards.py b/tests/tools/test_file_read_guards.py
index 1ee28f77892..4d154615152 100644
--- a/tests/tools/test_file_read_guards.py
+++ b/tests/tools/test_file_read_guards.py
@@ -6,6 +6,7 @@ context compression.
Run with: python -m pytest tests/tools/test_file_read_guards.py -v
"""
+import pytest
import json
import os
@@ -66,6 +67,7 @@ def _make_safe_tempdir(prefix: str) -> str:
class TestDevicePathBlocking(unittest.TestCase):
"""Paths like /dev/zero should be rejected before any I/O."""
+ @pytest.mark.linux_only
def test_blocked_device_detection(self):
for dev in ("/dev/zero", "/dev/random", "/dev/urandom", "/dev/stdin",
"/dev/tty", "/dev/console", "/dev/stdout", "/dev/stderr",
@@ -76,6 +78,7 @@ class TestDevicePathBlocking(unittest.TestCase):
self.assertFalse(_is_blocked_device("/dev/null"))
self.assertFalse(_is_blocked_device("/dev/sda1"))
+ @pytest.mark.linux_only
def test_proc_fd_blocked(self):
self.assertTrue(_is_blocked_device("/proc/self/fd/0"))
self.assertTrue(_is_blocked_device("/proc/12345/fd/2"))
@@ -92,6 +95,7 @@ class TestDevicePathBlocking(unittest.TestCase):
self.assertFalse(_is_blocked_device_path("/proc/self/fd/3"))
+ @pytest.mark.linux_only
def test_proc_sensitive_pseudo_files_blocked(self):
"""environ/cmdline/maps (and maps variants) under /proc/<pid> must be blocked (issue #4427)."""
for path in (
@@ -116,6 +120,7 @@ class TestDevicePathBlocking(unittest.TestCase):
):
self.assertTrue(_is_blocked_device(path), f"{path} should be blocked")
+ @pytest.mark.linux_only
def test_proc_task_thread_sensitive_files_blocked(self):
"""Per-thread /proc/<pid>/task/<tid>/<file> aliases leak the same data."""
for path in (
@@ -132,6 +137,7 @@ class TestDevicePathBlocking(unittest.TestCase):
for path in ("/proc/cpuinfo", "/proc/meminfo", "/proc/uptime", "/proc/version"):
self.assertFalse(_is_blocked_device(path), f"{path} should not be blocked")
+ @pytest.mark.linux_only
def test_normpath_alias_to_blocked_device_is_blocked(self):
self.assertTrue(_is_blocked_device("/dev/../dev/zero"))
self.assertTrue(_is_blocked_device("/dev/./urandom"))
@@ -162,6 +168,7 @@ class TestDevicePathBlocking(unittest.TestCase):
self.assertFalse(_is_blocked_device(link_path))
+ @pytest.mark.linux_only
def test_read_file_tool_rejects_device(self):
"""read_file_tool returns an error without any file I/O."""
result = json.loads(read_file_tool("/dev/zero", task_id="dev_test"))
diff --git a/tests/tools/test_file_sync.py b/tests/tools/test_file_sync.py
index 9ecabdb21bc..7514ee7aab6 100644
--- a/tests/tools/test_file_sync.py
+++ b/tests/tools/test_file_sync.py
@@ -264,6 +264,7 @@ class TestEdgeCases:
class TestConcurrency:
+ @pytest.mark.linux_only
def test_sync_back_waits_for_active_sync_transaction(self, tmp_path):
initial_file = tmp_path / "initial.png"
new_file = tmp_path / "new.png"
@@ -317,6 +318,7 @@ class TestConcurrency:
class TestSyncBackSecurity:
+ @pytest.mark.linux_only
def test_sync_back_does_not_overwrite_uploaded_credential_files(self, tmp_path, monkeypatch):
credential = tmp_path / "token.json"
credential.write_text("host-token", encoding="utf-8")
diff --git a/tests/tools/test_file_tools.py b/tests/tools/test_file_tools.py
index 58fb91ac2b1..c234b759a6a 100644
--- a/tests/tools/test_file_tools.py
+++ b/tests/tools/test_file_tools.py
@@ -44,6 +44,7 @@ class TestReadFileHandler:
class TestWriteFileHandler:
@patch("tools.file_tools._get_file_ops")
+ @pytest.mark.linux_only
def test_writes_content(self, mock_get):
mock_ops = MagicMock()
result_obj = MagicMock()
@@ -132,6 +133,7 @@ class TestWriteFileHandler:
class TestPatchHandler:
@patch("tools.file_tools._get_file_ops")
+ @pytest.mark.linux_only
def test_replace_mode_calls_patch_replace(self, mock_get):
mock_ops = MagicMock()
result_obj = MagicMock()
@@ -225,6 +227,7 @@ class TestPatchSensitivePathExtraction:
"""
@patch("tools.file_tools._get_file_ops")
+ @pytest.mark.linux_only
def test_patch_move_to_sensitive_dst_blocked(self, mock_get):
from tools.file_tools import patch_tool
patch_text = (
@@ -239,6 +242,7 @@ class TestPatchSensitivePathExtraction:
@patch("tools.file_tools._get_file_ops")
+ @pytest.mark.linux_only
def test_patch_update_no_space_after_asterisks_blocked(self, mock_get):
"""``***Update File:`` (no space after asterisks) must also be caught.
@@ -455,6 +459,7 @@ class TestSensitivePathCheck:
assert "Hermes config" in result["error"]
+ @pytest.mark.linux_only
def test_system_path_still_blocked(self, monkeypatch):
monkeypatch.setattr("tools.file_tools._hermes_config_resolved", "/some/other/path")
monkeypatch.setattr("tools.file_tools._hermes_config_resolved_loaded", True)
@@ -464,6 +469,7 @@ class TestSensitivePathCheck:
assert "error" in result
assert "sensitive system path" in result["error"]
+ @pytest.mark.linux_only
def test_macos_private_var_carveouts(self):
"""macOS temp dirs under /private/var must not be blanket-blocked,
while the genuinely-sensitive /private/var subtrees still are."""
diff --git a/tests/tools/test_file_tools_cwd_resolution.py b/tests/tools/test_file_tools_cwd_resolution.py
index 28f7ac5f5d8..834f2500e8f 100644
--- a/tests/tools/test_file_tools_cwd_resolution.py
+++ b/tests/tools/test_file_tools_cwd_resolution.py
@@ -89,6 +89,7 @@ def test_absolute_terminal_cwd_used_verbatim(_isolated_cwd, monkeypatch):
assert resolved == (workspace / "target.py")
def test_container_absolute_input_path_does_not_follow_host_symlink(tmp_path, monkeypatch):
"""Docker paths are sandbox-local and must not be host-dereferenced.
@@ -118,6 +119,7 @@ def test_container_path_normalization_uses_posix_path_syntax():
assert str(resolved) == "/workspace/projects/bar"
def test_container_relative_path_keeps_container_cwd_symlink(tmp_path, monkeypatch):
"""Relative Docker paths should stay under the container cwd textually."""
host_project = tmp_path / "host-project"
@@ -166,8 +168,11 @@ def test_warning_fires_when_relative_path_escapes_workspace(_isolated_cwd, monke
assert warn is not None
assert "OUTSIDE the active workspace" in warn
- assert str(decoy) in warn
- assert str(workspace) in warn
+ # Paths are repr-embedded in the message, so backslashes arrive doubled
+ # on Windows; un-escape before the containment check (host-aware).
+ warn_flat = warn.replace("\\\\", "\\")
+ assert str(decoy) in warn_flat
+ assert str(workspace) in warn_flat
# ── Fix C: sentinel TERMINAL_CWD + empty-registry worktree anchoring ─────────
@@ -199,7 +204,7 @@ def test_warning_fires_from_terminal_cwd_when_registry_empty(_isolated_cwd, monk
assert warn is not None
assert "OUTSIDE the active workspace" in warn
- assert str(workspace) in warn
+ assert str(workspace) in warn.replace("\\\\", "\\")
# ── Fix A: write_file / patch report the resolved ABSOLUTE path ──────────────
diff --git a/tests/tools/test_file_tools_live.py b/tests/tools/test_file_tools_live.py
index 81a11c061ad..b67ae5e935c 100644
--- a/tests/tools/test_file_tools_live.py
+++ b/tests/tools/test_file_tools_live.py
@@ -98,6 +98,7 @@ class TestLocalEnvironmentExecute:
_assert_clean(result["output"])
+ @pytest.mark.linux_only
def test_cat_deterministic_content(self, env, tmp_path):
f = tmp_path / "det.txt"
f.write_text(SIMPLE_CONTENT)
@@ -225,6 +226,7 @@ class TestSearch:
# ── _expand_path ─────────────────────────────────────────────────────────
class TestExpandPath:
+ @pytest.mark.linux_only
def test_tilde_exact(self, ops):
result = ops._expand_path("~/test.txt")
expected = f"{Path.home()}/test.txt"
@@ -261,6 +263,7 @@ class TestTerminalOutputCleanliness:
assert result["output"].strip() == "CLEAN_TEST"
_assert_clean(result["output"])
+ @pytest.mark.linux_only
def test_cat(self, env, tmp_path):
f = tmp_path / "cat_test.txt"
f.write_text("CAT_CONTENT_EXACT\n")
diff --git a/tests/tools/test_file_tools_tilde_profile.py b/tests/tools/test_file_tools_tilde_profile.py
index 23510b1f9ae..40bfa6b61a2 100644
--- a/tests/tools/test_file_tools_tilde_profile.py
+++ b/tests/tools/test_file_tools_tilde_profile.py
@@ -31,6 +31,7 @@ import tools.terminal_tool as terminal_tool
class TestExpandTilde:
"""Verify the _expand_tilde() helper resolves ~ to the profile home."""
+ @pytest.mark.linux_only
def test_tilde_expands_to_profile_home(self):
"""When get_subprocess_home returns a value, ~/path uses it."""
with patch("hermes_constants.get_subprocess_home", return_value="/opt/data/profiles/coder/home"):
diff --git a/tests/tools/test_file_write_safety.py b/tests/tools/test_file_write_safety.py
index fc92b55b09e..866882769a8 100644
--- a/tests/tools/test_file_write_safety.py
+++ b/tests/tools/test_file_write_safety.py
@@ -232,22 +232,27 @@ class TestSafeRootDenialMessageIntegration:
class TestCheckSensitivePathMacOSBypass:
"""Verify _check_sensitive_path blocks /private/etc paths (issue #8734)."""
+ @pytest.mark.linux_only
def test_etc_hosts_blocked(self):
from tools.file_tools import _check_sensitive_path
assert _check_sensitive_path("/etc/hosts") is not None
+ @pytest.mark.linux_only
def test_private_etc_hosts_blocked(self):
from tools.file_tools import _check_sensitive_path
assert _check_sensitive_path("/private/etc/hosts") is not None
+ @pytest.mark.linux_only
def test_private_etc_ssh_config_blocked(self):
from tools.file_tools import _check_sensitive_path
assert _check_sensitive_path("/private/etc/ssh/sshd_config") is not None
+ @pytest.mark.linux_only
def test_private_var_blocked(self):
from tools.file_tools import _check_sensitive_path
assert _check_sensitive_path("/private/var/db/something") is not None
+ @pytest.mark.linux_only
def test_boot_still_blocked(self):
from tools.file_tools import _check_sensitive_path
assert _check_sensitive_path("/boot/grub/grub.cfg") is not None
@@ -291,6 +296,7 @@ class TestAtomicWrite:
assert [p for p in os.listdir(tmp_path) if ".hermes-tmp" in p] == []
+ @pytest.mark.linux_only
def test_patch_routes_through_atomic_write(self, ops, tmp_path: Path):
target = tmp_path / "edit.py"
target.write_text("a = 1\nb = 2\nc = 3\n", encoding="utf-8")
@@ -508,6 +514,7 @@ class TestProtectedInstructionFiles:
# ---- adversarial path shapes ----------------------------------------
+ @pytest.mark.require_symlinks
def test_symlink_to_protected_file_is_gated(self, tmp_path, approvals):
"""#41351 lesson: realpath first — innocent name, protected target."""
real = tmp_path / "AGENTS.md"
diff --git a/tests/tools/test_find_shell.py b/tests/tools/test_find_shell.py
index e84fdef0ce1..0baab55e325 100644
--- a/tests/tools/test_find_shell.py
+++ b/tests/tools/test_find_shell.py
@@ -18,6 +18,7 @@ from tools.environments.local import _find_bash, _find_shell
class TestFindShellPrefersUserShell:
"""_find_shell should prefer $SHELL over bash on POSIX."""
+ @pytest.mark.linux_only
def test_returns_shell_env_when_set_and_exists(self, tmp_path):
"""When $SHELL points to an existing allowlisted executable, _find_shell returns it."""
fake_zsh = tmp_path / "zsh"
@@ -46,6 +47,7 @@ class TestFindShellPrefersUserShell:
assert _find_shell() == _find_bash()
+ @pytest.mark.linux_only
def test_honours_allowlisted_bash_and_dash(self, tmp_path):
"""Every allowlisted POSIX-sh-family shell is honoured."""
for name in ("bash", "dash", "sh", "ksh"):
diff --git a/tests/tools/test_interrupted_command_cwd.py b/tests/tools/test_interrupted_command_cwd.py
index ecf14f176ed..39c1ff7e8c2 100644
--- a/tests/tools/test_interrupted_command_cwd.py
+++ b/tests/tools/test_interrupted_command_cwd.py
@@ -58,6 +58,7 @@ class TestCwdObservedFlag:
result, _ = _run(env, "sess", f"cd {target} && pwd")
assert result["cwd_observed"] is True
+ @pytest.mark.linux_only
def test_interrupted_command_reports_no_cwd(self, env, tmp_path):
target = tmp_path / "slow"
target.mkdir()
@@ -67,6 +68,7 @@ class TestCwdObservedFlag:
class TestInterruptDoesNotStealAnotherSessionsCwd:
+ @pytest.mark.linux_only
def test_record_survives_an_interrupt(self, env, tmp_path):
mine = tmp_path / "mine"
theirs = tmp_path / "theirs"
@@ -84,6 +86,7 @@ class TestInterruptDoesNotStealAnotherSessionsCwd:
_run(env, "mine", f"cd {mine} && sleep 20", timeout=2)
assert tt.get_session_cwd("mine") == str(mine)
+ @pytest.mark.linux_only
def test_next_command_still_runs_in_my_directory(self, env, tmp_path):
mine = tmp_path / "mine"
theirs = tmp_path / "theirs"
@@ -97,6 +100,7 @@ class TestInterruptDoesNotStealAnotherSessionsCwd:
result, _ = _run(env, "mine", "pwd")
assert os.path.realpath(result["output"].strip()) == os.path.realpath(str(mine))
+ @pytest.mark.linux_only
def test_single_session_keeps_its_own_prior_directory(self, env, tmp_path):
"""No second session needed: a lone session must not re-home either."""
first = tmp_path / "first"
@@ -167,6 +171,7 @@ class TestTerminalToolReadsTheFlag:
tt.terminal_tool(command=command, task_id=task_id, timeout=timeout)
)
+ @pytest.mark.linux_only
def test_interrupt_keeps_record_and_echoes_no_cwd(self, env, tmp_path, monkeypatch):
mine = tmp_path / "mine"
theirs = tmp_path / "theirs"
@@ -194,6 +199,7 @@ class TestTerminalToolReadsTheFlag:
# my command_cwd (mine), so the echo would fire with THEIR directory.
assert "cwd" not in result or result.get("cwd") is None
+ @pytest.mark.linux_only
def test_completed_command_still_records_and_echoes(self, env, tmp_path, monkeypatch):
"""The gate must not break the observed path: cd still round-trips."""
target = tmp_path / "target"
diff --git a/tests/tools/test_lazy_deps_durable_target.py b/tests/tools/test_lazy_deps_durable_target.py
index cb9b517c51a..45dcc7477ee 100644
--- a/tests/tools/test_lazy_deps_durable_target.py
+++ b/tests/tools/test_lazy_deps_durable_target.py
@@ -91,6 +91,7 @@ class TestAbiStamp:
assert stamp.read_text().strip() == ld._python_abi_tag()
+ @pytest.mark.linux_only
def test_readonly_target_reports_error(self, tmp_path):
# A path under a non-writable parent should surface a clean error,
# not raise.
diff --git a/tests/tools/test_local_background_child_hang.py b/tests/tools/test_local_background_child_hang.py
index a9251cc7400..54fd896ce15 100644
--- a/tests/tools/test_local_background_child_hang.py
+++ b/tests/tools/test_local_background_child_hang.py
@@ -70,6 +70,7 @@ class TestBackgroundChildDoesNotHang:
_pkill("time.sleep(60)")
+ @pytest.mark.linux_only
def test_default_capture_is_full_fidelity_for_internal_consumers(
self, local_env
):
@@ -96,6 +97,7 @@ class TestBackgroundChildDoesNotHang:
assert len(result["output"]) > 200000
+ @pytest.mark.linux_only
def test_utf8_multibyte_across_read_boundary(self, local_env):
"""Multibyte UTF-8 characters straddling a 4096-byte ``os.read()`` boundary
must be decoded correctly via the incremental decoder — not lost to a
@@ -121,6 +123,7 @@ class TestBackgroundChildDoesNotHang:
# And the "[binary output detected ...]" fallback must NOT fire
assert "binary output detected" not in result["output"]
+ @pytest.mark.linux_only
def test_invalid_utf8_uses_replacement_not_fallback(self, local_env):
"""Truly invalid byte sequences must be substituted with U+FFFD (matching
the pre-fix ``errors='replace'`` behaviour of the old ``TextIOWrapper``
diff --git a/tests/tools/test_local_env_cwd_recovery.py b/tests/tools/test_local_env_cwd_recovery.py
index 41f101aaad4..3093eb5261b 100644
--- a/tests/tools/test_local_env_cwd_recovery.py
+++ b/tests/tools/test_local_env_cwd_recovery.py
@@ -7,6 +7,7 @@ subsequent terminal/file-tool call until the gateway restarts.
Regression coverage for https://github.com/NousResearch/hermes-agent/issues/17558.
"""
+import pytest
import os
import shutil
@@ -28,6 +29,7 @@ class TestResolveSafeCwd:
assert _resolve_safe_cwd(path) == path
+ @pytest.mark.linux_only
def test_returns_root_when_only_root_exists(self, monkeypatch):
"""If every ancestor except the filesystem root is gone, the root
itself is still a valid recovery target — don't skip it just because
diff --git a/tests/tools/test_local_env_relative_cwd.py b/tests/tools/test_local_env_relative_cwd.py
index 46a9a563ecb..d7ec6e2a0f6 100644
--- a/tests/tools/test_local_env_relative_cwd.py
+++ b/tests/tools/test_local_env_relative_cwd.py
@@ -3,6 +3,7 @@
from pathlib import Path
from tools.environments.local import LocalEnvironment, _resolve_local_initial_cwd
+import pytest
def test_relative_initial_cwd_resolves_from_parent(tmp_path, monkeypatch):
@@ -13,6 +14,7 @@ def test_relative_initial_cwd_resolves_from_parent(tmp_path, monkeypatch):
assert _resolve_local_initial_cwd("hermes-agent") == str(project)
def test_local_environment_keeps_existing_relative_child_cwd(tmp_path, monkeypatch):
project = tmp_path / "hermes-agent"
project.mkdir()
diff --git a/tests/tools/test_local_interrupt_cleanup.py b/tests/tools/test_local_interrupt_cleanup.py
index 74b1d55fd33..46ebd27c273 100644
--- a/tests/tools/test_local_interrupt_cleanup.py
+++ b/tests/tools/test_local_interrupt_cleanup.py
@@ -65,6 +65,7 @@ def _wait_for_pgid_exit(pgid: int, timeout: float = 60.0) -> bool:
return not _pgid_still_alive(pgid)
def test_kill_process_uses_cached_pgid_if_wrapper_already_exited(monkeypatch):
"""If the shell wrapper exits before cleanup, still kill its process group.
@@ -97,6 +98,7 @@ def test_kill_process_uses_cached_pgid_if_wrapper_already_exited(monkeypatch):
assert killpg_calls == [(67890, signal.SIGTERM), (67890, 0)]
def test_wait_for_process_kills_subprocess_on_keyboardinterrupt():
"""When KeyboardInterrupt arrives mid-poll, the subprocess group must be
killed before the exception is re-raised."""
diff --git a/tests/tools/test_local_setsid_descendant_sweep.py b/tests/tools/test_local_setsid_descendant_sweep.py
index 8ae35d68f74..b43dee6fc1a 100644
--- a/tests/tools/test_local_setsid_descendant_sweep.py
+++ b/tests/tools/test_local_setsid_descendant_sweep.py
@@ -17,6 +17,8 @@ from types import SimpleNamespace
import pytest
+pytestmark = pytest.mark.linux_only
+
from tools.environments.local import LocalEnvironment
diff --git a/tests/tools/test_local_shell_init.py b/tests/tools/test_local_shell_init.py
index 0f4f9af34aa..e0c3907b93c 100644
--- a/tests/tools/test_local_shell_init.py
+++ b/tests/tools/test_local_shell_init.py
@@ -19,6 +19,7 @@ from tools.environments.local import (
class TestResolveShellInitFiles:
+ @pytest.mark.linux_only
def test_auto_sources_bashrc_when_present(self, tmp_path, monkeypatch):
bashrc = tmp_path / ".bashrc"
bashrc.write_text('export MARKER=seen\n')
@@ -33,6 +34,7 @@ class TestResolveShellInitFiles:
assert resolved == [str(bashrc)]
+ @pytest.mark.linux_only
def test_auto_sources_profile_when_present(self, tmp_path, monkeypatch):
"""~/.profile is where ``n`` / ``nvm`` installers typically write
their PATH export on Debian/Ubuntu, and it has no interactivity
@@ -51,6 +53,7 @@ class TestResolveShellInitFiles:
assert resolved == [str(profile)]
+ @pytest.mark.linux_only
def test_auto_sources_profile_before_bashrc(self, tmp_path, monkeypatch):
"""Both files present: profile runs first so PATH exports in
profile take effect even if bashrc short-circuits on the
diff --git a/tests/tools/test_local_tempdir.py b/tests/tools/test_local_tempdir.py
index b07b1b77ee4..04c0776afba 100644
--- a/tests/tools/test_local_tempdir.py
+++ b/tests/tools/test_local_tempdir.py
@@ -1,9 +1,11 @@
from unittest.mock import patch
from tools.environments.local import LocalEnvironment
+import pytest
class TestLocalTempDir:
+ @pytest.mark.linux_only
def test_uses_os_tmpdir_for_session_artifacts(self, monkeypatch):
monkeypatch.setenv("TMPDIR", "/data/data/com.termux/files/usr/tmp")
monkeypatch.delenv("TMP", raising=False)
@@ -17,6 +19,7 @@ class TestLocalTempDir:
assert env._cwd_file == f"/data/data/com.termux/files/usr/tmp/hermes-cwd-{env._session_id}.txt"
+ @pytest.mark.linux_only
def test_falls_back_to_tempfile_when_tmp_missing(self, monkeypatch):
monkeypatch.delenv("TMPDIR", raising=False)
monkeypatch.delenv("TMP", raising=False)
diff --git a/tests/tools/test_macos_protected_search.py b/tests/tools/test_macos_protected_search.py
index 501280a85f7..c0e3ce44e41 100644
--- a/tests/tools/test_macos_protected_search.py
+++ b/tests/tools/test_macos_protected_search.py
@@ -3,7 +3,7 @@
from pathlib import Path
import tools.file_operations as file_operations
-from tools.environments.local import LocalEnvironment
+from tools.environments.local import LocalEnvironment, _bash_safe_path
from tools.file_operations import ShellFileOperations, _macos_protected_search_exclusions
@@ -128,7 +128,7 @@ def test_grep_fallback_prunes_by_path_not_basename(tmp_path, monkeypatch):
for dirname in PROTECTED_NAMES:
# Path-scoped pruning: full protected path present, no basename-wide
# --exclude-dir for protected names.
- assert str(home / dirname) in pruned_command
+ assert _bash_safe_path(str(home / dirname)) in pruned_command
assert f"--exclude-dir={dirname}" not in pruned_command
assert f"--exclude-dir='{dirname}'" not in pruned_command
@@ -188,7 +188,7 @@ def test_find_fallback_prunes_protected_directories(tmp_path, monkeypatch):
find_commands = [command for command in env.commands if command.startswith("find ")]
assert find_commands
for command in find_commands:
- assert str(home / "Downloads") in command
+ assert _bash_safe_path(str(home / "Downloads")) in command
assert "-prune" in command
diff --git a/tests/tools/test_mcp_schema_cache.py b/tests/tools/test_mcp_schema_cache.py
index cc6df9a6d29..5e21ad4c03d 100644
--- a/tests/tools/test_mcp_schema_cache.py
+++ b/tests/tools/test_mcp_schema_cache.py
@@ -4,6 +4,8 @@ The module landed in #56832's extraction without its tests; these cover the
fingerprint keying, read/write round-trip, and invalidation behavior.
"""
+import pytest
+
import tools.mcp_schema_cache as msc
@@ -75,6 +77,7 @@ class TestCacheRoundTrip:
class TestCacheFileLocation:
+ @pytest.mark.linux_only
def test_cache_lives_under_hermes_home_cache_dir_with_0600(
self, monkeypatch, tmp_path
):
diff --git a/tests/tools/test_mcp_tool.py b/tests/tools/test_mcp_tool.py
index 5f05b0fc343..98ded455a1d 100644
--- a/tests/tools/test_mcp_tool.py
+++ b/tests/tools/test_mcp_tool.py
@@ -1278,9 +1278,9 @@ class TestBuildSafeEnv:
fake_env = {
"PATH": r"C:\Windows\System32",
- "ProgramFiles": r"C:\Program Files",
- "ProgramData": r"C:\ProgramData",
- "ProgramW6432": r"C:\Program Files",
+ "PROGRAMFILES": r"C:\Program Files",
+ "PROGRAMDATA": r"C:\ProgramData",
+ "PROGRAMW6432": r"C:\Program Files",
"LOCALAPPDATA": r"C:\Users\alice\AppData\Local",
"APPDATA": r"C:\Users\alice\AppData\Roaming",
"USERPROFILE": r"C:\Users\alice",
@@ -1290,9 +1290,9 @@ class TestBuildSafeEnv:
with patch.dict("os.environ", fake_env, clear=True):
result = _build_safe_env(None)
- assert result["ProgramFiles"] == r"C:\Program Files"
- assert result["ProgramData"] == r"C:\ProgramData"
- assert result["ProgramW6432"] == r"C:\Program Files"
+ assert result["PROGRAMFILES"] == r"C:\Program Files"
+ assert result["PROGRAMDATA"] == r"C:\ProgramData"
+ assert result["PROGRAMW6432"] == r"C:\Program Files"
assert result["LOCALAPPDATA"].endswith("Local")
assert result["APPDATA"].endswith("Roaming")
assert result["USERPROFILE"] == r"C:\Users\alice"
diff --git a/tests/tools/test_modal_sandbox_fixes.py b/tests/tools/test_modal_sandbox_fixes.py
index 89878150dcf..c419f2d1b8d 100644
--- a/tests/tools/test_modal_sandbox_fixes.py
+++ b/tests/tools/test_modal_sandbox_fixes.py
@@ -85,6 +85,7 @@ class TestCwdHandling:
assert config["host_cwd"] is None
assert config["docker_mount_cwd_to_workspace"] is False
+ @pytest.mark.linux_only
def test_users_path_maps_to_workspace_for_docker_when_enabled(self, monkeypatch):
"""Docker should map the host cwd into /workspace only when explicitly enabled."""
monkeypatch.setenv("TERMINAL_ENV", "docker")
@@ -133,6 +134,7 @@ class TestCwdHandling:
f"Backend {backend}: expected /root default, got {config['cwd']}"
)
+ @pytest.mark.linux_only
def test_docker_default_cwd_maps_current_directory_when_enabled(self, monkeypatch):
"""Docker should use /workspace when cwd mounting is explicitly enabled."""
monkeypatch.setattr("tools.terminal_tool.os.getcwd", lambda: "/home/user/project")
diff --git a/tests/tools/test_plugin_guard.py b/tests/tools/test_plugin_guard.py
index ac40f3ad1c9..35e70a507b9 100644
--- a/tests/tools/test_plugin_guard.py
+++ b/tests/tools/test_plugin_guard.py
@@ -115,6 +115,7 @@ class TestMaliciousPlugin:
result = scan_plugin(plugin)
assert result.verdict == "dangerous"
+ @pytest.mark.require_symlinks
def test_symlink_escape_is_dangerous(self, tmp_path):
plugin = _mk_plugin(tmp_path, BASE_FILES)
outside = tmp_path / "outside-secret.txt"
diff --git a/tests/tools/test_pr_6656_regressions.py b/tests/tools/test_pr_6656_regressions.py
index c3f10a44062..c1f06da9f90 100644
--- a/tests/tools/test_pr_6656_regressions.py
+++ b/tests/tools/test_pr_6656_regressions.py
@@ -127,6 +127,7 @@ class TestUninstallPathTraversal:
assert ok is False
assert victim.exists()
+ @pytest.mark.require_symlinks
def test_symlink_escape_rejected(self, tmp_path, hub_setup):
"""Symlinks inside SKILLS_DIR that point outside must be refused
after realpath resolution."""
diff --git a/tests/tools/test_process_registry.py b/tests/tools/test_process_registry.py
index 8725a7f507b..c0292f5482e 100644
--- a/tests/tools/test_process_registry.py
+++ b/tests/tools/test_process_registry.py
@@ -570,6 +570,7 @@ class TestStdinHelpers:
proc.stdin.close.assert_called_once()
assert result["status"] == "ok"
+ @pytest.mark.linux_only
def test_close_stdin_allows_eof_driven_process_to_finish(self, registry, tmp_path):
"""PTY mode: writing data + sending EOF lets an EOF-driven child finish.
@@ -707,6 +708,7 @@ class TestPruning:
# =========================================================================
class TestSpawnEnvSanitization:
+ @pytest.mark.linux_only
def test_spawn_local_strips_blocked_vars_from_background_env(self, registry):
captured = {}
@@ -814,6 +816,7 @@ class TestSpawnEnvSanitization:
class TestPopenLeakOnSetupFailure:
"""Regression for issue #2749: subprocess orphaned when post-Popen setup raises."""
+ @pytest.mark.linux_only
def test_popen_killed_when_thread_creation_fails(self, registry):
"""If Thread() raises after Popen, proc must be killed — not orphaned."""
killed = []
@@ -915,6 +918,7 @@ class TestSpawnRewriteCompoundBackground:
# Simple background must remain as-is
assert "sleep 5 &" in shell_cmd
+ @pytest.mark.linux_only
def test_pty_path_uses_rewritten_command(self, registry):
"""PTY spawn path must also use the rewritten command (issue #68915)."""
mock_pty_proc = MagicMock()
@@ -1061,6 +1065,7 @@ class TestKillProcess:
assert result["status"] == "already_exited"
+ @pytest.mark.linux_only
def test_kill_detached_session_uses_host_pid(self, registry):
s = _make_session(sid="proc_detached", command="sleep 999")
s.pid = 424242
@@ -1286,6 +1291,7 @@ class TestTerminateHostPidWindows:
class TestTerminateHostPidPosix:
"""POSIX branch walks the tree via psutil and SIGTERMs children first."""
+ @pytest.mark.linux_only
def test_posix_walks_tree_and_terminates_children_then_parent(self, monkeypatch):
from tools import process_registry as pr
import psutil
@@ -1323,6 +1329,7 @@ class TestTerminateHostPidPosix:
"Children must be terminated before the parent"
)
+ @pytest.mark.linux_only
def test_posix_oserror_falls_back_to_os_kill(self, monkeypatch):
from tools import process_registry as pr
import psutil
diff --git a/tests/tools/test_process_registry_write_stdin_surrogates.py b/tests/tools/test_process_registry_write_stdin_surrogates.py
index 539d980caf6..b8f0ddfd53c 100644
--- a/tests/tools/test_process_registry_write_stdin_surrogates.py
+++ b/tests/tools/test_process_registry_write_stdin_surrogates.py
@@ -8,6 +8,7 @@ import pytest
from tools.process_registry import ProcessRegistry
def test_write_stdin_pty_surrogateescape_roundtrip(tmp_path):
registry = ProcessRegistry()
out = tmp_path / "out.bin"
diff --git a/tests/tools/test_read_shell_line_clamp.py b/tests/tools/test_read_shell_line_clamp.py
index 1d10b3b4d3c..08a3f5de7d6 100644
--- a/tests/tools/test_read_shell_line_clamp.py
+++ b/tests/tools/test_read_shell_line_clamp.py
@@ -120,7 +120,7 @@ def test_read_file_raw_not_clamped(tmp_path, ops):
max_len = get_max_line_length()
p = tmp_path / "long_raw.txt"
long_line = "z" * (10 * max_len)
- p.write_text(long_line + "\n")
+ p.write_bytes((long_line + "\n").encode("utf-8"))
result = ops.read_file_raw(str(p))
assert result.error is None
assert result.content == long_line + "\n"
diff --git a/tests/tools/test_read_special_file_guard.py b/tests/tools/test_read_special_file_guard.py
index 330f42edd78..80ad78407bb 100644
--- a/tests/tools/test_read_special_file_guard.py
+++ b/tests/tools/test_read_special_file_guard.py
@@ -26,11 +26,13 @@ class TestSpecialFileKind:
def test_missing_path(self, tmp_path):
assert _special_file_kind(tmp_path / "nope") is None
+ @pytest.mark.linux_only
def test_fifo(self, tmp_path):
fifo = tmp_path / "p.pipe"
os.mkfifo(fifo)
assert "FIFO" in (_special_file_kind(fifo) or "")
+ @pytest.mark.linux_only
def test_socket(self, tmp_path):
sock_path = tmp_path / "s.sock"
s = socket.socket(socket.AF_UNIX)
@@ -40,6 +42,7 @@ class TestSpecialFileKind:
finally:
s.close()
+ @pytest.mark.linux_only
def test_symlink_to_fifo_followed(self, tmp_path):
fifo = tmp_path / "p.pipe"
os.mkfifo(fifo)
@@ -54,6 +57,7 @@ class TestSpecialFileKind:
class TestReadFileToolFifoGuard:
+ @pytest.mark.linux_only
def test_fifo_read_returns_note_instantly(self, tmp_path, monkeypatch):
import time
diff --git a/tests/tools/test_search_auto_multiline.py b/tests/tools/test_search_auto_multiline.py
index 61838324383..f1e46cab323 100644
--- a/tests/tools/test_search_auto_multiline.py
+++ b/tests/tools/test_search_auto_multiline.py
@@ -14,7 +14,8 @@ def proj(tmp_path, monkeypatch):
d.mkdir()
(d / "mod.py").write_text(
"def setup():\n init_db()\n return True\n\n"
- "def teardown():\n close_db()\n"
+ "def teardown():\n close_db()\n",
+ newline="\n",
)
return d
@@ -40,7 +41,7 @@ class TestAutoMultiline:
def test_escaped_backslash_n_stays_literal(self, proj):
# \\n = literal backslash+n search, not a newline: no multiline mode.
- (proj / "strings.py").write_text('SEP = "a\\\\nb"\n')
+ (proj / "strings.py").write_text('SEP = "a\\\\nb"\n', newline="\n")
r = json.loads(search_tool(r"a\\nb", path=str(proj), task_id="t-ml"))
assert "error" not in r
assert "multiline" not in (r.get("warning") or "")
diff --git a/tests/tools/test_self_repo_guard.py b/tests/tools/test_self_repo_guard.py
index 06d96b4beac..2583bc2237d 100644
--- a/tests/tools/test_self_repo_guard.py
+++ b/tests/tools/test_self_repo_guard.py
@@ -149,6 +149,7 @@ class TestBlocksMutationsInSourceRepo:
def test_tilde_dash_c_path(self, repo, monkeypatch, tmp_path):
monkeypatch.setenv("HOME", str(repo.parent))
+ monkeypatch.setenv("USERPROFILE", str(repo.parent))
hit, _ = _detect("git -C ~/hermes-agent checkout main", tmp_path, repo)
assert hit is True
@@ -374,8 +375,9 @@ class TestBlockMessageGuidance:
assert "tmpfs" in msg
assert "Delete the clone" in msg
- def test_scratch_hint_honors_hermes_home(self, repo, monkeypatch):
- monkeypatch.setenv("HERMES_HOME", "/custom/hermes-home")
+ def test_scratch_hint_honors_hermes_home(self, repo, monkeypatch, tmp_path):
+ home = tmp_path / "custom" / "hermes-home"
+ monkeypatch.setenv("HERMES_HOME", str(home))
hit, msg = _detect("git rebase origin/main", repo, repo)
assert hit is True
- assert "/custom/hermes-home/scratch" in msg
+ assert str(home / "scratch") in msg
diff --git a/tests/tools/test_skill_bundle_provenance.py b/tests/tools/test_skill_bundle_provenance.py
index 1d5e6e02cf7..3ffe492d2f8 100644
--- a/tests/tools/test_skill_bundle_provenance.py
+++ b/tests/tools/test_skill_bundle_provenance.py
@@ -1,6 +1,7 @@
"""Multi-file third-party skill bundles and scanner provenance (#60598)."""
import json
+import os
import subprocess
import sys
import threading
@@ -511,7 +512,7 @@ def test_bundled_optional_source_still_includes_support_files(tmp_path, monkeypa
bundle = source.fetch("official/category/official-demo")
assert bundle is not None
- assert set(bundle.files) == {"SKILL.md", "references/all.md"}
+ assert set(bundle.files) == {"SKILL.md", os.path.join("references", "all.md")}
UPSTREAM_STUB_MD = """---
diff --git a/tests/tools/test_skill_manager_tool.py b/tests/tools/test_skill_manager_tool.py
index 1d5bcb4629e..e22f09a4375 100644
--- a/tests/tools/test_skill_manager_tool.py
+++ b/tests/tools/test_skill_manager_tool.py
@@ -981,6 +981,7 @@ class TestDeleteSkillRmtreeGuard:
assert result["success"] is True, result
assert not (tmp_path / "good-skill").exists()
+ @pytest.mark.require_symlinks
def test_symlinked_skill_dir_refused(self, tmp_path):
"""A skill dir that is a symlink must not be rmtree'd — rmtree would
otherwise follow it and delete the link target's contents."""
diff --git a/tests/tools/test_skills_guard.py b/tests/tools/test_skills_guard.py
index 8a8b7eb350b..c94c0782ed3 100644
--- a/tests/tools/test_skills_guard.py
+++ b/tests/tools/test_skills_guard.py
@@ -252,6 +252,7 @@ class TestCheckStructure:
ids = {fi.pattern_id for fi in _check_structure(tmp_path)}
assert {"too_many_files", "oversized_file", "binary_file"} <= ids
+ @pytest.mark.require_symlinks
def test_symlink_escape(self, tmp_path):
target = tmp_path / "outside"
target.mkdir()
diff --git a/tests/tools/test_skills_hub.py b/tests/tools/test_skills_hub.py
index 610ea2b3496..c807a1b1cba 100644
--- a/tests/tools/test_skills_hub.py
+++ b/tests/tools/test_skills_hub.py
@@ -1,6 +1,7 @@
"""Tests for tools/skills_hub.py — source adapters, lock file, taps, dedup logic."""
import json
+import os
import time
from typing import List, Optional
from unittest.mock import patch, MagicMock
@@ -527,7 +528,7 @@ class TestCheckForSkillUpdates:
skill_dir.mkdir()
(skill_dir / "SKILL.md").write_text("same content")
(skill_dir / "references").mkdir()
- (skill_dir / "references" / "checklist.md").write_text("- [ ] security\n")
+ (skill_dir / "references" / "checklist.md").write_bytes(b"- [ ] security\n")
assert bundle_content_hash(bundle) == content_hash(skill_dir)
@@ -860,8 +861,8 @@ class TestOptionalSkillSourceBinaryAssets:
(skill_dir / "assets" / "neutts-cli" / "samples" / "jo.wav").write_bytes(
wav_bytes
)
- (skill_dir / "assets" / "neutts-cli" / "samples" / "jo.txt").write_text(
- "hello\n", encoding="utf-8"
+ (skill_dir / "assets" / "neutts-cli" / "samples" / "jo.txt").write_bytes(
+ b"hello\n"
)
pycache_dir = skill_dir / "assets" / "neutts-cli" / "src" / "neutts_cli" / "__pycache__"
pycache_dir.mkdir(parents=True)
@@ -873,8 +874,8 @@ class TestOptionalSkillSourceBinaryAssets:
bundle = src.fetch("official/mlops/models/neutts")
assert bundle is not None
- assert bundle.files["assets/neutts-cli/samples/jo.wav"] == wav_bytes
- assert bundle.files["assets/neutts-cli/samples/jo.txt"] == b"hello\n"
+ assert bundle.files[os.path.join("assets", "neutts-cli", "samples", "jo.wav")] == wav_bytes
+ assert bundle.files[os.path.join("assets", "neutts-cli", "samples", "jo.txt")] == b"hello\n"
assert "assets/neutts-cli/src/neutts_cli/__pycache__/cli.cpython-312.pyc" not in bundle.files
def test_fetch_rejects_sibling_directory_traversal(self, tmp_path):
diff --git a/tests/tools/test_skills_sync.py b/tests/tools/test_skills_sync.py
index bb55469c4fc..d26a2dbd81d 100644
--- a/tests/tools/test_skills_sync.py
+++ b/tests/tools/test_skills_sync.py
@@ -141,7 +141,7 @@ class TestComputeRelativeDest:
def test_preserves_category_structure(self):
bundled = Path("/repo/skills")
dest = _compute_relative_dest(Path("/repo/skills/mlops/axolotl"), bundled)
- assert str(dest).endswith("mlops/axolotl")
+ assert str(dest).endswith(os.path.join("mlops", "axolotl"))
# Flat (uncategorized) skills keep their own name.
assert _compute_relative_dest(Path("/repo/skills/simple"), bundled).name == "simple"
diff --git a/tests/tools/test_skills_sync_client.py b/tests/tools/test_skills_sync_client.py
index c967eef187a..1b0245d38ef 100644
--- a/tests/tools/test_skills_sync_client.py
+++ b/tests/tools/test_skills_sync_client.py
@@ -353,6 +353,7 @@ class TestDevGate:
# ---------------------------------------------------------------------------
class TestObjectBuilding:
+ @pytest.mark.linux_only
def test_build_tree_blob_and_exec(self, tmp_path):
d = tmp_path / "skill"
d.mkdir()
diff --git a/tests/tools/test_skills_tool.py b/tests/tools/test_skills_tool.py
index 99bcb4c8ac1..56c8bb3f4a0 100644
--- a/tests/tools/test_skills_tool.py
+++ b/tests/tools/test_skills_tool.py
@@ -907,7 +907,7 @@ class TestSkillViewCollisionDetection:
assert "matches" in result
assert len(result["matches"]) == 2
# Both paths surfaced
- assert any("foundations/runtime" in p for p in result["matches"])
+ assert any(os.path.join("foundations", "runtime") in p for p in result["matches"])
assert any("external" in p for p in result["matches"])
assert "hint" in result
@@ -944,7 +944,7 @@ class TestSkillViewCollisionDetection:
result = json.loads(raw)
assert result["success"] is True
- assert result["path"] == "creative/sketch/SKILL.md"
+ assert result["path"] == os.path.join("creative", "sketch", "SKILL.md")
assert "REAL SKETCH SKILL" in result["content"]
diff --git a/tests/tools/test_spill_safety.py b/tests/tools/test_spill_safety.py
index 82440df3997..561d3d226d6 100644
--- a/tests/tools/test_spill_safety.py
+++ b/tests/tools/test_spill_safety.py
@@ -43,6 +43,7 @@ def test_private_dir_is_0700_and_tightened(tmp_path):
assert stat.S_IMODE(os.lstat(d).st_mode) == 0o700
def test_ensure_spill_dir_refuses_symlinked_leaf(tmp_path):
victim = tmp_path / "victim-dir"
victim.mkdir()
@@ -52,6 +53,7 @@ def test_ensure_spill_dir_refuses_symlinked_leaf(tmp_path):
ensure_spill_dir(link)
def test_refuses_planted_symlink(tmp_path):
"""The core attack: symlink at the spill path must fail, not redirect."""
victim = tmp_path / "victim.txt"
@@ -63,6 +65,7 @@ def test_refuses_planted_symlink(tmp_path):
assert victim.read_text() == "original"
def test_refuses_dangling_symlink(tmp_path):
target = tmp_path / "spill.txt"
target.symlink_to(tmp_path / "does-not-exist.txt")
@@ -71,6 +74,7 @@ def test_refuses_dangling_symlink(tmp_path):
assert not (tmp_path / "does-not-exist.txt").exists()
def test_overwrite_removes_symlink_not_its_target(tmp_path):
victim = tmp_path / "victim.txt"
victim.write_text("original")
diff --git a/tests/tools/test_ssh_bulk_upload.py b/tests/tools/test_ssh_bulk_upload.py
index bf41a2fb6e6..5b10c3523df 100644
--- a/tests/tools/test_ssh_bulk_upload.py
+++ b/tests/tools/test_ssh_bulk_upload.py
@@ -136,6 +136,7 @@ class TestSSHBulkUpload:
assert len(staging_paths) == 1, "tar command should have been called"
+ @pytest.mark.require_symlinks
def test_bulk_upload_never_stages_remote_home_prefix(self, mock_env, tmp_path):
"""Regression: do not archive /home/<user> path components."""
f1 = tmp_path / "nested.txt"
diff --git a/tests/tools/test_stage2_hook_api_server_keygen.py b/tests/tools/test_stage2_hook_api_server_keygen.py
index fdcf4cb22e3..c4e9de764ad 100644
--- a/tests/tools/test_stage2_hook_api_server_keygen.py
+++ b/tests/tools/test_stage2_hook_api_server_keygen.py
@@ -74,6 +74,7 @@ def _run_keygen(
)
def test_keygen_creates_env_when_missing(stage2_text: str, tmp_path: Path) -> None:
"""No .env at all (failed/absent first-boot seed) must still yield a key."""
home = tmp_path / "home"
@@ -116,6 +117,7 @@ def test_keygen_never_overwrites_operator_key(
assert content == "API_SERVER_KEY=operator-provided-key-123\n"
def test_keygen_refuses_symlinked_env(stage2_text: str, tmp_path: Path) -> None:
home = tmp_path / "home"
home.mkdir()
@@ -198,6 +200,7 @@ def _sed_is_gnu() -> bool:
return probe.returncode == 0 and "GNU sed" in probe.stdout
def test_keygen_readonly_env_degrades_to_warning_not_boot_abort(
stage2_text: str, tmp_path: Path
) -> None:
diff --git a/tests/tools/test_terminal_cwd_echo.py b/tests/tools/test_terminal_cwd_echo.py
index 98acccb8c5f..28120c0e8a1 100644
--- a/tests/tools/test_terminal_cwd_echo.py
+++ b/tests/tools/test_terminal_cwd_echo.py
@@ -22,6 +22,13 @@ def isolated_home(tmp_path, monkeypatch):
class TestCwdEcho:
+ # `cd` with a *native* Windows path (``str(Path)`` → ``C:\\Users\\...``)
+ # doesn't survive the terminal's ``eval '<command>'`` wrapper on Windows —
+ # bash re-parses the command and eats the backslash separators, so the
+ # ``cd`` no-ops and the cwd never changes. Native-path handling in the
+ # terminal is a separate Windows workstream; the echo feature itself is
+ # covered by the Linux lane here.
+ @pytest.mark.linux_only
def test_cd_reports_new_cwd(self, isolated_home, tmp_path):
target = tmp_path / "projdir"
target.mkdir()
@@ -35,6 +42,7 @@ class TestCwdEcho:
assert r["exit_code"] == 0
assert "cwd" not in r
+ @pytest.mark.linux_only
def test_cwd_persists_and_stops_reporting_when_stable(self, isolated_home, tmp_path):
target = tmp_path / "stable"
target.mkdir()
@@ -45,6 +53,7 @@ class TestCwdEcho:
assert "cwd" not in r2
assert os.path.realpath(r2["output"].strip()) == os.path.realpath(str(target))
+ @pytest.mark.linux_only
def test_cd_within_chain_reports_final_dir(self, isolated_home, tmp_path):
a = tmp_path / "a"
b = tmp_path / "b"
diff --git a/tests/tools/test_terminal_output_transform_hook.py b/tests/tools/test_terminal_output_transform_hook.py
index 9d9c7565160..9381247d751 100644
--- a/tests/tools/test_terminal_output_transform_hook.py
+++ b/tests/tools/test_terminal_output_transform_hook.py
@@ -3,6 +3,8 @@ import os
from pathlib import Path
from unittest.mock import MagicMock
+import pytest
+
import hermes_cli.plugins as plugins_mod
import tools.terminal_tool as terminal_tool_module
from tools.environments.local import LocalEnvironment
@@ -91,6 +93,7 @@ def test_terminal_output_transform_still_runs_strip_and_redact(monkeypatch, tmp_
assert "abc123def456" not in result["output"] # secret body is gone
def test_large_process_output_is_bounded_before_sudo_and_plugin_hooks(
monkeypatch, tmp_path
):
diff --git a/tests/tools/test_terminal_truncation_spill.py b/tests/tools/test_terminal_truncation_spill.py
index f14d0da5333..cf27103b66d 100644
--- a/tests/tools/test_terminal_truncation_spill.py
+++ b/tests/tools/test_terminal_truncation_spill.py
@@ -20,6 +20,7 @@ def small_cap(tmp_path, monkeypatch):
class TestTruncationSpill:
+ @pytest.mark.linux_only
def test_truncated_output_has_metadata_and_spill(self, small_cap):
r = json.loads(terminal_tool(
"python3 -c \"print('marker_head'); [print(f'row_{i}', 'x'*80) for i in range(200)]; print('marker_tail')\"",
@@ -41,6 +42,7 @@ class TestTruncationSpill:
assert "full_output_path" not in r
assert "output_total_chars" not in r
+ @pytest.mark.linux_only
def test_spill_is_redacted(self, small_cap):
r = json.loads(terminal_tool(
"python3 -c \"print('sk-proj-' + 'a1B2c3D4e5F6g7H8i9J0' * 3); [print('pad', 'y'*90) for i in range(200)]\"",
@@ -59,6 +61,7 @@ class TestTruncationSpill:
"python3 -c \"[print('z'*90) for i in range(200)]\"", task_id="t-spill-4"))
assert not stale.exists()
+ @pytest.mark.linux_only
def test_failed_command_still_gets_spill(self, small_cap):
r = json.loads(terminal_tool(
"python3 -c \"[print('e'*90) for i in range(200)]; import sys; sys.exit(3)\"",
diff --git a/tests/tools/test_tirith_security.py b/tests/tools/test_tirith_security.py
index ed5f8be92d2..3ed3365ee87 100644
--- a/tests/tools/test_tirith_security.py
+++ b/tests/tools/test_tirith_security.py
@@ -54,6 +54,7 @@ def _json_stdout(findings=None, summary=""):
# Exit code → action mapping
# ---------------------------------------------------------------------------
class TestExitCodeMapping:
@patch("tools.tirith_security.subprocess.run")
@patch("tools.tirith_security._load_security_config")
@@ -94,6 +95,7 @@ class TestExitCodeMapping:
# JSON parse failure (exit code still wins)
# ---------------------------------------------------------------------------
class TestJsonParseFailure:
@patch("tools.tirith_security.subprocess.run")
@patch("tools.tirith_security._load_security_config")
@@ -119,6 +121,7 @@ class TestJsonParseFailure:
# Operational failures + fail_open
# ---------------------------------------------------------------------------
class TestOSErrorFailOpen:
@patch("tools.tirith_security.subprocess.run")
@patch("tools.tirith_security._load_security_config")
@@ -141,6 +144,7 @@ class TestOSErrorFailOpen:
assert "fail-closed" in result["summary"]
class TestTimeoutFailOpen:
@patch("tools.tirith_security.subprocess.run")
@patch("tools.tirith_security._load_security_config")
@@ -153,6 +157,7 @@ class TestTimeoutFailOpen:
assert "fail-closed" in result["summary"]
class TestUnknownExitCode:
@patch("tools.tirith_security.subprocess.run")
@patch("tools.tirith_security._load_security_config")
@@ -182,6 +187,7 @@ class TestDisabled:
# Findings cap + summary cap
# ---------------------------------------------------------------------------
class TestCaps:
@patch("tools.tirith_security.subprocess.run")
@patch("tools.tirith_security._load_security_config")
@@ -199,6 +205,7 @@ class TestCaps:
# Programming errors propagate
# ---------------------------------------------------------------------------
class TestProgrammingErrors:
@patch("tools.tirith_security.subprocess.run")
@patch("tools.tirith_security._load_security_config")
@@ -222,6 +229,7 @@ class TestEnsureInstalled:
_tirith_mod._resolved_path = None
assert ensure_installed() is None
+ @pytest.mark.linux_only
@patch("tools.tirith_security.shutil.which", return_value="/usr/local/bin/tirith")
@patch("tools.tirith_security._load_security_config")
def test_found_on_path_returns_immediately(self, mock_cfg, mock_which):
@@ -299,6 +307,7 @@ class TestUnsupportedPlatform:
# ---------------------------------------------------------------------------
class TestFailedDownloadCaching:
+ @pytest.mark.linux_only
@patch("tools.tirith_security._mark_install_failed")
@patch("tools.tirith_security._is_install_failed_on_disk", return_value=False)
@patch("tools.tirith_security._install_tirith", return_value=(None, "download_failed"))
@@ -341,6 +350,7 @@ class TestExplicitPathNoAutoDownload:
_tirith_mod._resolved_path = None
+ @pytest.mark.linux_only
@patch("tools.tirith_security._mark_install_failed")
@patch("tools.tirith_security._is_install_failed_on_disk", return_value=False)
@patch("tools.tirith_security._install_tirith", return_value=("/auto/tirith", ""))
@@ -490,6 +500,7 @@ class TestInstallArchiveMemberValidation:
# ---------------------------------------------------------------------------
class TestBackgroundInstall:
+ @pytest.mark.linux_only
def test_ensure_installed_non_blocking(self):
"""ensure_installed must return immediately when download needed."""
_tirith_mod._resolved_path = None
@@ -586,6 +597,7 @@ class TestHermesHomeIsolation:
# Warn-once dedupe (issue: tirith spawn failed spamming on Windows)
# ---------------------------------------------------------------------------
class TestSpawnWarningDedup:
"""When tirith isn't installed yet (background install in flight, or
install marked failed), every terminal command spammed an identical
@@ -636,6 +648,7 @@ _CFG = {"tirith_enabled": True, "tirith_path": "tirith",
"tirith_timeout": 5, "tirith_fail_open": True}
class TestAppTldSuppression:
"""warn verdicts whose only finding is lookalike_tld/.app are downgraded to allow."""
@@ -694,6 +707,7 @@ class TestIsAppTldFinding:
# mkdtemp OSError → no_space (disk-full leak prevention)
# ---------------------------------------------------------------------------
class TestMkdtempOSErrorNoSpace:
"""When tempfile.mkdtemp raises OSError (e.g. disk full), _install_tirith
must return (None, "no_space") instead of propagating the exception.
diff --git a/tests/tools/test_video_analyze.py b/tests/tools/test_video_analyze.py
index 00351116302..280769fe05c 100644
--- a/tests/tools/test_video_analyze.py
+++ b/tests/tools/test_video_analyze.py
@@ -6,6 +6,7 @@ import json
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
+import pytest
from tools.vision_tools import (
_detect_video_mime_type,
@@ -145,6 +146,7 @@ class TestVideoAnalyzeTool:
assert data["success"] is True
assert "demo" in data["analysis"].lower()
+ @pytest.mark.require_symlinks
def test_local_file_read_guard_blocks_env_via_video_extension(self, tmp_path):
"""A .env file symlinked with a video extension must still be blocked.
diff --git a/tests/tools/test_voice_mode.py b/tests/tools/test_voice_mode.py
index be9f24f6de3..e129a669f22 100644
--- a/tests/tools/test_voice_mode.py
+++ b/tests/tools/test_voice_mode.py
@@ -120,6 +120,7 @@ def fake_clock(monkeypatch):
# detect_audio_environment — WSL / SSH / Docker detection
# ============================================================================
class TestPulseSocketReachable:
def test_stale_socket_file_not_reachable(self, monkeypatch, tmp_path):
"""A socket file with no listener should not count as reachable."""
@@ -1391,6 +1392,7 @@ class TestWSL2PowerShellFallback:
return next(it)
return _side_effect
+ @pytest.mark.linux_only
def test_powershell_pipeline_preserves_real_exit_status(self, sample_wav):
"""Regression (review of #63768): the shell pipeline must preserve
the (ffmpeg && powershell) exit status past the unconditional
@@ -1440,6 +1442,7 @@ class TestWSL2PowerShellFallback:
"Shell pipeline must preserve the real exit status past cleanup: " + sh_script
)
+ @pytest.mark.linux_only
def test_wsl2_unique_temp_filename(self, monkeypatch, tmp_path, sample_wav):
"""Two concurrent calls must use different temp WAV filenames."""
from unittest.mock import patch, MagicMock
diff --git a/tests/tools/test_windows_native_support.py b/tests/tools/test_windows_native_support.py
index 1a04a28f55a..bed8f6718fb 100644
--- a/tests/tools/test_windows_native_support.py
+++ b/tests/tools/test_windows_native_support.py
@@ -931,6 +931,7 @@ class TestWindowlessGatewayRestartSpec:
hidden-console respawn spec (normalized interpreter + stable cwd + env
overlay)."""
+ @pytest.mark.linux_only
def test_noop_on_non_windows(self):
import hermes_cli.gateway_windows as gw
diff --git a/tests/tools/test_zombie_process_cleanup.py b/tests/tools/test_zombie_process_cleanup.py
index ba3c20eebce..929b4145030 100644
--- a/tests/tools/test_zombie_process_cleanup.py
+++ b/tests/tools/test_zombie_process_cleanup.py
@@ -11,6 +11,8 @@ import subprocess
import sys
import threading
+import pytest
+
def _spawn_sleep(seconds: float = 60) -> subprocess.Popen:
@@ -32,6 +34,7 @@ def _pid_alive(pid: int) -> bool:
class TestZombieReproduction:
"""Demonstrate that subprocesses survive when cleanup is not called."""
+ @pytest.mark.linux_only
def test_orphaned_processes_survive_without_cleanup(self):
"""REPRODUCTION: processes spawned directly survive if no one kills
them — this models the gap that causes zombie accumulation when
diff --git a/tests/tui_gateway/test_bot_relay_methods.py b/tests/tui_gateway/test_bot_relay_methods.py
index fb6d357744a..274e627954f 100644
--- a/tests/tui_gateway/test_bot_relay_methods.py
+++ b/tests/tui_gateway/test_bot_relay_methods.py
@@ -116,6 +116,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
diff --git a/tests/tui_gateway/test_compute_host.py b/tests/tui_gateway/test_compute_host.py
index fa0019722f1..cc76f87698c 100644
--- a/tests/tui_gateway/test_compute_host.py
+++ b/tests/tui_gateway/test_compute_host.py
@@ -30,6 +30,7 @@ def _read_json_line(out: queue.Queue[dict], timeout: float = 2.0) -> dict:
raise AssertionError("timed out waiting for compute host JSON") from exc
def test_compute_host_line_json_seed_turn_interrupt():
repo = Path(__file__).resolve().parents[2]
env = dict(os.environ)
diff --git a/tests/tui_gateway/test_entry_import_off_main_thread.py b/tests/tui_gateway/test_entry_import_off_main_thread.py
index d3a80c4dbdf..233d7e896d9 100644
--- a/tests/tui_gateway/test_entry_import_off_main_thread.py
+++ b/tests/tui_gateway/test_entry_import_off_main_thread.py
@@ -26,6 +26,8 @@ thread, so an in-process import would not reproduce the bug).
import subprocess
import sys
+import pytest
+
REPO_ROOT = "."
@@ -65,6 +67,7 @@ def _spawn_worker_import_entry():
return proc.returncode, proc.stdout, proc.stderr
def test_entry_imports_cleanly_from_worker_thread():
"""First import of tui_gateway.entry from a worker thread must succeed."""
rc, out, err = _spawn_worker_import_entry()
diff --git a/tests/verify/test_environment_and_runner.py b/tests/verify/test_environment_and_runner.py
index 4c1d8885623..852f015e78d 100644
--- a/tests/verify/test_environment_and_runner.py
+++ b/tests/verify/test_environment_and_runner.py
@@ -5,6 +5,8 @@ import json
import threading
import time
+import pytest
+
from agent.verify.environment import (
load_manifest,
load_or_detect,
@@ -128,6 +130,7 @@ def _free_port() -> int:
class TestReadiness:
+ @pytest.mark.linux_only
def test_readiness_against_live_server(self, tmp_path):
port = _free_port()
recipe = Recipe(
diff --git a/tests/website/test_generate_llms_txt.py b/tests/website/test_generate_llms_txt.py
index 738ba55a092..cf84acce415 100644
--- a/tests/website/test_generate_llms_txt.py
+++ b/tests/website/test_generate_llms_txt.py
@@ -53,7 +53,7 @@ def _pages_on_disk(gen) -> set[str]:
pages = set()
for path in (*gen.DOCS.rglob("*.md"), *gen.DOCS.rglob("*.mdx")):
rel = path.relative_to(gen.DOCS).with_suffix("")
- slug = str(rel.parent) if rel.name == "index" else str(rel)
+ slug = rel.parent.as_posix() if rel.name == "index" else rel.as_posix()
# The docs landing page is the index's subject; per-skill pages are
# summarized by the two catalog reference pages.
if slug == "." or slug.startswith(("user-guide/skills/bundled", "user-guide/skills/optional")):
diff --git a/tools/approval.py b/tools/approval.py
index 15867a188cf..7c34b471587 100644
--- a/tools/approval.py
+++ b/tools/approval.py
@@ -2168,6 +2168,9 @@ def _replace_simple_shell_expansions(word: str) -> str:
return _PARAM_DEFAULT_RE.sub(lambda match: match.group("default"), word)
+_IS_WINDOWS = sys.platform == "win32"
+
+
def _strip_shell_word_syntax(word: str) -> str:
chars: list[str] = []
quote: str | None = None
@@ -2175,7 +2178,7 @@ def _strip_shell_word_syntax(word: str) -> str:
while i < len(word):
ch = word[i]
if quote:
- if ch == "\\" and quote == '"' and i + 1 < len(word):
+ if ch == "\\" and quote == '"' and not _IS_WINDOWS and i + 1 < len(word):
chars.append(word[i + 1])
i += 2
continue
@@ -2190,7 +2193,7 @@ def _strip_shell_word_syntax(word: str) -> str:
quote = ch
i += 1
continue
- if ch == "\\" and i + 1 < len(word):
+ if ch == "\\" and not _IS_WINDOWS and i + 1 < len(word):
chars.append(word[i + 1])
i += 2
continue
diff --git a/tools/checkpoint_manager.py b/tools/checkpoint_manager.py
index 1061874b410..e2d43187763 100644
--- a/tools/checkpoint_manager.py
+++ b/tools/checkpoint_manager.py
@@ -2202,6 +2202,25 @@ def store_status(checkpoint_base: Optional[Path] = None) -> Dict:
return out
+def _rmtree_force(path: Path) -> None:
+ """``shutil.rmtree`` that clears read-only bits before deleting.
+
+ Windows refuses to delete a tree containing read-only files (git objects
+ are commonly read-only), raising ``PermissionError`` where POSIX unlinks
+ them fine. The ``onerror`` hook chmods the file writable and retries.
+ """
+ import stat
+
+ def _onerror(func, p, _exc_info):
+ try:
+ os.chmod(p, stat.S_IWRITE)
+ except OSError:
+ pass
+ func(p)
+
+ shutil.rmtree(path, onerror=_onerror)
+
+
def clear_all(checkpoint_base: Optional[Path] = None) -> Dict[str, int]:
"""Nuke the entire checkpoint base (store + legacy). Irreversible.
@@ -2213,7 +2232,7 @@ def clear_all(checkpoint_base: Optional[Path] = None) -> Dict[str, int]:
return out
size = _dir_size_bytes(base)
try:
- shutil.rmtree(base)
+ _rmtree_force(base)
out["bytes_freed"] = size
out["deleted"] = True
except OSError as exc:
@@ -2235,7 +2254,7 @@ def clear_legacy(checkpoint_base: Optional[Path] = None) -> Dict[str, int]:
continue
try:
size = _dir_size_bytes(child)
- shutil.rmtree(child)
+ _rmtree_force(child)
out["bytes_freed"] += size
out["deleted"] += 1
except OSError as exc:
diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.py
index 2d3937787d2..3d8b93fa6ce 100644
--- a/tools/computer_use/cua_backend.py
+++ b/tools/computer_use/cua_backend.py
@@ -51,7 +51,7 @@ import tempfile
import threading
import time
import uuid
-from pathlib import PureWindowsPath
+from pathlib import PurePosixPath, PureWindowsPath
from typing import Any, Dict, List, Optional, Tuple
from hermes_cli._subprocess_compat import windows_hide_flags
@@ -538,7 +538,10 @@ def _wsl_windows_path_to_posix(path: str) -> str:
drive = (win.drive or "").rstrip(":").lower()
if not drive:
return path
- return os.path.join("/mnt", drive, *(str(part) for part in win.parts[1:]))
+ # PurePosixPath (not os.path.join) so the result always uses forward
+ # slashes — os.path.join would emit backslashes on a native Windows host,
+ # producing the invalid ``/mnt\c\...`` the WSL side cannot read.
+ return str(PurePosixPath("/mnt", drive, *(str(part) for part in win.parts[1:])))
def _resolve_cua_driver_app_path(driver_cmd: str) -> Optional[str]:
diff --git a/tools/environments/daytona.py b/tools/environments/daytona.py
index 8aba7128041..c3ebda3eaa0 100644
--- a/tools/environments/daytona.py
+++ b/tools/environments/daytona.py
@@ -10,7 +10,7 @@ import math
import os
import shlex
import threading
-from pathlib import Path
+from pathlib import Path, PurePosixPath
from tools.environments.base import (
BaseEnvironment,
@@ -153,7 +153,9 @@ class DaytonaEnvironment(BaseEnvironment):
def _daytona_upload(self, host_path: str, remote_path: str) -> None:
"""Upload a single file via Daytona SDK."""
- parent = str(Path(remote_path).parent)
+ # remote_path is a POSIX path on the sandbox; never run it through the
+ # host's Path (Windows would mangle the separators into backslashes).
+ parent = str(PurePosixPath(remote_path).parent)
self._sandbox.process.exec(quoted_mkdir_command([parent]))
self._sandbox.fs.upload_file(host_path, remote_path)
diff --git a/tools/file_operations.py b/tools/file_operations.py
index fbfd06cab8e..cbef8fc1e26 100644
--- a/tools/file_operations.py
+++ b/tools/file_operations.py
@@ -1175,7 +1175,7 @@ class ShellFileOperations(FileOperations):
return path
- def _escape_shell_arg(self, arg: str) -> str:
+ def _escape_shell_arg(self, arg: str, translate_path: bool = True) -> str:
"""Escape a string for safe use in shell commands.
On Windows native drive paths (``C:\\Users\\x`` / ``C:/Users/x``)
@@ -1185,10 +1185,20 @@ class ShellFileOperations(FileOperations):
``Directory \\drivers\\etc does not exist`` failure class. Reuses
the env-layer translator so shell file ops and the terminal ``cd``
agree on the path form. No-op off Windows and for plain POSIX paths.
+
+ ``translate_path=False`` skips that translation for non-path values
+ (regex patterns) whose backslashes are meaningful. On Windows those
+ backslashes are doubled first: the ``-c`` argument passes through
+ ``subprocess`` list-arg quoting (which wraps it in double quotes) and
+ ``bash`` then collapses ``\\\\`` → ``\\`` inside those double quotes,
+ so one level must survive the round trip.
"""
- from tools.environments.local import _bash_safe_path
+ from tools.environments.local import _IS_WINDOWS, _bash_safe_path
- arg = _bash_safe_path(arg)
+ if translate_path:
+ arg = _bash_safe_path(arg)
+ elif _IS_WINDOWS:
+ arg = arg.replace("\\", "\\\\")
# Use single quotes and escape any single quotes in the string
return "'" + arg.replace("'", "'\"'\"'") + "'"
@@ -1410,6 +1420,38 @@ class ShellFileOperations(FileOperations):
_UTF16_MAX_BYTES = 10 * 1024 * 1024
_UTF16_SAMPLE_BYTES = 512
+ def _python_interpreter_cmd(self) -> str:
+ """Return a shell-safe Python interpreter for the terminal backend.
+
+ On the local backend ``sys.executable`` is always a working
+ interpreter — and on Windows it dodges the Microsoft Store
+ ``python``/``python3`` alias stub (exit 49, "Python was not
+ found") that otherwise breaks inline ``-c`` snippets. Remote
+ backends (docker/ssh/...) don't have the agent's interpreter, so
+ they fall back to ``python3`` on their own PATH (the ``python``
+ fallback is handled at the call site).
+ """
+ if self._lsp_local_only():
+ return self._escape_shell_arg(sys.executable)
+ return "python3"
+
+ def _exec_python_snippet(self, snippet: str, py: str = None) -> ExecuteResult:
+ """Run a Python ``snippet`` in the terminal backend's interpreter.
+
+ Base64-encodes the snippet so it survives every shell/quoting layer
+ as pure ASCII: Windows ``subprocess`` list-arg quoting and ``bash``
+ double-quote processing both eat backslashes, which otherwise
+ corrupts Windows paths (``C:\\Users\\x``) and byte literals
+ (``b'\\xfe\\xff'``) embedded in a ``-c`` program. ``exec`` decodes
+ and runs it unchanged.
+ """
+ encoded = base64.b64encode(snippet.encode("utf-8")).decode("ascii")
+ if py is None:
+ py = self._python_interpreter_cmd()
+ return self._exec(
+ f"{py} -c \"import base64; exec(base64.b64decode('{encoded}').decode())\""
+ )
+
def _try_read_utf16(self, path: str, offset: int, limit: int,
file_size: int) -> "Optional[ReadResult]":
"""Attempt to read ``path`` as UTF-16 text, transcoded to UTF-8.
@@ -1429,7 +1471,7 @@ class ShellFileOperations(FileOperations):
snippet = (
"import sys, json, os\n"
- f"p = {path!r}\n"
+ f"p = {json.dumps(path)}\n"
f"offset = {int(offset)}\n"
f"limit = {int(limit)}\n"
f"MAX = {self._UTF16_MAX_BYTES}\n"
@@ -1470,9 +1512,9 @@ class ShellFileOperations(FileOperations):
" print('HERMES_UTF16:NO'); sys.exit(0)\n"
)
- result = self._exec(f"python3 -c {self._escape_shell_arg(snippet)}")
+ result = self._exec_python_snippet(snippet)
if result.exit_code != 0 and "python3" in (result.stdout or ""):
- result = self._exec(f"python -c {self._escape_shell_arg(snippet)}")
+ result = self._exec_python_snippet(snippet, py="python")
stdout = _strip_terminal_fence_leaks(result.stdout or "")
marker = stdout.find("HERMES_UTF16:OK")
@@ -1909,7 +1951,7 @@ class ShellFileOperations(FileOperations):
# snippet via ``repr()`` so quoting is correct on every shell.
snippet = (
"import shutil, pathlib, sys\n"
- f"p = pathlib.Path({path!r})\n"
+ f"p = pathlib.Path({json.dumps(path)})\n"
f"recursive = {bool(recursive)!r}\n"
"try:\n"
" if p.is_dir() and not p.is_symlink():\n"
@@ -1929,12 +1971,12 @@ class ShellFileOperations(FileOperations):
" print(str(exc), file=sys.stderr); sys.exit(1)\n"
)
- result = self._exec(f"python3 -c {self._escape_shell_arg(snippet)}")
+ result = self._exec_python_snippet(snippet)
- # Fall back to ``python`` (Windows / older systems where there's no
+ # Fall back to ``python`` (remote backends / older systems where there's no
# ``python3`` symlink but a ``python`` binary is on PATH).
if result.exit_code != 0 and "python3" in (result.stdout or ""):
- result = self._exec(f"python -c {self._escape_shell_arg(snippet)}")
+ result = self._exec_python_snippet(snippet, py="python")
if result.exit_code != 0:
return WriteResult(error=f"Failed to delete {path}: {(result.stdout or '').strip() or 'unknown error'}")
@@ -2987,10 +3029,10 @@ class ShellFileOperations(FileOperations):
extra = len(per_file) - cap
return shown + (f" (+{extra} more)" if extra > 0 else "")
- glob_expr = f" --glob {self._escape_shell_arg(file_glob)}" if file_glob else ""
+ glob_expr = f" --glob {self._escape_shell_arg(file_glob, translate_path=False)}" if file_glob else ""
probe = self._exec(
f"rg -i --count-matches{glob_expr} "
- f"{self._escape_shell_arg(pattern)} {self._escape_native_tool_arg(path)} "
+ f"{self._escape_shell_arg(pattern, translate_path=False)} {self._escape_native_tool_arg(path)} "
f"2>/dev/null | head -50",
timeout=30,
)
@@ -3007,7 +3049,7 @@ class ShellFileOperations(FileOperations):
# missing from results).
hidden = self._exec(
f"rg --hidden --no-ignore --count-matches{glob_expr} "
- f"{self._escape_shell_arg(pattern)} {self._escape_native_tool_arg(path)} "
+ f"{self._escape_shell_arg(pattern, translate_path=False)} {self._escape_native_tool_arg(path)} "
f"2>/dev/null | head -50",
timeout=30,
)
@@ -3021,7 +3063,7 @@ class ShellFileOperations(FileOperations):
if re.search(r"[.\[\](){}?*+^$\\|]", pattern):
fixed = self._exec(
f"rg -F --count-matches{glob_expr} "
- f"{self._escape_shell_arg(pattern)} {self._escape_native_tool_arg(path)} "
+ f"{self._escape_shell_arg(pattern, translate_path=False)} {self._escape_native_tool_arg(path)} "
f"2>/dev/null | head -50",
timeout=30,
)
@@ -3258,7 +3300,7 @@ class ShellFileOperations(FileOperations):
cmd_parts.append("-c") # Count per file
# Add pattern and path
- cmd_parts.append(self._escape_shell_arg(pattern))
+ cmd_parts.append(self._escape_shell_arg(pattern, translate_path=False))
# rg is a native Windows binary when installed via winget/cargo/choco:
# it needs the C:/... path form, not the MSYS /c/... form (which
# nothing converts back — Hermes sets MSYS_NO_PATHCONV for its bash).
@@ -3418,7 +3460,7 @@ class ShellFileOperations(FileOperations):
# ``.*`` to exclude the entire search. Anchor relative paths at the
# shell's live cwd; quoting $PWD separately keeps user paths escaped
# while working across local, container, and remote backends.
- cmd_parts.append(self._escape_shell_arg(pattern))
+ cmd_parts.append(self._escape_shell_arg(pattern, translate_path=False))
is_absolute = path.startswith(("/", "\\\\")) or bool(
re.match(r"^[A-Za-z]:[\\/]", path)
)
@@ -3467,7 +3509,7 @@ class ShellFileOperations(FileOperations):
grep_parts.append("-l")
elif output_mode == "count":
grep_parts.append("-c")
- grep_parts.append(self._escape_shell_arg(pattern))
+ grep_parts.append(self._escape_shell_arg(pattern, translate_path=False))
prune_terms = " -o ".join(
f"-path {self._escape_shell_arg(item)}" for item in protected_paths
diff --git a/tools/registry.py b/tools/registry.py
index bf6d52f2ee6..4eb4411cb5b 100644
--- a/tools/registry.py
+++ b/tools/registry.py
@@ -550,6 +550,7 @@ class ToolRegistry:
scope: Optional[str] = None,
) -> Optional[ToolEntry]:
"""Return the local slot state without following global fallback."""
+ scope = hermes_home_key(scope) if scope is not None else None
with self._lock:
target = self._tools if scope is None else self._scoped_tools.get(scope, {})
return target.get(name)
@@ -607,6 +608,7 @@ class ToolRegistry:
The identity-bearing result lets plugin unload/reload revoke a stale
authorization without losing durable module-to-profile attribution.
"""
+ scope = hermes_home_key(scope) if scope is not None else None
with self._lock:
policy = _PluginOverridePolicy(allowed)
self._plugin_override_policy[(scope, module_namespace)] = policy
@@ -620,6 +622,7 @@ class ToolRegistry:
scope: Optional[str] = None,
) -> Optional[_PluginOverridePolicy]:
"""Return one local authorization generation without fallback."""
+ scope = hermes_home_key(scope) if scope is not None else None
with self._lock:
return self._plugin_override_policy.get((scope, module_namespace))
@@ -632,6 +635,7 @@ class ToolRegistry:
scope: Optional[str] = None,
) -> bool:
"""CAS-restore policy state while retaining durable scope attribution."""
+ scope = hermes_home_key(scope) if scope is not None else None
with self._lock:
key = (scope, module_namespace)
if self._plugin_override_policy.get(key) is not current:
@@ -789,6 +793,7 @@ class ToolRegistry:
owner = caller_owner or handler_owner
if scope is None and owner is not None:
scope = self._plugin_scope_of(owner)
+ scope = hermes_home_key(scope) if scope is not None else None
with self._lock:
target = (
self._tools
@@ -986,6 +991,7 @@ class ToolRegistry:
newer entry under the same name, in which case unloading this entry
must leave the newer entry untouched.
"""
+ scope = hermes_home_key(scope) if scope is not None else None
with self._lock:
target = (
self._tools
diff --git a/tools/skills_tool.py b/tools/skills_tool.py
index 53d7947aa8e..9e4db9c54bb 100644
--- a/tools/skills_tool.py
+++ b/tools/skills_tool.py
@@ -1646,7 +1646,7 @@ def skill_view(
references_dir = skill_dir / "references"
if references_dir.exists():
reference_files = [
- str(f.relative_to(skill_dir)) for f in references_dir.glob("*.md")
+ f.relative_to(skill_dir).as_posix() for f in references_dir.glob("*.md")
]
templates_dir = skill_dir / "templates"
@@ -1662,7 +1662,7 @@ def skill_view(
]:
template_files.extend(
[
- str(f.relative_to(skill_dir))
+ f.relative_to(skill_dir).as_posix()
for f in templates_dir.rglob(ext)
]
)
@@ -1672,13 +1672,13 @@ def skill_view(
if assets_dir.exists():
for f in assets_dir.rglob("*"):
if f.is_file():
- asset_files.append(str(f.relative_to(skill_dir)))
+ asset_files.append(f.relative_to(skill_dir).as_posix())
scripts_dir = skill_dir / "scripts"
if scripts_dir.exists():
for ext in ["*.py", "*.sh", "*.bash", "*.js", "*.ts", "*.rb"]:
script_files.extend(
- [str(f.relative_to(skill_dir)) for f in scripts_dir.glob(ext)]
+ [f.relative_to(skill_dir).as_posix() for f in scripts_dir.glob(ext)]
)
# Read tags/related_skills with backward compat:
diff --git a/website/scripts/generate-llms-txt.py b/website/scripts/generate-llms-txt.py
index 91caeb4ad37..2dcfc3e61d9 100644
--- a/website/scripts/generate-llms-txt.py
+++ b/website/scripts/generate-llms-txt.py
@@ -226,7 +226,7 @@ def slug_for(path: Path) -> str:
rel = path.relative_to(DOCS).with_suffix("")
if rel.name == "index":
rel = rel.parent
- return "" if str(rel) == "." else str(rel)
+ return "" if str(rel) == "." else rel.as_posix()
def doc_path(slug: str) -> Path | None: