"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(backtest): warn about model training exposure
lorenzozaneec28209f4d160
diff --git a/README.md b/README.mdindex 30aafb62a..214bf26bb 100644--- a/README.md+++ b/README.md@@ -1203,6 +1203,14 @@ select execution bars in `config.json`:}```+Backtest run cards record the provider and model that wrote `config.json` and+`code/signal_engine.py`. Set `model_training_cutoff` in `config.json` to an+ISO date to record the model's cutoff; a window ending earlier is marked as+potentially exposed, and an unset cutoff is treated as unknown and exposed.+For strict factor benchmarks, pass `--training-cutoff YYYY-MM-DD` to+`vibe-trading alpha bench --strict` to place the out-of-sample segment strictly+after the cutoff.+`MS` executes the aligned target on the first observed trading bar of eachmonth. Weekly/quarterly pandas offset aliases (for example `W-FRI` and `QS`) andexplicit ISO date lists are also accepted. An alias must not be finer than thediff --git a/agent/backtest/run_card.py b/agent/backtest/run_card.pyindex 610ba52fb..c3fed1c4b 100644--- a/agent/backtest/run_card.py+++ b/agent/backtest/run_card.py@@ -8,7 +8,7 @@ import refrom decimal import Decimal, InvalidOperationimport jsonimport math-from datetime import datetime, timezone+from datetime import date, datetime, timezonefrom pathlib import Pathfrom typing import Any, Mapping, Sequence@@ -44,6 +44,127 @@ BACKTEST_SUMMARY_KEYS = ()+def _model_provenance(+ run_dir: Path, config: Mapping[str, Any]+) -> tuple[dict[str, Any], list[str]]:+ warnings: list[str] = []+ metadata_path = run_dir / "strategy_provenance.json"+ try:+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ metadata = {}+ except (OSError, json.JSONDecodeError):+ metadata = {}+ warnings.append(+ "Strategy model provenance could not be read; training exposure is assumed."+ )+ if not isinstance(metadata, Mapping):+ metadata = {}+ warnings.append(+ "Strategy model provenance is invalid; training exposure is assumed."+ )++ raw_files = metadata.get("files")+ if raw_files is None:+ raw_files = {}+ elif not isinstance(raw_files, Mapping):+ raw_files = {}+ warnings.append(+ "Strategy model provenance is invalid; training exposure is assumed."+ )+ files: dict[str, dict[str, str | None]] = {}+ for path in ("config.json", "code/signal_engine.py"):+ raw_model = raw_files.get(path)+ if raw_model is None:+ if (run_dir / path).is_file():+ files[path] = {"provider": None, "model_id": None, "model_source": None}+ warnings.append(+ f"No strategy model provenance was recorded for {path}; "+ "writer identity is unknown."+ )+ continue+ if not isinstance(raw_model, Mapping):+ files[path] = {"provider": None, "model_id": None, "model_source": None}+ warnings.append(+ f"Strategy model provenance for {path} is invalid; "+ "writer identity is unknown."+ )+ continue+ provider = raw_model.get("provider")+ model_id = raw_model.get("model_id")+ files[path] = {+ "provider": (+ provider.strip()+ if isinstance(provider, str) and provider.strip()+ else None+ ),+ "model_id": (+ model_id.strip()+ if isinstance(model_id, str) and model_id.strip()+ else None+ ),+ "model_source": (+ raw_model.get("model_source")+ if raw_model.get("model_source")+ in ("provider_response", "configured")+ else None+ ),+ }+ if files[path]["provider"] is None or files[path]["model_id"] is None:+ warnings.append(+ f"Strategy model provenance for {path} is incomplete; "+ "writer identity is unknown."+ )++ cutoff_value = config.get("model_training_cutoff")+ cutoff = str(cutoff_value).strip() if cutoff_value is not None else ""+ cutoff_date = None+ if cutoff:+ try:+ cutoff_date = date.fromisoformat(cutoff)+ except ValueError:+ warnings.append(+ "model_training_cutoff is invalid; training exposure is assumed."+ )+ cutoff = ""++ provenance = {+ "files": files,+ "training_cutoff": cutoff or None,+ "cutoff_source": "config" if cutoff else None,+ }+ model_labels = sorted(+ {+ "/".join(part for part in (model["provider"], model["model_id"]) if part)+ for model in files.values()+ if model["provider"] or model["model_id"]+ }+ )+ model_label = ", ".join(model_labels) or "unknown model"+ if cutoff_date is None:+ warnings.append(+ f"Training cutoff for {model_label} is unknown; "+ "assume results may reflect what the model remembers."+ )+ else:+ end_value = config.get("end_date")+ try:+ end_date = date.fromisoformat(str(end_value)[:10])+ except (TypeError, ValueError):+ warnings.append(+ f"Backtest end date is unavailable; exposure to "+ f"{model_label} training data cannot be assessed."+ )+ else:+ if end_date < cutoff_date:+ warnings.append(+ f"Backtest window ends on {end_date.isoformat()}, before the training cutoff "+ f"({cutoff_date.isoformat()}) for {model_label}; "+ "results may reflect what the model remembers."+ )+ return provenance, warnings++def write_run_card(run_dir: Path,config: Mapping[str, Any],@@ -85,6 +206,7 @@ def write_run_card(if strategy_file.exists() and strategy_file.is_file():reproducibility["strategy_hash"] = _file_hash(strategy_file)+ model_provenance, provenance_warnings = _model_provenance(run_dir, config)card: dict[str, Any] = {"schema_version": SCHEMA_VERSION,"generated_at": _utc_now(),@@ -93,7 +215,8 @@ def write_run_card("reproducibility": reproducibility,"data_sources": list(data_sources or []),"metrics": _scalar_metrics(metrics),- "warnings": list(warnings or []),+ "warnings": [*(warnings or []), *provenance_warnings],+ "model_provenance": model_provenance,"artifacts": _list_artifacts(run_dir),}normalized_refs = _normalize_artifact_refs(artifact_refs)@@ -404,6 +527,22 @@ def _render_markdown(card: Mapping[str, Any]) -> str:if "strategy_hash" in reproducibility:lines.append(f"- strategy_hash: `{reproducibility['strategy_hash']}`")+ model = card.get("model_provenance", {})+ lines.extend(["", "## Model provenance"])+ model_files = model.get("files", {})+ if model_files:+ for path, source in model_files.items():+ label = "/".join(+ part for part in (source.get("provider"), source.get("model_id")) if part+ ) or "Unknown"+ source = source.get("model_source")+ if source:+ label += f" ({source})"+ lines.append(f"- {path}: {label}")+ else:+ lines.append("- No strategy writer recorded.")+ lines.append(f"- Training cutoff: {model.get('training_cutoff') or 'Unknown'}")+lines.extend(["", "## Data Sources"])data_sources = card.get("data_sources", [])lines.extend(f"- {source}" for source in data_sources) if data_sources else lines.append("- None recorded.")diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 2030b84bc..88a7b5414 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -1120,6 +1120,8 @@ class AgentLoop:),)self._llm_runtime = runtime_snapshot+ self._active_model_id = runtime_snapshot.configured_model+ self._active_model_source = "configured"self.memory = memory or WorkspaceMemory()self._event_callback = event_callbackself.max_iterations = max_iterations@@ -1624,8 +1626,9 @@ class AgentLoop:self._last_activity_wall = _time.time()usage = getattr(response, "usage_metadata", None)- if getattr(response, "response_model", None):- last_response_model = response.response_model+ current_response_model = getattr(response, "response_model", None)+ if current_response_model:+ last_response_model = current_response_modelusage_delta = _record_llm_usage(run_dir,llm_usage_summary,@@ -2087,6 +2090,12 @@ class AgentLoop:messages.append(assistant_message)# Execute tools with read/write batching+ self._active_model_id = (+ current_response_model or self._llm_runtime.configured_model+ )+ self._active_model_source = (+ "provider_response" if current_response_model else "configured"+ )compact_requested, focus_topic = self._process_tool_calls(response.tool_calls, context, messages, trace, react_trace, current_iter,)@@ -2988,10 +2997,54 @@ class AgentLoop:if not p.is_absolute() and self.memory.run_dir:p = Path(self.memory.run_dir) / ptry:- self._written_files.add(str(p.resolve()).casefold())+ resolved = p.resolve()+ self._written_files.add(str(resolved).casefold())except (OSError, ValueError):+ resolved = pself._written_files.add(str(p).casefold())+ if not self.memory.run_dir:+ return+ run_root = Path(self.memory.run_dir).resolve()+ try:+ relative = resolved.relative_to(run_root).as_posix()+ except ValueError:+ return+ if relative not in {"config.json", "code/signal_engine.py"}:+ return++ metadata_path = run_root / "strategy_provenance.json"+ try:+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ files = {}+ except (OSError, json.JSONDecodeError) as exc:+ logger.warning(+ "Could not read strategy model provenance; update skipped: %s",+ exc,+ )+ return+ else:+ if not isinstance(metadata, dict):+ logger.warning("Invalid strategy model provenance; update skipped.")+ return+ files = metadata.get("files", {})+ if not isinstance(files, dict):+ logger.warning("Invalid strategy model provenance files; update skipped.")+ return+ files[relative] = {+ "provider": self._llm_runtime.provider or None,+ "model_id": self._active_model_id or None,+ "model_source": self._active_model_source,+ }+ try:+ metadata_path.write_text(+ json.dumps({"files": files}, ensure_ascii=False, sort_keys=True) + "\n",+ encoding="utf-8",+ )+ except OSError as exc:+ logger.warning("Could not write strategy model provenance: %s", exc)+def _pending_write_directive(self, user_message: str, run_started_wall: float) -> str:diff --git a/agent/src/factors/bench_runner_strict.py b/agent/src/factors/bench_runner_strict.pyindex 23fac82c5..d26fb1da9 100644--- a/agent/src/factors/bench_runner_strict.py+++ b/agent/src/factors/bench_runner_strict.py@@ -322,6 +322,7 @@ def run_bench_strict(random_control: bool,n_random_seeds: int = 5,oos_split: str | None = None,+ training_cutoff: str | None = None,thresholds: StrictThresholds | None = None,top: int = 20,on_progress: ProgressCb | None = None,@@ -343,8 +344,9 @@ def run_bench_strict(values shrink the random IC variance and tighten the alphat-stat; default 5 is enough for a 455-alpha zoo without makingthe bench more than ~6x slower.- oos_split: Date string (``YYYY-MM-DD``) splitting train and test.- ``None`` disables the OOS gate (full sample only).+ oos_split: Date string splitting train and test.+ ``None`` disables the OOS gate unless ``training_cutoff`` is set.+ training_cutoff: Model training cutoff; test observations must be later.thresholds: ``StrictThresholds`` instance. Defaults to``alpha_t_threshold=2.0`` (back-compat). Pass ``3.5`` to applyHarvey-Liu-Zhu (2016) multiple-testing correction when bench@@ -387,6 +389,7 @@ def run_bench_strict(# Initialise the full schema up-front so even early-error returns# carry zeroed counters and empty lists — downstream consumers can# depend on the keys always being present.+ effective_oos_split = training_cutoff if training_cutoff is not None else oos_splitentry: dict[str, Any] = {"status": "pending","zoo": zoo,@@ -394,7 +397,8 @@ def run_bench_strict("period": period,"random_control": random_control,"n_random_seeds": effective_seeds,- "oos_split": oos_split,+ "oos_split": effective_oos_split,+ "training_cutoff": training_cutoff,"alpha_t_threshold": thresholds.alpha_t_threshold,"n_alphas_tested": 0,"n_skipped": 0,@@ -423,6 +427,9 @@ def run_bench_strict(entry["wall_seconds"] = round(time.monotonic() - start, 2)return entry+ if training_cutoff is not None and oos_split is not None:+ return _finish_error("pass either training_cutoff or oos_split, not both")+reg = registry if registry is not None else get_default_registry()alpha_ids = reg.list(zoo=zoo)if not alpha_ids:@@ -443,18 +450,19 @@ def run_bench_strict(n_total = len(alpha_ids)oos_ts: pd.Timestamp | None = None- if oos_split is not None:+ if effective_oos_split is not None:try:- oos_ts = pd.Timestamp(oos_split)+ oos_ts = pd.Timestamp(effective_oos_split)except (TypeError, ValueError) as exc:- return _finish_error(f"invalid oos_split {oos_split!r}: {exc}")+ return _finish_error(f"invalid OOS boundary {effective_oos_split!r}: {exc}")close = panel.get("close")if close is not None and len(close.index):first = pd.Timestamp(close.index.min())last = pd.Timestamp(close.index.max())if not first <= oos_ts < last:return _finish_error(- f"oos_split {oos_split!r} must fall within the loaded sample "+ f"OOS boundary {effective_oos_split!r} must fall within the "+ "loaded sample "f"[{first.date()}, {last.date()})")@@ -512,7 +520,7 @@ def run_bench_strict(# horizon before the last price.if min(ic_count_train, ic_count_test) < 2:raise SkipAlpha(- f"oos_split {oos_split} leaves {ic_count_train} train / "+ f"OOS boundary {effective_oos_split} leaves {ic_count_train} train / "f"{ic_count_test} test IC observations; each side needs 2")@@ -622,6 +630,13 @@ def run_bench_strict(by_theme = _theme_breakdown_strict(rows)+ if effective_oos_split is not None and not rows:+ entry["n_skipped"] = len(skipped)+ entry["skipped"] = skipped+ return _finish_error(+ "OOS benchmark produced no valid alpha rows; inspect skipped reasons"+ )+entry.update({"status": "ok",diff --git a/agent/src/factors/cli_handlers.py b/agent/src/factors/cli_handlers.pyindex 1fd188451..d5fd19c53 100644--- a/agent/src/factors/cli_handlers.py+++ b/agent/src/factors/cli_handlers.py@@ -547,8 +547,15 @@ def cmd_alpha_bench(args: argparse.Namespace) -> int:from ``src.tools.alpha_bench_tool`` (we do NOT modify that module)."""try:- if (getattr(args, "oos_split", None) or getattr(args, "random_seeds", 5) != 5) and not getattr(args, "strict", False):- _err("alpha bench: --oos-split/--random-seeds only take effect with --strict.")+ if (+ getattr(args, "oos_split", None)+ or getattr(args, "training_cutoff", None)+ or getattr(args, "random_seeds", 5) != 5+ ) and not getattr(args, "strict", False):+ _err(+ "alpha bench: --oos-split/--training-cutoff/--random-seeds "+ "only take effect with --strict."+ )return 1try:if getattr(args, "strict", False):@@ -559,6 +566,7 @@ def cmd_alpha_bench(args: argparse.Namespace) -> int:random_control=True,n_random_seeds=max(1, int(getattr(args, "random_seeds", 5) or 5)),oos_split=getattr(args, "oos_split", None),+ training_cutoff=getattr(args, "training_cutoff", None),)else:from src.factors.bench_runner import run_bench@@ -602,7 +610,13 @@ def cmd_alpha_bench(args: argparse.Namespace) -> int:strict_banner = (" [strict: random control"- + (f", oos {args.oos_split}" if getattr(args, "oos_split", None) else "")+ + (+ f", OOS after {args.training_cutoff}"+ if getattr(args, "training_cutoff", None)+ else f", oos {args.oos_split}"+ if getattr(args, "oos_split", None)+ else ""+ )+ "]"if getattr(args, "strict", False)else ""@@ -757,6 +771,8 @@ def cmd_alpha_bench(args: argparse.Namespace) -> int:envelope[key] = result[key]if result.get("oos_split") is not None:envelope["oos_split"] = result["oos_split"]+ if result.get("training_cutoff") is not None:+ envelope["training_cutoff"] = result["training_cutoff"]if universe_meta:envelope["meta"] = universe_metaif report_path is not None:@@ -1014,6 +1030,15 @@ def add_subparser(subparsers: Any) -> argparse.ArgumentParser:metavar="YYYY-MM-DD",help="Strict mode only: split train/test at this date for the OOS confirmation gate",)+ p_bench.add_argument(+ "--training-cutoff",+ default=None,+ metavar="YYYY-MM-DD",+ help=(+ "Strict mode only: use this model training cutoff as the "+ "train/test boundary"+ ),+ )p_bench.add_argument("--random-seeds",type=int,diff --git a/agent/tests/factors/test_bench_strict.py b/agent/tests/factors/test_bench_strict.pyindex 825a36df6..57fed45e1 100644--- a/agent/tests/factors/test_bench_strict.py+++ b/agent/tests/factors/test_bench_strict.py@@ -295,6 +295,63 @@ def test_run_bench_strict_respects_oos_split(assert row["alpha_t_test"] is not None+def test_run_bench_strict_places_oos_after_training_cutoff(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _stub_panel(monkeypatch, n_rows=120)+ result = run_bench_strict(+ zoo="alpha101",+ universe="csi300",+ period="2024-2024",+ random_control=True,+ n_random_seeds=2,+ training_cutoff="2024-03-01",+ registry=_StubRegistry(panel={}),+ )++ assert result["status"] == "ok"+ assert result["training_cutoff"] == "2024-03-01"+ assert result["oos_split"] == "2024-03-01"+ assert all(row["ic_count_test"] >= 2 for row in result["rows"])+++[email protected]("boundary", ["training_cutoff", "oos_split"])+def test_oos_boundary_with_no_usable_alpha_rows_returns_error(+ monkeypatch: pytest.MonkeyPatch,+ boundary: str,+) -> None:+ _stub_panel(monkeypatch, n_rows=80)+ result = run_bench_strict(+ zoo="alpha101",+ universe="csi300",+ period="2024-2024",+ random_control=False,+ registry=_StubRegistry(panel={}),+ **{boundary: "2024-03-19"},+ )++ assert result["status"] == "error"+ assert result["n_alphas_tested"] == 0+ assert result["n_skipped"] > 0+ assert "no valid alpha rows" in result["error"]+++def test_run_bench_strict_rejects_two_oos_boundaries() -> None:+ result = run_bench_strict(+ zoo="alpha101",+ universe="csi300",+ period="2024-2024",+ random_control=True,+ oos_split="2024-03-01",+ training_cutoff="2024-04-01",+ registry=_StubRegistry(panel={}),+ )++ assert result["status"] == "error"+ assert "either training_cutoff or oos_split" in result["error"]++def test_run_bench_strict_random_control_is_keyword_only() -> None:# Positional call should fail with TypeError because random_control is# keyword-only by construction. This locks the rail at the signaturediff --git a/agent/tests/test_agent_loop_strategy_provenance.py b/agent/tests/test_agent_loop_strategy_provenance.pynew file mode 100644index 000000000..69d9f9fa9--- /dev/null+++ b/agent/tests/test_agent_loop_strategy_provenance.py@@ -0,0 +1,47 @@+import json+from pathlib import Path+from types import SimpleNamespace++from src.agent.loop import AgentLoop+from src.agent.memory import WorkspaceMemory+++def test_successful_strategy_file_write_records_the_active_model(+ tmp_path: Path,+) -> None:+ loop = object.__new__(AgentLoop)+ loop.memory = WorkspaceMemory(run_dir=str(tmp_path))+ loop._written_files = set()+ loop._active_model_id = "gpt-5.6-luna"+ loop._active_model_source = "configured"+ loop._llm_runtime = SimpleNamespace(+ provider="openai",+ configured_model="gpt-5.6-luna",+ )++ loop._record_written_target({"path": "config.json"})+ loop._llm_runtime = SimpleNamespace(+ provider="openrouter",+ configured_model="anthropic/claude-sonnet",+ )+ loop._active_model_id = "claude-sonnet-4-5"+ loop._active_model_source = "provider_response"+ loop._record_written_target({"path": "code/signal_engine.py"})++ provenance = json.loads(+ (tmp_path / "strategy_provenance.json").read_text(encoding="utf-8")+ )+ assert provenance == {+ "files": {+ "config.json": {+ "provider": "openai",+ "model_id": "gpt-5.6-luna",+ "model_source": "configured",+ },+ "code/signal_engine.py": {+ "provider": "openrouter",+ "model_id": "claude-sonnet-4-5",+ "model_source": "provider_response",+ },+ }+ }diff --git a/agent/tests/test_alpha_bench_strict_cli.py b/agent/tests/test_alpha_bench_strict_cli.pyindex 050dfb5af..173220ded 100644--- a/agent/tests/test_alpha_bench_strict_cli.py+++ b/agent/tests/test_alpha_bench_strict_cli.py@@ -19,6 +19,7 @@ def _ns(**overrides):yes=True,strict=False,oos_split=None,+ training_cutoff=None,random_seeds=5,)base.update(overrides)@@ -121,7 +122,10 @@ def _run(capsys, args, monkeypatch):def fake_strict(zoo, universe, period, **kwargs):called.update(kwargs)- return _strict_result()+ result = _strict_result()+ result["training_cutoff"] = kwargs.get("training_cutoff")+ result["oos_split"] = kwargs.get("training_cutoff") or kwargs.get("oos_split")+ return resultmonkeypatch.setattr(strict_mod, "run_bench_strict", fake_strict)rc = cli_handlers.cmd_alpha_bench(args)@@ -129,19 +133,36 @@ def _run(capsys, args, monkeypatch):def test_strict_routes_to_strict_runner(capsys, monkeypatch, _reg, _no_report):- rc, called, cap = _run(capsys, _ns(strict=True, oos_split="2023-01-01", random_seeds=3), monkeypatch)+ rc, called, cap = _run(+ capsys,+ _ns(strict=True, training_cutoff="2023-01-01", random_seeds=3),+ monkeypatch,+ )assert rc == 0assert called["random_control"] is True- assert called["oos_split"] == "2023-01-01"+ assert called["oos_split"] is None+ assert called["training_cutoff"] == "2023-01-01"assert called["n_random_seeds"] == 3envelope = _envelope(cap.out)assert envelope["strict"] is Trueassert envelope["confirmed_alive"] == 2assert envelope["noise"] == 5- assert envelope["oos_split"] == "2023-01-01"+ assert envelope["training_cutoff"] == "2023-01-01"assert envelope["top"][0]["category"] == "confirmed_alive"+def test_strict_routes_existing_oos_split(capsys, monkeypatch, _reg, _no_report):+ rc, called, cap = _run(+ capsys,+ _ns(strict=True, oos_split="2023-01-01"),+ monkeypatch,+ )+ assert rc == 0+ assert called["oos_split"] == "2023-01-01"+ assert called["training_cutoff"] is None+ assert _envelope(cap.out)["oos_split"] == "2023-01-01"++def test_default_routes_to_legacy_runner(capsys, monkeypatch, _reg, _no_report):import src.factors.bench_runner as legacy_mod@@ -160,10 +181,14 @@ def test_default_routes_to_legacy_runner(capsys, monkeypatch, _reg, _no_report):assert envelope["top"][0]["category"] == "alive"-def test_oos_split_without_strict_is_rejected(capsys, monkeypatch, _reg):- rc = cli_handlers.cmd_alpha_bench(_ns(oos_split="2023-01-01"))- assert rc == 1- assert "--strict" in capsys.readouterr().err+def test_strict_only_options_without_strict_are_rejected(capsys, monkeypatch, _reg):+ for option in (+ {"oos_split": "2023-01-01"},+ {"training_cutoff": "2023-01-01"},+ ):+ rc = cli_handlers.cmd_alpha_bench(_ns(**option))+ assert rc == 1+ assert "--strict" in capsys.readouterr().errdef test_strict_argparse_flags():@@ -171,14 +196,18 @@ def test_strict_argparse_flags():sub = parser.add_subparsers()alpha_parser = cli_handlers.add_subparser(sub)args = parser.parse_args(- ["alpha", "bench", "--zoo", "alpha101", "--strict", "--oos-split", "2023-01-01", "--random-seeds", "3"]+ [+ "alpha", "bench", "--zoo", "alpha101", "--strict",+ "--training-cutoff", "2023-01-01", "--random-seeds", "3",+ ])assert args.strict is True- assert args.oos_split == "2023-01-01"+ assert args.training_cutoff == "2023-01-01"assert args.random_seeds == 3args_default = parser.parse_args(["alpha", "bench", "--zoo", "alpha101"])assert args_default.strict is Falseassert args_default.oos_split is None+ assert args_default.training_cutoff is Noneassert args_default.random_seeds == 5assert alpha_parser is not Nonediff --git a/agent/tests/test_run_card_training_cutoff.py b/agent/tests/test_run_card_training_cutoff.pynew file mode 100644index 000000000..337b3bb57--- /dev/null+++ b/agent/tests/test_run_card_training_cutoff.py@@ -0,0 +1,193 @@+import json+from pathlib import Path++from backtest.run_card import write_run_card+++def test_run_card_records_model_and_warns_when_window_precedes_cutoff(+ tmp_path: Path,+) -> None:+ run_dir = tmp_path / "run"+ run_dir.mkdir()+ (run_dir / "strategy_provenance.json").write_text(+ json.dumps(+ {+ "files": {+ "config.json": {+ "provider": "openai",+ "model_id": "gpt-5.6-luna",+ "model_source": "configured",+ },+ "code/signal_engine.py": {+ "provider": "openrouter",+ "model_id": "claude-sonnet-4-5",+ "model_source": "provider_response",+ },+ }+ }+ ),+ encoding="utf-8",+ )++ card = write_run_card(+ run_dir,+ {+ "start_date": "2024-01-01",+ "end_date": "2024-12-31",+ "model_training_cutoff": "2025-01-01",+ },+ {},+ )++ assert card["model_provenance"]["files"] == {+ "config.json": {+ "provider": "openai",+ "model_id": "gpt-5.6-luna",+ "model_source": "configured",+ },+ "code/signal_engine.py": {+ "provider": "openrouter",+ "model_id": "claude-sonnet-4-5",+ "model_source": "provider_response",+ },+ }+ assert card["model_provenance"]["training_cutoff"] == "2025-01-01"+ assert card["model_provenance"]["cutoff_source"] == "config"+ assert any(+ "results may reflect what the model remembers" in w for w in card["warnings"]+ )+ markdown = (run_dir / "run_card.md").read_text(encoding="utf-8")+ assert "config.json: openai/gpt-5.6-luna (configured)" in markdown+ assert (+ "code/signal_engine.py: openrouter/claude-sonnet-4-5 (provider_response)"+ in markdown+ )+++def test_run_card_treats_unknown_cutoff_as_exposed(tmp_path: Path) -> None:+ run_dir = tmp_path / "run"+ run_dir.mkdir()+ (run_dir / "strategy_provenance.json").write_text(+ json.dumps(+ {+ "files": {+ "config.json": {+ "provider": "openrouter",+ "model_id": "custom/model",+ }+ }+ }+ ),+ encoding="utf-8",+ )++ card = write_run_card(+ run_dir,+ {"start_date": "2025-01-01", "end_date": "2025-12-31"},+ {},+ )++ assert card["model_provenance"]["training_cutoff"] is None+ assert (+ card["model_provenance"]["files"]["config.json"]["model_id"] == "custom/model"+ )+ assert any(+ "cutoff" in w.lower() and "unknown" in w.lower() for w in card["warnings"]+ )+++def test_run_card_warns_when_existing_strategy_has_incomplete_provenance(+ tmp_path: Path,+) -> None:+ run_dir = tmp_path / "run"+ signal_path = run_dir / "code" / "signal_engine.py"+ signal_path.parent.mkdir(parents=True)+ signal_path.write_text("class SignalEngine: pass\n", encoding="utf-8")+ (run_dir / "strategy_provenance.json").write_text(+ json.dumps(+ {+ "files": {+ "code/signal_engine.py": {"provider": "openai"},+ }+ }+ ),+ encoding="utf-8",+ )++ card = write_run_card(+ run_dir,+ {+ "start_date": "2025-01-01",+ "end_date": "2025-01-02",+ "model_training_cutoff": "2025-01-01",+ },+ {},+ )++ source = card["model_provenance"]["files"]["code/signal_engine.py"]+ assert source["provider"] == "openai"+ assert source["model_id"] is None+ assert any(+ "provenance" in warning.lower() and "incomplete" in warning.lower()+ for warning in card["warnings"]+ )+++def test_run_card_warns_when_strategy_files_have_no_provenance(+ tmp_path: Path,+) -> None:+ run_dir = tmp_path / "run"+ (run_dir / "code").mkdir(parents=True)+ (run_dir / "config.json").write_text("{}\n", encoding="utf-8")+ (run_dir / "code" / "signal_engine.py").write_text(+ "class SignalEngine: pass\n",+ encoding="utf-8",+ )++ card = write_run_card(+ run_dir,+ {+ "start_date": "2025-01-01",+ "end_date": "2025-01-02",+ "model_training_cutoff": "2025-01-01",+ },+ {},+ )++ for path in ("config.json", "code/signal_engine.py"):+ assert card["model_provenance"]["files"][path]["model_id"] is None+ assert any(+ path in warning and "provenance" in warning.lower()+ for warning in card["warnings"]+ )+++def test_run_card_does_not_warn_when_window_reaches_cutoff(tmp_path: Path) -> None:+ run_dir = tmp_path / "run"+ run_dir.mkdir()+ (run_dir / "strategy_provenance.json").write_text(+ json.dumps(+ {+ "files": {+ "config.json": {"provider": "openai", "model_id": "gpt-5.6-luna"},+ "code/signal_engine.py": {+ "provider": "openai",+ "model_id": "gpt-5.6-luna",+ },+ }+ }+ ),+ encoding="utf-8",+ )++ card = write_run_card(+ run_dir,+ {+ "start_date": "2025-01-01",+ "end_date": "2025-01-01",+ "model_training_cutoff": "2025-01-01",+ },+ {},+ )++ assert not any("training cutoff" in w.lower() for w in card["warnings"])