"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(tests): sandbox the suite's config root before collection on Windows
lorenzozanee82bcc5adbb49
diff --git a/agent/src/core/runner.py b/agent/src/core/runner.pyindex caed5461c..2e01cd273 100644--- a/agent/src/core/runner.py+++ b/agent/src/core/runner.py@@ -129,12 +129,27 @@ def _prepare_sandbox_home(real_home: Path | None) -> Path:src = src_root / relif not src.exists():continue+ dst = dst_root / reltry:- (dst_root / rel).symlink_to(src, target_is_directory=src.is_dir())+ dst.symlink_to(src, target_is_directory=src.is_dir())except OSError:- # Best-effort: a loader that can't find its config just falls- # back to a live fetch / disabled cache — never a hard break.- pass+ # Symlinks need privileges on Windows, so they can fail even+ # when nothing is fundamentally wrong. Fall back to a copy:+ # the loader cache/config paths stay visible to the subprocess+ # (the whole point of the re-exposure) without privileges.+ # Copies are per-run snapshots that the existing sandbox+ # cleanup removes, so the opt-in cache stops persisting across+ # runs only on hosts that cannot create symlinks.+ try:+ if src.is_dir():+ shutil.copytree(src, dst, dirs_exist_ok=True)+ else:+ shutil.copy2(src, dst)+ except OSError:+ # Best-effort: a loader that can't find its config just+ # falls back to a live fetch / disabled cache — never a+ # hard break.+ passtry:os.chmod(dst_root, 0o755)except OSError:diff --git a/agent/tests/conftest.py b/agent/tests/conftest.pyindex a8b702aaa..8d2616c39 100644--- a/agent/tests/conftest.py+++ b/agent/tests/conftest.py@@ -2,7 +2,11 @@from __future__ import annotations+import atexit+import os+import shutilimport sys+import tempfilefrom pathlib import Pathimport pytest@@ -12,6 +16,77 @@ AGENT_DIR = Path(__file__).resolve().parent.parentif str(AGENT_DIR) not in sys.path:sys.path.insert(0, str(AGENT_DIR))+# --------------------------------------------------------------------------- #+# Sandbox the config runtime root BEFORE any test module is imported (#1116).+# --------------------------------------------------------------------------- #+# The suite must never resolve its config root against the real ~/.vibe-trading+# (live mandate + audit-ledger state). Modules in BOTH categories must resolve+# to a temp sandbox:+#+# * Import-time-baked constants (bound when the module is first imported,+# i.e. during collection): loop.RUNS_DIR/SESSIONS_DIR, goal/session+# _DB_PATH, helpers.ENV_PATH, memory MEMORY_BASE, skills USER_SKILLS_DIR,+# strategy_store _DEFAULT_DB_PATH, swarm presets USER_PRESETS_DIR,+# qveris QVERIS_CONFIG_PATH.+# * Runtime Path.home() call sites: redaction's internal-root anchors+# (_internal_roots_for_cwd), alpha_bench report output (_default_output_dir),+# autopilot run dirs, uploads shadow_reports.+#+# Because the import-time constants are baked during test-module collection, the+# sandbox cannot be a pytest fixture (fixtures run AFTER collection); it has to+# be installed at conftest import time, before pytest imports any test module.+#+# TEST DISCIPLINE: a test that asserts the DEFAULT config-root fallback (e.g.+# ``get_runtime_root() == Path.home()/".vibe-trading"``) MUST call+# ``monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)`` first, so it+# exercises the real fallback instead of silently passing green against this+# sandbox.+#+# On Windows Path.home() ignores $HOME and reads %USERPROFILE%, so we set all+# three knobs: VIBE_TRADING_HOME (the project's documented Windows-safe+# override, src/config/paths.py:27-33), HOME (POSIX) and USERPROFILE (Windows).+_PRIOR_SANDBOX_ENV = {+ key: os.environ.get(key) for key in ("VIBE_TRADING_HOME", "HOME", "USERPROFILE")+}+_SANDBOX_HOME = Path(tempfile.mkdtemp(prefix="vibe-trading-test-home-"))+os.environ["VIBE_TRADING_HOME"] = str(_SANDBOX_HOME / ".vibe-trading")+os.environ["HOME"] = str(_SANDBOX_HOME)+os.environ["USERPROFILE"] = str(_SANDBOX_HOME)+(_SANDBOX_HOME / ".vibe-trading").mkdir(parents=True, exist_ok=True)+++def _teardown_sandbox() -> None:+ shutil.rmtree(_SANDBOX_HOME, ignore_errors=True)+ for key, prior in _PRIOR_SANDBOX_ENV.items():+ if prior is None:+ os.environ.pop(key, None)+ else:+ os.environ[key] = prior+++# Safety net for e.g. `--collect-only` (no fixtures run) and abnormal exits.+atexit.register(_teardown_sandbox)++[email protected](autouse=True, scope="session")+def _sandbox_runtime_root():+ """Guard the import-time sandbox and tear it down at session end.++ The environment (VIBE_TRADING_HOME/HOME/USERPROFILE) is installed at+ conftest import time above — before collection — so both import-time-baked+ constants and runtime ``Path.home()`` calls resolve to the temp sandbox,+ never the real ``~/.vibe-trading``. This fixture only asserts that the+ invariant is still active and removes the temp dir at session end. The+ function-scoped ``_reset_env_config`` fixture snapshots the environment each+ test, so the sandbox values survive every test while per-test monkeypatches+ still work.+ """+ assert os.environ["VIBE_TRADING_HOME"] == str(_SANDBOX_HOME / ".vibe-trading")+ assert os.environ["HOME"] == str(_SANDBOX_HOME)+ assert os.environ["USERPROFILE"] == str(_SANDBOX_HOME)+ yield _SANDBOX_HOME / ".vibe-trading"+ _teardown_sandbox()+@pytest.fixture(autouse=True)def _reset_env_config():@@ -33,8 +108,6 @@ def _reset_env_config():Snapshotting and restoring the whole environment closes the class of bugrather than the one instance of it."""- import os-from src.config.accessor import reset_env_configsaved_environ = dict(os.environ)diff --git a/agent/tests/test_agent_config.py b/agent/tests/test_agent_config.pyindex c0a29eca8..d0d877777 100644--- a/agent/tests/test_agent_config.py+++ b/agent/tests/test_agent_config.py@@ -340,11 +340,14 @@ def test_runtime_overrides_fall_back_to_base_config_when_merge_is_invalid(tmp_paassert config.mcp_servers["demo"].args == ["--base"]-def test_explicit_config_path_does_not_mutate_default_runtime_root(tmp_path: Path) -> None:+def test_explicit_config_path_does_not_mutate_default_runtime_root(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:config_path = tmp_path / "nested" / "agent.json"load_agent_config(config_path)assert get_runtime_root(config_path) == config_path.parent+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)assert get_runtime_root() == Path.home() / ".vibe-trading"assert get_config_path(config_path) == config_path@@ -412,6 +415,7 @@ def test_live_authorize_missing_robinhood_config_prints_safe_seed() -> None:from cli._legacy import EXIT_USAGE_ERROR, cmd_live_authorize+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)monkeypatch.setattr(Path, "home", lambda: tmp_path)assert cmd_live_authorize("robinhood") == EXIT_USAGE_ERROR@@ -432,6 +436,7 @@ def test_live_authorize_wildcard_robinhood_config_prints_safe_seed() -> None:from cli._legacy import EXIT_USAGE_ERROR, cmd_live_authorize+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)monkeypatch.setattr(Path, "home", lambda: tmp_path)config_path = tmp_path / ".vibe-trading" / "agent.json"config_path.parent.mkdir(parents=True)diff --git a/agent/tests/test_api_live_runtime.py b/agent/tests/test_api_live_runtime.pyindex f000c7d76..3a7d3cfe1 100644--- a/agent/tests/test_api_live_runtime.py+++ b/agent/tests/test_api_live_runtime.py@@ -26,6 +26,7 @@ def _client(tmp_path: Path, monkeypatch) -> TestClient:# Redirect the runtime root (``~/.vibe-trading``) at the home boundary so the# live tree, HALT sentinel, mandate store, and proposal store all resolve# under tmp_path. get_runtime_root() == Path.home() / ".vibe-trading".+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)monkeypatch.setattr(api_server, "_runner_tasks", {}, raising=False)monkeypatch.setattr(api_server, "_runner_factory", None, raising=False)@@ -260,6 +261,7 @@ def _seed_proposal(tmp_path: Path, proposal_id: str, broker: str = "robinhood")def test_c1_relay_builds_mandate_proposal_frame(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)proposal_id = "mp_" + "1" * 32_seed_proposal(tmp_path, proposal_id)@@ -282,6 +284,7 @@ def test_c1_relay_builds_mandate_proposal_frame(tmp_path: Path, monkeypatch) ->def test_c1_relay_ignores_non_propose_events(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)# A different tool's result: no relay.@@ -298,6 +301,7 @@ def test_c1_relay_ignores_non_propose_events(tmp_path: Path, monkeypatch) -> Nondef test_c1_relay_returns_none_when_proposal_missing(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)# Preview references an id with no persisted proposal on disk.event = SimpleNamespace(@@ -318,6 +322,7 @@ def test_c1_relay_returns_none_when_proposal_missing(tmp_path: Path, monkeypatchdef test_build_live_runner_no_broker_configured_raises_unavailable(tmp_path, monkeypatch) -> None:+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)monkeypatch.setattr(api_server, "_runner_factory", None, raising=False)# No robinhood MCP server in the default config → clean 503-class error,@@ -329,6 +334,7 @@ def test_build_live_runner_no_broker_configured_raises_unavailable(tmp_path, mondef test_build_live_runner_wires_a_real_runner(tmp_path, monkeypatch) -> None:+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)monkeypatch.setattr(api_server, "_runner_factory", None, raising=False)@@ -388,6 +394,7 @@ def _seed_ledger(tmp_path: Path, record: dict) -> None:def test_live_action_relay_builds_frame_from_guard_result(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)audit_id = "la_01abcDEF"_seed_ledger(tmp_path, {"audit_id": audit_id, "kind": "order_placed", "outcome": "accepted",@@ -410,6 +417,7 @@ def test_live_action_relay_builds_frame_from_guard_result(tmp_path: Path, monkeydef test_live_action_relay_ignores_non_live_results(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)# A normal tool_result with no live_action marker → no relay.event = SimpleNamespace(diff --git a/agent/tests/test_channel_media_roots.py b/agent/tests/test_channel_media_roots.pyindex 8208a7e04..9916338a7 100644--- a/agent/tests/test_channel_media_roots.py+++ b/agent/tests/test_channel_media_roots.py@@ -6,6 +6,7 @@ from pathlib import Pathdef test_media_dir_lives_under_uploads_root(tmp_path, monkeypatch):+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)from src.channels.utils import get_media_dir@@ -16,6 +17,7 @@ def test_media_dir_lives_under_uploads_root(tmp_path, monkeypatch):def test_media_dir_is_within_allowed_file_roots(tmp_path, monkeypatch):+ monkeypatch.delenv("VIBE_TRADING_HOME", raising=False)monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path), raising=False)from src.channels.utils import get_media_dirdiff --git a/agent/tests/test_config_root_sandbox.py b/agent/tests/test_config_root_sandbox.pynew file mode 100644index 000000000..1c7caef9b--- /dev/null+++ b/agent/tests/test_config_root_sandbox.py@@ -0,0 +1,78 @@+"""Regression tests for the sandboxed runtime root (issue #1116).++The test suite must never resolve its config root against the real home+directory. On Windows, ``Path.home()`` ignores ``$HOME`` and reads+``%USERPROFILE%``, so the suite's historical ``HOME``-based isolation idiom is+inert there and tests leaked into the real ``~/.vibe-trading`` (including the+live audit ledger). ``conftest.py`` installs ``VIBE_TRADING_HOME``/``HOME``/+``USERPROFILE`` at import time (before collection, so import-time-baked+constants also resolve there) to a temp sandbox root — the project's documented+Windows-safe override — and these tests pin that contract.++NOTE: the base-failure signature of these tests depends on ``VIBE_TRADING_HOME``+being unset in the ambient environment. A CI runner that pre-sets it (rather+than letting ``conftest.py`` install the sandbox) would not see the red/green+regression signal this file is meant to produce.+"""++from __future__ import annotations++import os+import tempfile+from pathlib import Path++import pytest++from src.config.paths import get_runtime_root+from src.live.audit import audit_ledger_path+from src.live.paths import live_root+++def test_sandbox_runtime_root_is_active() -> None:+ """The import-time sandbox must have pointed the runtime root at a sandbox."""+ sandbox_root = os.environ.get("VIBE_TRADING_HOME")+ assert sandbox_root, (+ "VIBE_TRADING_HOME is unset — the conftest sandbox is not active; "+ "without it tests resolve the real ~/.vibe-trading (issue #1116)"+ )+ sandbox_root = Path(sandbox_root)++ # The root must live under the system temp dir — a temp sandbox, not a+ # non-temp value a broken setup could otherwise point VIBE_TRADING_HOME at.+ assert sandbox_root.is_relative_to(Path(tempfile.gettempdir()))+ assert sandbox_root.is_absolute()+ assert get_runtime_root() == sandbox_root+++def test_windows_home_semantics_still_resolve_under_sandbox_root(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ """Windows ``Path.home()`` ignores ``HOME``; it must not escape the sandbox.++ Simulates the Windows failure from issue #1116: a fake "real home" is+ installed into BOTH ``HOME`` and ``USERPROFILE`` (Windows ``Path.home()``+ reads the latter). The runtime root must still resolve under the sandbox+ ``VIBE_TRADING_HOME``, never under the fake real home.+ """+ fake_real_home = tmp_path / "real-home"+ monkeypatch.setenv("HOME", str(fake_real_home))+ monkeypatch.setenv("USERPROFILE", str(fake_real_home))++ sandbox_root = os.environ.get("VIBE_TRADING_HOME")+ assert sandbox_root, (+ "VIBE_TRADING_HOME is unset — the conftest sandbox is not active; "+ "without it get_runtime_root() falls back to Path.home()/.vibe-trading, "+ "which resolves to the fake real home under Windows HOME/USERPROFILE "+ "semantics (issue #1116)"+ )+ sandbox_root = Path(sandbox_root)++ # Temp sandbox, not the real home — same mutation-gap closure as Test 1.+ assert sandbox_root.is_relative_to(Path(tempfile.gettempdir()))+ assert get_runtime_root() == sandbox_root+ assert get_runtime_root() != fake_real_home / ".vibe-trading"+ assert live_root() == sandbox_root / "live"+ # The issue's headline harm: the live audit ledger must also resolve under the+ # sandbox, never the real ~/.vibe-trading.+ assert audit_ledger_path() == sandbox_root / "live" / "audit.jsonl"diff --git a/agent/tests/test_daily_count.py b/agent/tests/test_daily_count.pyindex 7e5a405cd..0463a2923 100644--- a/agent/tests/test_daily_count.py+++ b/agent/tests/test_daily_count.py@@ -26,6 +26,7 @@ except DailyOrderLockUnavailable:"""env = os.environ.copy()env["HOME"] = str(home)+ env["VIBE_TRADING_HOME"] = str(home / ".vibe-trading")env["PYTHONPATH"] = str(repo_root / "agent")return subprocess.run([sys.executable, "-c", script],diff --git a/agent/tests/test_loader_retry_helpers.py b/agent/tests/test_loader_retry_helpers.pyindex 52f349c92..2c9fea5c3 100644--- a/agent/tests/test_loader_retry_helpers.py+++ b/agent/tests/test_loader_retry_helpers.py@@ -263,6 +263,7 @@ def test_stubbed_config_cannot_enable_cache_or_redirect_root_into_cwd(monkeypatchome = tmp_path / "home"monkeypatch.setenv("HOME", str(home))+ monkeypatch.setenv("USERPROFILE", str(home))stub = MagicMock()monkeypatch.setattr("src.config.accessor.get_env_config", lambda: stub, raising=Falsediff --git a/agent/tests/test_mt5_connector.py b/agent/tests/test_mt5_connector.pyindex 9375e32cb..b49f1454f 100644--- a/agent/tests/test_mt5_connector.py+++ b/agent/tests/test_mt5_connector.py@@ -203,6 +203,7 @@ def fake_mt5(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> FakeMT5:fake = FakeMT5()monkeypatch.setattr(_client, "_require_mt5", lambda: fake)monkeypatch.setattr(_client, "get_runtime_root", lambda: tmp_path)+ monkeypatch.setattr("src.live.paths.get_runtime_root", lambda: tmp_path)return fakediff --git a/agent/tests/test_runner_env.py b/agent/tests/test_runner_env.pyindex f4c239ab8..131a2284b 100644--- a/agent/tests/test_runner_env.py+++ b/agent/tests/test_runner_env.py@@ -185,6 +185,44 @@ def test_prepare_sandbox_home_reexposes_only_loader_paths(tmp_path: Path) -> Nonassert (vt / "cache").exists()+def test_prepare_sandbox_home_copy_fallback_when_symlink_privileges_missing(+ monkeypatch, tmp_path: Path+) -> None:+ """Windows cannot always create symlinks; the copy fallback must still work.++ On Windows, ``symlink_to`` can raise OSError 1314 (privilege not held) even+ in an otherwise healthy environment. ``_prepare_sandbox_home`` must then copy+ the loader-owned paths so the subprocess still sees them, and must still keep+ persistent secrets/state out of the ephemeral home.+ """+ real_home = tmp_path / "home"+ vt = real_home / ".vibe-trading"+ (vt / "cache").mkdir(parents=True)+ (vt / "data-bridge").mkdir(parents=True)+ (vt / "qveris.json").write_text("{}", encoding="utf-8")++ def _deny_symlink(*args, **kwargs):+ raise OSError(1314, "A required privilege is not held by the client")++ monkeypatch.setattr(Path, "symlink_to", _deny_symlink)++ sandbox = _prepare_sandbox_home(real_home)+ try:+ dst_vt = sandbox / ".vibe-trading"+ # Symlinks were impossible, yet the loader paths are still present...+ assert (dst_vt / "cache").is_dir()+ assert (dst_vt / "data-bridge").is_dir()+ assert (dst_vt / "qveris.json").is_file()+ # ...and the persistent secrets/state are still NOT re-exposed.+ assert not (dst_vt / ".env").exists()+ assert not (dst_vt / "memory").exists()+ finally:+ import shutil++ shutil.rmtree(sandbox, ignore_errors=True)+ assert not sandbox.exists()++def test_prepare_sandbox_home_preseeds_mootdx_config(tmp_path: Path) -> None:sandbox = _prepare_sandbox_home(tmp_path)try: