Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(autopilot,loaders): repair zero-review runtime defects in #260 + #252 (#266)

Haozhe Wue7a95106da7b
diff --git a/agent/backtest/loaders/local_loader.py b/agent/backtest/loaders/local_loader.py
index c63e5ce47..879b4de52 100644
--- a/agent/backtest/loaders/local_loader.py
+++ b/agent/backtest/loaders/local_loader.py
@@ -88,6 +88,11 @@ def _normalize_columns(
df["trade_date"] = pd.to_datetime(df[date_col], format=date_fmt, errors="coerce")
else:
df["trade_date"] = pd.to_datetime(df[date_col], errors="coerce")
+ # Drop any timezone so the tz-naive date-range filter in ``_fetch_one`` never
+ # raises "Invalid comparison between tz-aware and tz-naive" (which was caught
+ # and swallowed into a silently empty result for tz-aware parquet/CSV inputs).
+ if getattr(df["trade_date"].dt, "tz", None) is not None:
+ df["trade_date"] = df["trade_date"].dt.tz_localize(None)
df = df.dropna(subset=["trade_date"])
df = df.set_index("trade_date").sort_index()
diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.py
index 3e0a34289..94557ce01 100644
--- a/agent/src/tools/__init__.py
+++ b/agent/src/tools/__init__.py
@@ -119,6 +119,7 @@ def build_registry(
StartResearchGoalTool,
UpdateResearchGoalStatusTool,
)
+ from src.tools.autopilot_tool import RunResearchAutopilotTool
from src.tools.remember_tool import RememberTool
from src.tools.swarm_tool import SwarmTool
@@ -128,6 +129,9 @@ def build_registry(
AddGoalEvidenceTool,
UpdateResearchGoalStatusTool,
}
+ # Tools that need the host session id injected: they create or mutate the
+ # session's research goal, and the LLM never knows the session id.
+ session_injected_classes = goal_tool_classes | {RunResearchAutopilotTool}
registry = ToolRegistry()
for cls in _discover_subclasses():
try:
@@ -139,7 +143,7 @@ def build_registry(
continue
if cls is RememberTool and persistent_memory is not None:
registry.register(cls(memory=persistent_memory))
- elif cls in goal_tool_classes:
+ elif cls in session_injected_classes:
registry.register(cls(default_session_id=session_id, event_callback=event_callback))
elif cls is SwarmTool:
registry.register(cls(include_shell_tools=include_shell_tools, event_callback=event_callback))
diff --git a/agent/src/tools/autopilot_tool.py b/agent/src/tools/autopilot_tool.py
index 91e4a61f3..ad6b3c49e 100644
--- a/agent/src/tools/autopilot_tool.py
+++ b/agent/src/tools/autopilot_tool.py
@@ -54,8 +54,9 @@ class RunResearchAutopilotTool(BaseTool):
description = (
"Start a research goal from a saved hypothesis. "
"Reads the hypothesis, creates a goal with the thesis as objective "
- "and backtest-relevant criteria. Returns a goal snapshot you can "
- "continue from with backtest/evidence tools."
+ "and backtest-relevant criteria. NOTE: this replaces the session's "
+ "current research goal. Returns a goal snapshot you can continue "
+ "from with backtest/evidence tools."
)
is_readonly = False
repeatable = True
@@ -74,6 +75,23 @@ class RunResearchAutopilotTool(BaseTool):
"required": ["hypothesis_id"],
}
+ def __init__(
+ self,
+ *,
+ default_session_id: str | None = None,
+ event_callback: Any = None,
+ ) -> None:
+ """Initialize the autopilot tool.
+
+ Args:
+ default_session_id: Session id injected by the host runtime, so the
+ tool can create a goal without the LLM ever knowing the id.
+ event_callback: Optional host callback, accepted for registry
+ construction parity with the goal tools (currently unused).
+ """
+ self._default_session_id = default_session_id
+ self._event_callback = event_callback
+
def execute(self, **kwargs: Any) -> str:
try:
hypothesis_id = str(kwargs.get("hypothesis_id", "")).strip()
@@ -94,7 +112,9 @@ class RunResearchAutopilotTool(BaseTool):
ensure_ascii=False,
)
- session_id = str(kwargs.get("session_id", "")).strip()
+ session_id = str(
+ kwargs.get("session_id") or self._default_session_id or ""
+ ).strip()
if not session_id:
return json.dumps(
{
@@ -182,6 +202,34 @@ def _lookup_codes(universe: str) -> list[str]:
return _UNIVERSE_CODES.get(key, [universe])
+def _resolve_source(data_sources: list[str] | None) -> tuple[str, str | None]:
+ """Pick a valid loader source from the hypothesis, else fall back to ``auto``.
+
+ A hypothesis ``data_sources`` entry is free text, so an unrecognised value
+ would otherwise only fail deep inside the backtest runner with a confusing
+ message. Validate it up front and degrade to ``auto`` with a warning the
+ agent can surface.
+
+ Args:
+ data_sources: The hypothesis ``data_sources`` list (may be empty/None).
+
+ Returns:
+ A ``(source, warning)`` tuple; ``warning`` is ``None`` when the source
+ is valid or the source whitelist cannot be imported.
+ """
+ candidate = (data_sources or ["auto"])[0]
+ try:
+ from backtest.loaders.registry import VALID_SOURCES
+ except Exception: # pragma: no cover - registry import is environment-stable
+ return candidate, None
+ if candidate in VALID_SOURCES:
+ return candidate, None
+ return "auto", (
+ f"hypothesis data_source {candidate!r} is not a known loader source; "
+ "fell back to 'auto'"
+ )
+
+
def _validate_backtest_dates(start_date: str, end_date: str) -> None:
"""Validate backtest dates before writing any run artifacts."""
try:
@@ -279,7 +327,7 @@ class GenerateBacktestConfigTool(BaseTool):
_validate_backtest_dates(start_date, end_date)
codes = _lookup_codes(hypothesis.universe)
- source = (hypothesis.data_sources or ["auto"])[0]
+ source, source_warning = _resolve_source(hypothesis.data_sources)
config = {
"codes": codes,
@@ -297,25 +345,26 @@ class GenerateBacktestConfigTool(BaseTool):
with open(config_path, "w", encoding="utf-8") as f:
json.dump(config, f, indent=2, ensure_ascii=False)
- return _ok(
- {
- "run_dir": str(run_dir),
- "config": config,
- "config_path": str(config_path),
- "hypothesis": {
- "hypothesis_id": hypothesis.hypothesis_id,
- "title": hypothesis.title,
- "signal_definition": hypothesis.signal_definition,
- "universe": hypothesis.universe,
- "data_sources": hypothesis.data_sources,
- },
- "next_step": (
- "Config written. Next: use write_file to create "
- "code/signal_engine.py from the signal_definition above, "
- "then call backtest(run_dir=...)."
- ),
- }
- )
+ payload: dict[str, Any] = {
+ "run_dir": str(run_dir),
+ "config": config,
+ "config_path": str(config_path),
+ "hypothesis": {
+ "hypothesis_id": hypothesis.hypothesis_id,
+ "title": hypothesis.title,
+ "signal_definition": hypothesis.signal_definition,
+ "universe": hypothesis.universe,
+ "data_sources": hypothesis.data_sources,
+ },
+ "next_step": (
+ "Config written. Next: use write_file to create "
+ "code/signal_engine.py from the signal_definition above, "
+ "then call backtest(run_dir=...)."
+ ),
+ }
+ if source_warning:
+ payload["warning"] = source_warning
+ return _ok(payload)
except Exception as exc:
return _error(exc)
diff --git a/agent/src/tools/path_utils.py b/agent/src/tools/path_utils.py
index d13e69fe9..bf691e3ec 100644
--- a/agent/src/tools/path_utils.py
+++ b/agent/src/tools/path_utils.py
@@ -99,6 +99,7 @@ def _default_run_roots() -> list[Path]:
swarm_runs_root(),
cwd / "runs",
home / ".vibe-trading" / "shadow_runs",
+ home / ".vibe-trading" / "runs",
]
diff --git a/agent/tests/test_autopilot_tool.py b/agent/tests/test_autopilot_tool.py
index b39938748..f9ca5745e 100644
--- a/agent/tests/test_autopilot_tool.py
+++ b/agent/tests/test_autopilot_tool.py
@@ -8,7 +8,13 @@ from pathlib import Path
import pytest
from src.hypotheses import HypothesisRegistry
-from src.tools.autopilot_tool import GenerateBacktestConfigTool, _lookup_codes
+from src.tools import build_registry
+from src.tools.autopilot_tool import (
+ GenerateBacktestConfigTool,
+ RunResearchAutopilotTool,
+ _lookup_codes,
+)
+from src.tools.path_utils import safe_run_dir
def _seed_hypothesis(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *, universe: str):
@@ -73,3 +79,96 @@ def test_generate_backtest_config_rejects_invalid_date_before_write(
assert payload["status"] == "error"
assert "start_date" in payload["error"]
assert not (tmp_path / ".vibe-trading" / "runs").exists()
+
+
+def test_run_research_autopilot_uses_host_injected_session_id(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The tool must work through build_registry without the LLM passing a session_id.
+
+ Regression for the dead-on-arrival defect: the tool only read session_id from
+ kwargs, but the LLM never knows it, so every call errored. It must fall back to
+ the host-injected default the registry wires in (like the goal tools).
+ """
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ hypothesis = _seed_hypothesis(tmp_path, monkeypatch, universe="CSI 300")
+
+ registry = build_registry(session_id="sess_autopilot")
+ tool = registry.get("run_research_autopilot")
+ assert tool is not None
+
+ # No session_id in kwargs — it must come from the host-injected default.
+ payload = json.loads(tool.execute(hypothesis_id=hypothesis.hypothesis_id))
+
+ assert payload["status"] == "ok"
+ assert payload["hypothesis"]["hypothesis_id"] == hypothesis.hypothesis_id
+ assert len(payload["goal"]["criteria"]) == 4
+ assert hypothesis.thesis in json.dumps(payload, ensure_ascii=False)
+
+
+def test_run_research_autopilot_unknown_hypothesis_errors(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A missing hypothesis id returns a clean not-found error, not a crash."""
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ monkeypatch.setenv("VIBE_TRADING_HYPOTHESES_PATH", str(tmp_path / "hypotheses.json"))
+
+ tool = RunResearchAutopilotTool(default_session_id="sess_x")
+ payload = json.loads(tool.execute(hypothesis_id="hyp_missing"))
+
+ assert payload["status"] == "error"
+ assert "not found" in payload["error"].lower()
+
+
+def test_generate_backtest_config_run_dir_passes_safe_run_dir(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The returned run_dir must be accepted by safe_run_dir.
+
+ Regression for the high-severity defect: the tool wrote run_dir under
+ ~/.vibe-trading/runs, which safe_run_dir rejected, so the advertised
+ write_file -> backtest handoff could never execute.
+ """
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ hypothesis = _seed_hypothesis(tmp_path, monkeypatch, universe="CSI 300")
+
+ payload = json.loads(
+ GenerateBacktestConfigTool().execute(
+ hypothesis_id=hypothesis.hypothesis_id,
+ start_date="2026-01-01",
+ end_date="2026-01-31",
+ )
+ )
+
+ assert payload["status"] == "ok"
+ # The exact handoff the agent performs next; before the fix this raised
+ # "run_dir ... is outside allowed run roots".
+ resolved = safe_run_dir(payload["run_dir"])
+ assert resolved == Path(payload["run_dir"]).resolve()
+
+
+def test_generate_backtest_config_falls_back_on_unknown_source(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A free-text data_source that is not a real loader degrades to 'auto'."""
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ monkeypatch.setenv("VIBE_TRADING_HYPOTHESES_PATH", str(tmp_path / "hypotheses.json"))
+ hypothesis = HypothesisRegistry().create(
+ title="Free-text source",
+ thesis="Momentum should outperform.",
+ universe="CSI 300",
+ signal_definition="Rank by trailing returns.",
+ data_sources=["my personal notes"],
+ )
+
+ payload = json.loads(
+ GenerateBacktestConfigTool().execute(
+ hypothesis_id=hypothesis.hypothesis_id,
+ start_date="2026-01-01",
+ end_date="2026-01-31",
+ )
+ )
+
+ assert payload["status"] == "ok"
+ assert payload["config"]["source"] == "auto"
+ assert "warning" in payload
diff --git a/agent/tests/test_local_loader.py b/agent/tests/test_local_loader.py
index 61dc4cc86..e9c6b1fc8 100644
--- a/agent/tests/test_local_loader.py
+++ b/agent/tests/test_local_loader.py
@@ -93,3 +93,50 @@ def test_local_loader_fetches_duckdb_without_path(
assert set(frames) == {"MYINDEX"}
assert list(frames["MYINDEX"]["close"]) == [10.5, 12.5]
+
+
+def test_local_loader_handles_timezone_aware_timestamps(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """tz-aware timestamps must not crash the date filter into an empty result.
+
+ Regression: the date-range filter compared a tz-naive Timestamp against a
+ tz-aware index, which raised TypeError that was swallowed into empty data.
+ """
+ csv_path = tmp_path / "tz_aapl.csv"
+ csv_path.write_text(
+ "\n".join(
+ [
+ "Date,Open,High,Low,Close,Volume",
+ "2026-01-01T00:00:00+00:00,10,11,9,10.5,1000",
+ "2026-01-02T00:00:00+00:00,12,13,11,12.5,1500",
+ ]
+ ),
+ encoding="utf-8",
+ )
+ _configure(
+ monkeypatch,
+ tmp_path,
+ [
+ {
+ "symbol": "AAPL.US",
+ "type": "csv",
+ "path": str(csv_path),
+ "columns": {
+ "date": "Date",
+ "open": "Open",
+ "high": "High",
+ "low": "Low",
+ "close": "Close",
+ "volume": "Volume",
+ },
+ }
+ ],
+ )
+
+ frames = local_loader.DataLoader().fetch(
+ ["local:AAPL.US"], "2026-01-01", "2026-01-02"
+ )
+
+ assert set(frames) == {"AAPL.US"}
+ assert list(frames["AAPL.US"]["close"]) == [10.5, 12.5]