"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(windows): cross-platform locks, path handling, and test robustness
Emad Karimi5c28d4934bcd
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 923c108cb..f2a323304 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -720,8 +720,11 @@ def _looks_like_tool_call_syntax(content: str) -> bool:# create or update ("update C:\\...\\plan.md"). If a run approaches its# iteration cap without having written that file, the loop must remind the# model instead of ending "answered but incomplete".+# Windows absolute paths may contain spaces (e.g. C:\Users\Emad Karimi\...),+# so the drive-letter branch allows spaces and stops non-greedily at the first+# ".md"; the POSIX and bare-name branches stay space-free word matches._TARGET_PATH_RE = re.compile(- r"[A-Za-z]:\\[^\s\x22\x27<>|?*]+\.md\b"+ r"[A-Za-z]:\\[^<>|?*\x22\x27\r\n]+?\.md\b"r"|/[\w./\\-]+\.md\b"r"|\b[\w./\\-]+\.md\b")@@ -862,7 +865,7 @@ def _archive_backtest_result(result: str, active_run_dir: str | None) -> bool:if source_dir.is_dir():shutil.copytree(source_dir, target / directory, dirs_exist_ok=True)archived += [- str(path.relative_to(source))+ path.relative_to(source).as_posix()for path in source_dir.rglob("*")if path.is_file()]diff --git a/agent/src/governance/ledger.py b/agent/src/governance/ledger.pyindex e24e09456..8ece74049 100644--- a/agent/src/governance/ledger.py+++ b/agent/src/governance/ledger.py@@ -330,10 +330,10 @@ def _lock_exclusive(handle: BinaryIO) -> None:fcntl.flock(handle.fileno(), fcntl.LOCK_EX)returnif msvcrt is not None: # pragma: no cover - exercised on Windows CI- handle.seek(0, os.SEEK_END)- if handle.tell() == 0:- handle.write(b"\0")- handle.flush()+ # Windows byte-range locks are valid beyond EOF, so an empty ledger is+ # locked at offset 0 WITHOUT writing anything. Writing a b"\0" sentinel+ # made the chain walk see a malformed line 0 and refuse every first+ # append with LedgerCorruptionError.handle.seek(0)msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)returndiff --git a/agent/src/live/daily_count.py b/agent/src/live/daily_count.pyindex 5d02c1b14..724925f29 100644--- a/agent/src/live/daily_count.py+++ b/agent/src/live/daily_count.py@@ -55,10 +55,7 @@ def _try_lock(handle: BinaryIO) -> None:fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)returnif msvcrt is not None: # pragma: no cover - exercised on Windows CI- handle.seek(0, os.SEEK_END)- if handle.tell() == 0:- handle.write(b"\0")- handle.flush()+ # Lock byte 0 beyond EOF without writing a sentinel byte (see ledger.py).handle.seek(0)msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)returndiff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.pyindex b2e9ddeb1..b8043242f 100644--- a/agent/src/providers/llm.py+++ b/agent/src/providers/llm.py@@ -1190,7 +1190,12 @@ def _build_anthropic(def _load_env_file(path: Path) -> None:- """Load a single .env file into os.environ (setdefault, no override)."""+ """Load a single .env file into os.environ without clobbering real vars.++ Exported environment variables are explicit operator intent and outrank+ the file; ``.env`` only fills the gaps (pinned by+ ``test_dispatch_connector_never_overrides_a_real_environment_variable``).+ """if load_dotenv is not None:load_dotenv(dotenv_path=path, override=False)else:@@ -1200,8 +1205,8 @@ def _load_env_file(path: Path) -> None:continuekey, value = line.split("=", 1)key = key.strip()- if key:- os.environ.setdefault(key, value.strip().strip('"').strip("'"))+ if key and key not in os.environ:+ os.environ[key] = value.strip().strip('"').strip("'")def _ensure_dotenv() -> None:diff --git a/agent/src/providers/openai_codex.py b/agent/src/providers/openai_codex.pyindex 97c96a1a5..262320633 100644--- a/agent/src/providers/openai_codex.py+++ b/agent/src/providers/openai_codex.py@@ -131,11 +131,7 @@ def _lock_token_file(handle: Any) -> None:fcntl.flock(handle.fileno(), fcntl.LOCK_EX)returnif msvcrt is not None: # pragma: no cover - exercised with a platform mock.- handle.seek(0, os.SEEK_END)- if handle.tell() == 0:- handle.write(b"\0")- handle.flush()- os.fsync(handle.fileno())+ # Lock byte 0 beyond EOF without writing a sentinel byte (see ledger.py).handle.seek(0)msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)returndiff --git a/agent/tests/test_alpha_bench_cache.py b/agent/tests/test_alpha_bench_cache.pyindex ca681caa8..9df5ff6a9 100644--- a/agent/tests/test_alpha_bench_cache.py+++ b/agent/tests/test_alpha_bench_cache.py@@ -9,6 +9,7 @@ sidecar, so the tampered blob is rejected before ``pickle.loads``.from __future__ import annotationsimport hashlib+import osimport pickleimport stat@@ -72,7 +73,8 @@ def test_fallback_key_is_stable_and_0600(tmp_path, no_api_key):key_file = tmp_path / ".hmac_key"assert key_file.is_file()- assert stat.S_IMODE(key_file.stat().st_mode) == 0o600+ if os.name == "posix":+ assert stat.S_IMODE(key_file.stat().st_mode) == 0o600def test_configured_api_key_takes_priority(tmp_path, monkeypatch):diff --git a/agent/tests/test_feishu_login_persistence.py b/agent/tests/test_feishu_login_persistence.pyindex fd0471b68..45a19762e 100644--- a/agent/tests/test_feishu_login_persistence.py+++ b/agent/tests/test_feishu_login_persistence.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import osimport statfrom src.channels.feishu import _persist_login_credentials@@ -38,4 +39,5 @@ def test_persist_login_credentials_preserves_config_and_writes_private_file(tmp_"app_secret": "test-secret","domain": "feishu",}- assert stat.S_IMODE(saved.stat().st_mode) == 0o600+ if os.name == "posix":+ assert stat.S_IMODE(saved.stat().st_mode) == 0o600diff --git a/agent/tests/test_local_connections.py b/agent/tests/test_local_connections.pyindex 901819be3..3a373ad58 100644--- a/agent/tests/test_local_connections.py+++ b/agent/tests/test_local_connections.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import osimport pytest@@ -37,7 +38,8 @@ def test_connection_registry_never_serializes_credentials(tmp_path):payload = (tmp_path / "connections.json").read_text(encoding="utf-8")assert "secret-value" not in payloadassert connection.credential_ref == "keyring://vibe-trading/main-binance"- assert (tmp_path / "connections.json").stat().st_mode & 0o777 == 0o600+ if os.name == "posix":+ assert (tmp_path / "connections.json").stat().st_mode & 0o777 == 0o600def test_connection_registry_normalizes_ids_before_duplicate_checks(tmp_path):diff --git a/agent/tests/test_lockup_expiry_integer_code.py b/agent/tests/test_lockup_expiry_integer_code.pyindex e45e1cfbd..642f282bf 100644--- a/agent/tests/test_lockup_expiry_integer_code.py+++ b/agent/tests/test_lockup_expiry_integer_code.py@@ -5,8 +5,27 @@ import pytestfrom src.tools.lockup_expiry_tool import LockupExpiryTool-def test_lockup_expiry_tool_integer_code_handling():+def test_lockup_expiry_tool_integer_code_handling(monkeypatch: pytest.MonkeyPatch):"""Verify LockupExpiryTool.execute handles integer stock codes without raising AttributeError on .strip()."""+ canned = {+ "result": {+ "data": [+ {+ "SECURITY_CODE": "600519",+ "SECURITY_NAME_ABBR": "MT",+ "FREE_DATE": "2026-01-02",+ "FREE_SHARES_TYPE": "1",+ "FREE_SHARES": "100",+ "ABLE_FREE_SHARES": "80",+ "LIFT_MARKET_CAP": "1000",+ }+ ]+ }+ }+ monkeypatch.setattr(+ "src.tools.lockup_expiry_tool.eastmoney_client.get_json",+ lambda *args, **kwargs: canned,+ )tool = LockupExpiryTool()res_str = tool.execute(code=600519)res = json.loads(res_str)diff --git a/agent/tests/test_mcp_alpha_zoo_contract.py b/agent/tests/test_mcp_alpha_zoo_contract.pyindex ad4c93f71..6d98027b9 100644--- a/agent/tests/test_mcp_alpha_zoo_contract.py+++ b/agent/tests/test_mcp_alpha_zoo_contract.py@@ -4,10 +4,13 @@ import asyncioimport datetime as dtimport inspectimport json+import osimport refrom pathlib import Pathimport mcp_server+import pytest+from src.tools.alpha_bench_tool import AlphaBenchToolfrom src.tools.alpha_zoo_tool import AlphaZooToolfrom src.tools import alpha_bench_tool as alpha_bench_module@@ -201,6 +204,9 @@ def test_alpha_bench_rejects_output_outside_allowed_roots(monkeypatch) -> None:assert registry.calls == []+ os.name == "nt", reason="symlink creation requires privileges unavailable on Windows"+)def test_alpha_bench_does_not_follow_preexisting_report_symlink(monkeypatch, tmp_path: Path) -> None:class _BenchRegistry:def get(self, alpha_id: str) -> object:diff --git a/agent/tests/test_mcp_client_adapter.py b/agent/tests/test_mcp_client_adapter.pyindex f4bba61a5..575abcd58 100644--- a/agent/tests/test_mcp_client_adapter.py+++ b/agent/tests/test_mcp_client_adapter.py@@ -468,7 +468,7 @@ def test_data_only_fallback_uses_pydantic_json_serialization() -> None:_StandardJsonAdapters(amount=Decimal("1234.5600"),order_id=UUID("12345678-1234-5678-1234-567812345678"),- output_path=Path("reports/daily.json"),+ output_path=Path("daily.json"),state=_OrderState.OPEN,labels={"beta", "alpha"},range_pair=(1, 5),@@ -480,7 +480,7 @@ def test_data_only_fallback_uses_pydantic_json_serialization() -> None:assert payload["data"] == {"amount": "1234.5600","order_id": "12345678-1234-5678-1234-567812345678",- "output_path": "reports/daily.json",+ "output_path": "daily.json","state": "open","range_pair": [1, 5],}diff --git a/agent/tests/test_memory_lifecycle.py b/agent/tests/test_memory_lifecycle.pyindex 22b1a7cf1..e7f604c48 100644--- a/agent/tests/test_memory_lifecycle.py+++ b/agent/tests/test_memory_lifecycle.py@@ -2,6 +2,7 @@from __future__ import annotations+import osfrom pathlib import Pathimport pytest@@ -341,6 +342,10 @@ class TestMemoryLock:with memory_lock(tmp_path) as acquired:assert acquired is True+ @pytest.mark.skipif(+ os.name == "nt",+ reason="POSIX flock; the win32 lock path yields without creating a .lock file",+ )def test_lock_file_created(self, tmp_path: Path) -> None:"""Lock file .lock should be created in memory dir."""with memory_lock(tmp_path):diff --git a/agent/tests/test_portfolio_config.py b/agent/tests/test_portfolio_config.pyindex d407d9d28..8776076f8 100644--- a/agent/tests/test_portfolio_config.py+++ b/agent/tests/test_portfolio_config.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import osimport pytest@@ -34,7 +35,8 @@ def test_portfolio_settings_round_trip_without_credentials(tmp_path):)assert store.load() == settings- assert (tmp_path / "portfolio.json").stat().st_mode & 0o777 == 0o600+ if os.name == "posix":+ assert (tmp_path / "portfolio.json").stat().st_mode & 0o777 == 0o600payload = json.loads((tmp_path / "portfolio.json").read_text(encoding="utf-8"))assert "api_key" not in json.dumps(payload)assert "profile_id" not in json.dumps(payload)diff --git a/agent/tests/test_qveris_tool.py b/agent/tests/test_qveris_tool.pyindex 2e429ea4d..ad6b5424e 100644--- a/agent/tests/test_qveris_tool.py+++ b/agent/tests/test_qveris_tool.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import osimport statimport threadingfrom concurrent.futures import ThreadPoolExecutor@@ -60,7 +61,8 @@ def test_config_read_write_masks_key_and_uses_0600(qveris_config_path: Path):assert saved.enabled is Trueassert qt.load_qveris_config().api_key == "sk-test-8TI"assert qt.mask_api_key("sk-test-8TI") == "sk-t…8TI"- assert stat.S_IMODE(qveris_config_path.stat().st_mode) == 0o600+ if os.name == "posix":+ assert stat.S_IMODE(qveris_config_path.stat().st_mode) == 0o600def test_env_overrides_file_config(monkeypatch: pytest.MonkeyPatch):diff --git a/agent/tests/test_telegram_split_fence_hang.py b/agent/tests/test_telegram_split_fence_hang.pyindex 721405135..4029179b9 100644--- a/agent/tests/test_telegram_split_fence_hang.py+++ b/agent/tests/test_telegram_split_fence_hang.py@@ -2,6 +2,10 @@from __future__ import annotations+import os++import pytest+import signalimport sysimport types@@ -64,6 +68,7 @@ def _alarm_handler(signum, frame) -> None: # noqa: ANN001raise _Hang()[email protected](os.name == "nt", reason="SIGALRM hang-guard is POSIX-only")def test_split_telegram_markdown_long_fence_body_no_hang() -> None:"""Long fenced line with no breaks must finish under the production limit."""body = "a" * 5000@@ -82,6 +87,7 @@ def test_split_telegram_markdown_long_fence_body_no_hang() -> None:assert body in joined_body or joined_body.count("a") >= len(body)[email protected](os.name == "nt", reason="SIGALRM hang-guard is POSIX-only")def test_split_telegram_markdown_closed_long_fence_no_hang() -> None:content = "```\n" + "x" * 5000 + "\n```"signal.signal(signal.SIGALRM, _alarm_handler)@@ -100,6 +106,7 @@ def test_split_telegram_markdown_nonpositive_max_len_returns_unsplit() -> None:assert _split_telegram_markdown(content, -1) == [content][email protected](os.name == "nt", reason="SIGALRM hang-guard is POSIX-only")def test_split_telegram_markdown_short_fence_mid_limit_no_hang() -> None:"""Fence at index 0 with mid-size max_len must not rebuild the same chunk."""content = '```\n om/yyyyyyyyyyyyyyyyyyyy)\n\na"'diff --git a/agent/tests/test_trace_writer.py b/agent/tests/test_trace_writer.pyindex e2bdc5a40..5643b98ec 100644--- a/agent/tests/test_trace_writer.py+++ b/agent/tests/test_trace_writer.py@@ -159,6 +159,9 @@ def test_write_calls_fsync_for_crash_safety(trace.close()+ os.name == "nt", reason="directory fsync is a POSIX-only durability primitive"+)def test_new_trace_file_fsyncs_parent_directory(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,diff --git a/agent/tests/test_user_state_paths.py b/agent/tests/test_user_state_paths.pyindex 973264a28..c899d42ae 100644--- a/agent/tests/test_user_state_paths.py+++ b/agent/tests/test_user_state_paths.py@@ -249,7 +249,7 @@ def test_welcome_panel_reports_runtime_root_as_workspace(console = Console(width=200, record=True)console.print(_legacy._build_welcome_panel(term_width=120))- assert "/RTROOT" in console.export_text()+ assert "RTROOT" in console.export_text()def test_state_dir_helpers_do_not_create_directories(