Skip to content

The agent that grows with you

test: real-home tripwire — fail ANY test that touches the real HERMES_HOME

ethernet979c9cf8b687
diff --git a/tests/conftest.py b/tests/conftest.py
index 6153db600b7..c018f65b35f 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1752,3 +1752,161 @@ def _moa_caches_isolated():
yield
moa._preset_cache.clear()
moa._runtime_cache.clear()
+
+
+# ── Real-home tripwire (universal read/write guard) ──────────────────────────
+# The hermetic sandbox redirects get_hermes_home(), but TWO escape classes
+# remain: (a) code hardcoding Path.home()/".hermes" (the exact restatement
+# class AGENTS.md bans — the Path.home()/.hermes/profiles bug the 2026-09-03
+# deployment review caught in pm/plugins_state.py), and (b) imports freezing
+# real-home paths before fixtures run. The kanban guard (#69283) covers one
+# subsystem; this covers EVERY file operation: any open()/mkdir/stat-family
+# call resolving under the REAL hermes root fails the test immediately
+# with a message naming the path — reads AND writes (a read of production
+# state is as much a leak as a write: it drags fixture rows and real config
+# into test assertions).
+#
+# The real root is captured at conftest import (pre-sandbox), honoring a
+# genuinely-custom pre-set HERMES_HOME exactly like the kanban deny-list
+# (_hermes_home_points_at_production governs which values count).
+_REAL_HERMES_ROOT_CANDIDATES: list[Path] = []
+
+
+def _capture_real_hermes_root() -> list[Path]:
+ """The real root(s) to refuse: the default ~/.hermes plus a pre-sandbox
+ custom HERMES_HOME when one was set. Both are guarded — the default
+ because hardcoded restatements hit it; the custom one because
+ deployment-shaped tests (Docker /opt/data) must not touch the operator's
+ real custom root either."""
+ import platform
+
+ roots: list[Path] = []
+ try:
+ default_root = (Path.home() / ".hermes").resolve()
+ roots.append(default_root)
+ except Exception:
+ pass
+ # native-Windows default: %LOCALAPPDATA%\hermes (get_hermes_home's
+ # platform-native path) — guard it too
+ localappdata = os.environ.get("LOCALAPPDATA", "")
+ if localappdata:
+ try:
+ win_root = (Path(localappdata) / "hermes").resolve()
+ if win_root not in roots:
+ roots.append(win_root)
+ except Exception:
+ pass
+ if _PRE_SANDBOX_HERMES_HOME and not _hermes_home_points_at_production(
+ _PRE_SANDBOX_HERMES_HOME
+ ):
+ try:
+ custom = Path(_PRE_SANDBOX_HERMES_HOME).expanduser().resolve()
+ if custom not in roots:
+ roots.append(custom)
+ except Exception:
+ pass
+ return roots
+
+
+_REAL_HERMES_ROOT_CANDIDATES = _capture_real_hermes_root()
+
+
+def _path_hits_real_home(candidate) -> bool:
+ """True when candidate resolves under any guarded real root."""
+ try:
+ resolved = Path(candidate).expanduser().resolve()
+ except Exception:
+ return False
+ for root in _REAL_HERMES_ROOT_CANDIDATES:
+ try:
+ resolved.relative_to(root)
+ return True
+ except ValueError:
+ continue
+ return False
+
+
[email protected](autouse=True)
+def _forbid_real_hermes_home_io(monkeypatch, request):
+ """Fail ANY test that opens/mkdirs/stats under the REAL hermes home.
+
+ Opt-out for the (rare) test that legitimately inspects the guard
+ itself or documents a real-path read: @pytest.mark.allow_real_home_io.
+ Everything else gets the tripwire.
+
+ Implementation: wrap builtins.open (covers ~all file I/O incl. pathlib
+ read_text/write_text which call io.open) plus os.mkdir/os.makedirs for
+ directory creation. Guard the check itself with try/except so a weird
+ path never breaks the wrapper.
+ """
+ if request.node.get_closest_marker("allow_real_home_io"):
+ return
+
+ import builtins as _builtins
+
+ real_open = _builtins.open
+
+ def _guarded_open(file, *args, **kwargs):
+ try:
+ if _path_hits_real_home(file):
+ raise AssertionError(
+ f"TEST BUG: file I/O against the REAL hermes home: "
+ f"{file}\n"
+ "The hermetic sandbox redirects get_hermes_home(); this "
+ "path bypasses it (hardcoded Path.home()/.hermes, a "
+ "frozen import-time path, or an explicit real path). "
+ "Use get_hermes_home()/the isolated fixture instead."
+ )
+ except AssertionError:
+ raise
+ except Exception:
+ pass
+ return real_open(file, *args, **kwargs)
+
+ monkeypatch.setattr(_builtins, "open", _guarded_open)
+
+ real_mkdir = os.mkdir
+ real_makedirs = os.makedirs
+
+ def _guarded_mkdir(path, *args, **kwargs):
+ if _path_hits_real_home(path):
+ pytest.fail(
+ f"TEST BUG: mkdir against the REAL hermes home: {path}",
+ pytrace=False,
+ )
+ return real_mkdir(path, *args, **kwargs)
+
+ def _guarded_makedirs(path, *args, **kwargs):
+ if _path_hits_real_home(path):
+ pytest.fail(
+ f"TEST BUG: makedirs against the REAL hermes home: {path}",
+ pytrace=False,
+ )
+ return real_makedirs(path, *args, **kwargs)
+
+ monkeypatch.setattr(os, "mkdir", _guarded_mkdir)
+ monkeypatch.setattr(os, "makedirs", _guarded_makedirs)
+
+
[email protected](autouse=True)
+def _forbid_real_hermes_home_sqlite(monkeypatch, request):
+ """sqlite3.connect bypasses builtins.open (C-level open) — guard it
+ directly: a DB path resolving under the REAL hermes home fails the
+ test (the state.db-under-~/.hermes leak the session sandbox docs the
+ history of). Same opt-out marker as the file guard."""
+ if request.node.get_closest_marker("allow_real_home_io"):
+ return
+
+ import sqlite3 as _sqlite3
+
+ real_connect = _sqlite3.connect
+
+ def _guarded_connect(database, *args, **kwargs):
+ if isinstance(database, (str, bytes, Path)) and _path_hits_real_home(database):
+ pytest.fail(
+ f"TEST BUG: sqlite connect against the REAL hermes home: {database}",
+ pytrace=False,
+ )
+ return real_connect(database, *args, **kwargs)
+
+ monkeypatch.setattr(_sqlite3, "connect", _guarded_connect)
diff --git a/tests/hermes_cli/test_real_home_tripwire.py b/tests/hermes_cli/test_real_home_tripwire.py
new file mode 100644
index 00000000000..dc939ae3820
--- /dev/null
+++ b/tests/hermes_cli/test_real_home_tripwire.py
@@ -0,0 +1,91 @@
+"""The real-home tripwire: tests touching the REAL hermes home must fail.
+
+The guard (conftest _forbid_real_hermes_home_io) exists to catch the
+hardcoded-restatement bug class — code writing Path.home()/".hermes"
+instead of get_hermes_home(). These tests prove the tripwire fires.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+
+def test_read_from_real_home_fails():
+ """Reading production state in a test is a leak — must trip."""
+ from tests.conftest import _REAL_HERMES_ROOT_CANDIDATES
+
+ assert _REAL_HERMES_ROOT_CANDIDATES, "guard roots not captured"
+ root = _REAL_HERMES_ROOT_CANDIDATES[0]
+ sentinel = root / "tripwire-probe-should-fail.txt"
+ # the wrapper must raise AssertionError (not create/read anything)
+ with pytest.raises(AssertionError, match="REAL hermes home"):
+ # open() for READ on a nonexistent file still trips the guard
+ # BEFORE the OS error — the check is path-based, not result-based
+ with open(sentinel, "r", encoding="utf-8"):
+ pass
+
+
+def test_write_to_real_home_fails():
+ root = Path.home() / ".hermes"
+ sentinel = root / "tripwire-probe-write-should-fail.json"
+ with pytest.raises(AssertionError, match="REAL hermes home"):
+ with open(sentinel, "w", encoding="utf-8") as f:
+ f.write("should never land")
+
+
+def test_mkdir_under_real_home_fails(tmp_path):
+ # os.mkdir with a real-home target (parent must exist for mkdir; use
+ # makedirs which creates parents — both are guarded)
+ with pytest.raises(pytest.fail.Exception):
+ import os
+
+ os.makedirs(str(Path.home() / ".hermes" / "tripwire-deep" / "dir"), exist_ok=True)
+
+
+def test_isolated_home_io_still_works(tmp_path):
+ """The happy path: tempdir (the sandboxed HERMES_HOME shape) is NOT
+ under the real root — ordinary I/O must be completely unaffected."""
+ target = tmp_path / "fine.json"
+ with open(target, "w", encoding="utf-8") as f:
+ f.write("ok")
+ with open(target, encoding="utf-8") as f:
+ assert f.read() == "ok"
+
+
+def test_profile_paths_under_real_root_also_trip():
+ """<root>/profiles/<name> is inside the guarded root — the deployment
+ bug class (pm/plugins_state Path.home()/.hermes/profiles) trips."""
+ with pytest.raises(AssertionError, match="REAL hermes home"):
+ with open(
+ Path.home() / ".hermes" / "profiles" / "some-profile" / "config.yaml",
+ "r",
+ encoding="utf-8",
+ ):
+ pass
+
+
[email protected]_real_home_io
+def test_opt_out_marker_bypasses_guard(tmp_path):
+ """The documented escape hatch: marked tests read real paths freely
+ (the guard's own tests inspect conftest internals)."""
+ # just exercising that the fixture returns without wrapping
+ assert True
+
+
+def test_sqlite_connect_to_real_home_fails():
+ """sqlite3 bypasses builtins.open (C-level) — the dedicated hook must
+ catch a state.db-shaped leak under ~/.hermes."""
+ import sqlite3
+
+ with pytest.raises(pytest.fail.Exception):
+ sqlite3.connect(str(Path.home() / ".hermes" / "state.db"))
+
+
+def test_sqlite_connect_to_tempdir_still_works(tmp_path):
+ import sqlite3
+
+ con = sqlite3.connect(str(tmp_path / "fine.db"))
+ con.execute("CREATE TABLE t (x)")
+ con.close()