Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(agent): add evidence population, decay monitoring and stale refusal to strategy discovery

shadowinlifeae68820a7118
diff --git a/README.md b/README.md
index a51455a64..d8e0ca821 100644
--- a/README.md
+++ b/README.md
@@ -1227,7 +1227,7 @@ Posting `{}` schedules a template on its own suggested cadence with its declared
## 🔌 MCP Plugin
-Vibe-Trading exposes 73 MCP tools for any MCP-compatible client. Runs as a stdio subprocess — no server setup needed. Core research tools work with zero API keys for HK/US/crypto; trading connector tools use the selected connector profile, and `run_swarm` needs an LLM key.
+Vibe-Trading exposes 74 MCP tools for any MCP-compatible client. Runs as a stdio subprocess — no server setup needed. Core research tools work with zero API keys for HK/US/crypto; trading connector tools use the selected connector profile, and `run_swarm` needs an LLM key.
**Environment variables:** the client spawns the server itself, so a shell `export` never reaches it — set them in the client's `env` block. Generated backtest code is sandboxed to the allowed run roots, so writing results into a workspace of your own needs `VIBE_TRADING_ALLOWED_RUN_ROOTS`:
@@ -1296,7 +1296,7 @@ with `--host` / `--port`.
</details>
-**MCP tools exposed (73):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.
+**MCP tools exposed (74):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.
### SWARM external MCP tools
@@ -1670,7 +1670,7 @@ Vibe-Trading/
├── agent/ # Backend (Python)
│ ├── cli/ # CLI package — interactive TUI + subcommands
│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE
-│ ├── mcp_server.py # MCP server — 73 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 74 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
diff --git a/README_ar.md b/README_ar.md
index 42dd86676..1d08c9620 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -1145,7 +1145,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \
## 🔌 MCP Plugin
-يعرض Vibe-Trading 73 أداة MCP لأي عميل متوافق مع MCP. يعمل كعملية stdio فرعية، دون إعداد خادم. أدوات البحث الأساسية تعمل دون أي مفاتيح API لأسواق HK/US/crypto؛ وأدوات connector للتداول تستخدم profile الموصل المختار، ويحتاج `run_swarm` وحده إلى مفتاح LLM.
+يعرض Vibe-Trading 74 أداة MCP لأي عميل متوافق مع MCP. يعمل كعملية stdio فرعية، دون إعداد خادم. أدوات البحث الأساسية تعمل دون أي مفاتيح API لأسواق HK/US/crypto؛ وأدوات connector للتداول تستخدم profile الموصل المختار، ويحتاج `run_swarm` وحده إلى مفتاح LLM.
**متغيرات البيئة:** العميل هو من يشغّل الخادم بنفسه، لذا لا يصل إليه `export` من الـ shell أبداً —— اضبطها في كتلة `env` الخاصة بالعميل. كود الاختبار الخلفي المولَّد محصور ضمن جذور التشغيل المسموح بها، لذا تحتاج إلى `VIBE_TRADING_ALLOWED_RUN_ROOTS` لكتابة النتائج في دليل عمل خاص بك:
@@ -1201,7 +1201,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)
</details>
-**أدوات MCP المعروضة (73):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.
+**أدوات MCP المعروضة (74):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.
### أدوات MCP الخارجية في SWARM
@@ -1561,7 +1561,7 @@ Vibe-Trading/
├── agent/ # Backend (Python)
│ ├── cli/ # CLI package — interactive TUI + subcommands
│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE
-│ ├── mcp_server.py # MCP server — 73 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 74 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
diff --git a/README_ja.md b/README_ja.md
index a7a25f364..81d68529d 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -1147,7 +1147,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \
## 🔌 MCP Plugin
-Vibe-Trading は MCP-compatible client 向けに 73 MCP tools を公開します。stdio subprocess として動作し、server setup は不要です。Core research tools は HK/US/crypto で API key なしに動作し、trading connector tools は選択中の connector profile を使います。LLM key が必要なのは `run_swarm` のみです。
+Vibe-Trading は MCP-compatible client 向けに 74 MCP tools を公開します。stdio subprocess として動作し、server setup は不要です。Core research tools は HK/US/crypto で API key なしに動作し、trading connector tools は選択中の connector profile を使います。LLM key が必要なのは `run_swarm` のみです。
**環境変数:** server は client 自身が spawn するため、shell の `export` は届きません —— client の `env` block に設定してください。生成された backtest code は allowed run roots 内に制限されるので、結果を自分の作業 directory に書き出すには `VIBE_TRADING_ALLOWED_RUN_ROOTS` が必要です:
@@ -1203,7 +1203,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)
</details>
-**公開される MCP tools(73):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.
+**公開される MCP tools(74):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.
### SWARM の外部 MCP tools
@@ -1569,7 +1569,7 @@ Vibe-Trading/
├── agent/ # バックエンド (Python)
│ ├── cli/ # CLI パッケージ — インタラクティブ TUI + サブコマンド
│ ├── api_server.py # FastAPI サーバー — runs、sessions、upload、swarm、SSE
-│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 73 tools
+│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 74 tools
│ │
│ ├── src/
│ │ ├── agent/ # ReAct エージェントコア
diff --git a/README_ko.md b/README_ko.md
index b064def3c..c29a46652 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -1148,7 +1148,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \
## 🔌 MCP Plugin
-Vibe-Trading은 모든 MCP-compatible client를 위해 73개 MCP tools를 제공합니다. stdio subprocess로 실행되므로 server setup이 필요 없습니다. 핵심 research tools는 HK/US/crypto에서 API key 없이 작동하고, trading connector tools는 선택된 connector profile을 사용하며, `run_swarm`만 LLM key가 필요합니다.
+Vibe-Trading은 모든 MCP-compatible client를 위해 74개 MCP tools를 제공합니다. stdio subprocess로 실행되므로 server setup이 필요 없습니다. 핵심 research tools는 HK/US/crypto에서 API key 없이 작동하고, trading connector tools는 선택된 connector profile을 사용하며, `run_swarm`만 LLM key가 필요합니다.
**환경 변수:** server는 client가 직접 spawn하므로 shell의 `export`는 전달되지 않습니다 —— client의 `env` block에 설정하세요. 생성된 backtest code는 allowed run roots 안으로 제한되므로, 결과를 자신의 작업 directory에 쓰려면 `VIBE_TRADING_ALLOWED_RUN_ROOTS`가 필요합니다:
@@ -1204,7 +1204,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)
</details>
-**노출되는 MCP tools(73):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.
+**노출되는 MCP tools(74):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.
### SWARM 외부 MCP tools
@@ -1566,7 +1566,7 @@ Vibe-Trading/
├── agent/ # Backend (Python)
│ ├── cli/ # CLI package — interactive TUI + subcommands
│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE
-│ ├── mcp_server.py # MCP server — 73 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 74 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
diff --git a/README_zh.md b/README_zh.md
index bb02d1364..4928a9d2c 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -1136,7 +1136,7 @@ POST `{}` 即按模板自身的建议节奏和默认变量排程。渲染后的
## 🔌 MCP Plugin
-Vibe-Trading 为任何 MCP-compatible client 暴露 73 个 MCP tools。它作为 stdio subprocess 运行,无需 server setup。核心 research tools 对港股/美股/加密零 API key 可用;trading connector tools 使用当前选择的 connector profile;只有 `run_swarm` 需要 LLM key。
+Vibe-Trading 为任何 MCP-compatible client 暴露 74 个 MCP tools。它作为 stdio subprocess 运行,无需 server setup。核心 research tools 对港股/美股/加密零 API key 可用;trading connector tools 使用当前选择的 connector profile;只有 `run_swarm` 需要 LLM key。
**环境变量:** server 由 client 自己 spawn,因此在 shell 里 `export` 永远传不进去 —— 请写在 client 的 `env` 块里。生成的回测代码被限制在 allowed run roots 内,所以要把结果写进你自己的工作目录,需要 `VIBE_TRADING_ALLOWED_RUN_ROOTS`:
@@ -1192,7 +1192,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)
</details>
-**暴露的 MCP tools(73):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.
+**暴露的 MCP tools(74):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`.
### SWARM 的外部 MCP tools
@@ -1548,7 +1548,7 @@ Vibe-Trading/
├── agent/ # 后端(Python)
│ ├── cli/ # CLI 包 —— 交互式 TUI + 子命令
│ ├── api_server.py # FastAPI server —— runs、sessions、upload、swarm、SSE
-│ ├── mcp_server.py # MCP server —— 73 个工具,面向 OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server —— 74 个工具,面向 OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent 内核
diff --git a/agent/SKILL.md b/agent/SKILL.md
index d90707083..0e4764c95 100644
--- a/agent/SKILL.md
+++ b/agent/SKILL.md
@@ -133,7 +133,7 @@ Comprehensive knowledge base covering:
Use `load_skill(name)` to access full methodology docs with code templates.
-## Available MCP Tools (73)
+## Available MCP Tools (74)
| Tool | Description | API Key |
|------|-------------|---------|
@@ -180,6 +180,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.
| `list_strategies` | Browse discoverable strategies (Alpha Zoo + SDM store) | None |
| `query_strategies` | Evidence-gated query: regime / Sharpe / quality / cost filters | None |
| `get_strategy_evidence` | Per-regime evidence rows for one strategy | None |
+| `refresh_strategy_evidence` | Rebuild the disposable strategy-evidence cache from run artifacts | None |
| `analyze_trade_journal` | Parse broker CSV → profile + behavior diagnostics | None |
| `extract_shadow_strategy` | Distill 3-5 if-then rules from profitable roundtrips | None |
| `run_shadow_backtest` | Multi-market backtest + delta-PnL attribution | None* |
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 7e03099fd..331b5f4c8 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -5013,6 +5013,10 @@ def _build_parser() -> argparse.ArgumentParser:
from cli.commands.research_playbook import add_subparser as _add_playbook_subparser
_add_playbook_subparser(subparsers)
+ # Strategy-evidence cache refresh (manifest-driven rebuild)
+ from cli.commands.strategy_evidence import add_subparser as _add_strategy_evidence_subparser
+ _add_strategy_evidence_subparser(subparsers)
+
return parser
@@ -5917,6 +5921,9 @@ def main(argv: list[str] | None = None) -> int:
if args.command == "playbook":
from cli.commands.research_playbook import dispatch as _playbook_dispatch
return _coerce_exit_code(_playbook_dispatch(args))
+ if args.command == "strategy-evidence":
+ from cli.commands.strategy_evidence import dispatch as _strategy_evidence_dispatch
+ return _coerce_exit_code(_strategy_evidence_dispatch(args))
if args.command == "connector":
return _coerce_exit_code(_dispatch_connector(args))
if args.command == "memory":
diff --git a/agent/cli/commands/strategy_evidence.py b/agent/cli/commands/strategy_evidence.py
new file mode 100644
index 000000000..6d3528c8a
--- /dev/null
+++ b/agent/cli/commands/strategy_evidence.py
@@ -0,0 +1,173 @@
+"""CLI surface for the strategy-discovery evidence cache.
+
+``vibe-trading strategy-evidence refresh --manifest <path>`` rebuilds the
+disposable facade-owned evidence cache from real backtest run artifacts —
+the same core the ``refresh_strategy_evidence`` agent tool runs
+(:func:`src.tools.strategy_discovery_tool.refresh_strategy_evidence_core`),
+so there is ONE spec-parsing/validation code path for both surfaces. The CLI
+never shells out to the agent tool.
+
+Querying the evidence stays with the agent tools (``list_strategies`` /
+``query_strategies`` / ``get_strategy_evidence``); this command only
+populates/refreshes the cache they read.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import logging
+from typing import Any, Optional
+
+logger = logging.getLogger(__name__)
+
+_STRATEGY_EVIDENCE_PARSER: Optional[argparse.ArgumentParser] = None
+
+
+def _console() -> Any:
+ """Return the shared CLI console."""
+ from cli.theme import get_console
+
+ return get_console()
+
+
+def _print(message: str) -> None:
+ """Print one line through the shared console."""
+ _console().print(message)
+
+
+def _render_summary(envelope: dict) -> None:
+ """Human-readable refresh summary: rows written, strategies, skipped table."""
+ from rich.table import Table
+
+ console = _console()
+ console.print(
+ f"Refreshed strategy evidence: [bold]{envelope.get('rows', 0)}[/bold] "
+ f"row(s) across [bold]{envelope.get('strategies', 0)}[/bold] "
+ f"strateg(y/ies) from {envelope.get('runs', 0)} run spec(s)."
+ )
+ skipped = envelope.get("skipped") or []
+ if not skipped:
+ return
+ table = Table(title="Skipped runs", title_style="bold", box=None, pad_edge=False)
+ table.add_column("run_dir", style="cyan", overflow="fold")
+ table.add_column("reason", overflow="fold")
+ for entry in skipped:
+ table.add_row(str(entry.get("run_dir")), str(entry.get("reason")))
+ console.print(table)
+
+
+def _cmd_refresh(args: argparse.Namespace) -> int:
+ """Handle ``vibe-trading strategy-evidence refresh``."""
+ from src.tools.strategy_discovery_tool import refresh_strategy_evidence_core
+
+ manifest = getattr(args, "strategy_evidence_manifest", None)
+ try:
+ envelope = refresh_strategy_evidence_core(manifest_path=manifest)
+ except ValueError as exc:
+ message = str(exc)
+ if getattr(args, "strategy_evidence_json", False):
+ print(json.dumps({"status": "error", "error": message}, ensure_ascii=False))
+ else:
+ _print(f"[bold red]{message}[/bold red]")
+ return 2
+ except Exception: # noqa: BLE001 — one line for the operator, never a traceback
+ # Full detail goes to the logs only; the operator-facing message must
+ # not echo raw exception text (it can leak internal paths), mirroring
+ # the MCP envelope redaction.
+ logger.exception("strategy-evidence refresh failed")
+ message = "evidence refresh failed internally; see logs for detail"
+ if getattr(args, "strategy_evidence_json", False):
+ print(json.dumps({"status": "error", "error": message}, ensure_ascii=False))
+ else:
+ _print(f"[bold red]{message}[/bold red]")
+ return 1
+
+ if getattr(args, "strategy_evidence_json", False):
+ print(json.dumps(envelope, ensure_ascii=False, indent=2))
+ else:
+ _render_summary(envelope)
+ return 0
+
+
+_DISPATCH = {
+ "refresh": _cmd_refresh,
+}
+
+
+def add_subparser(subparsers: Any) -> argparse.ArgumentParser:
+ """Register ``strategy-evidence`` and its subcommands on the parent.
+
+ Args:
+ subparsers: The object returned by ``ArgumentParser.add_subparsers``.
+
+ Returns:
+ The ``strategy-evidence`` parser, for test introspection.
+ """
+ global _STRATEGY_EVIDENCE_PARSER
+
+ parser = subparsers.add_parser(
+ "strategy-evidence",
+ help="Strategy-evidence cache: refresh from backtest run artifacts",
+ description=(
+ "Manage the strategy-discovery evidence cache. Only 'refresh' "
+ "lives here — querying evidence stays with the agent tools "
+ "(list_strategies / query_strategies / get_strategy_evidence)."
+ ),
+ )
+ sub = parser.add_subparsers(dest="strategy_evidence_command")
+
+ p_refresh = sub.add_parser(
+ "refresh",
+ help="Rebuild the evidence cache from a JSON manifest of run specs",
+ description=(
+ "Rebuild the disposable strategy-evidence cache from real "
+ "backtest run artifacts. The manifest is a JSON object with a "
+ "'runs' array or a bare JSON array of "
+ "{strategy_id, run_dir, position_size?} entries. Runs failing "
+ "the ingestion gates are skipped with reasons; the rest still "
+ "process."
+ ),
+ )
+ p_refresh.add_argument(
+ "--manifest",
+ dest="strategy_evidence_manifest",
+ required=True,
+ help="Path to the JSON manifest of run specs",
+ )
+ p_refresh.add_argument(
+ "--json",
+ dest="strategy_evidence_json",
+ action="store_true",
+ help="Emit the machine-readable envelope instead of a summary",
+ )
+
+ _STRATEGY_EVIDENCE_PARSER = parser
+ return parser
+
+
+def dispatch(args: argparse.Namespace) -> int:
+ """Dispatch ``strategy-evidence <sub>`` to its handler.
+
+ Returns:
+ A process exit code: ``0`` on success, ``1`` on a failed operation,
+ ``2`` on a usage error.
+ """
+ sub = getattr(args, "strategy_evidence_command", None)
+ handler = _DISPATCH.get(sub or "")
+ if handler is None:
+ if _STRATEGY_EVIDENCE_PARSER is not None:
+ _STRATEGY_EVIDENCE_PARSER.print_help()
+ else:
+ _print(
+ "[red]strategy-evidence requires a subcommand.[/red] "
+ "Try: vibe-trading strategy-evidence refresh --manifest <path>"
+ )
+ return 2
+ return int(handler(args))
+
+
+__all__ = [
+ "add_subparser",
+ "dispatch",
+]
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index 83ac70e71..cab8473a7 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -6,7 +6,7 @@ Zero API key required for HK/US/crypto research markets (yfinance, OKX,
AKShare are free). Trading connector tools are profile-scoped and require the
selected connector's own local app or OAuth setup.
-Surfaces 73 tools: skills, research goals, strategy discovery,
+Surfaces 74 tools: skills, research goals, strategy discovery,
backtest/factor/options/pattern
analysis, market data, fundamentals & capital-flow & news & discovery
(get_fund_flow / get_dragon_tiger / get_northbound_flow / get_margin_trading /
@@ -20,7 +20,9 @@ etf_holdings / prediction_market / research_papers), read-only finance math and
market analytics (quantlib_call / cashflow_performance / orderbook_depth /
sentiment / technical_indicators / get_fundamentals), read-only
trading-connector reads, swarm orchestration, trade-journal and shadow-account
-analysis. Every exposed tool is read-only or research-only; no order-placing or
+analysis. Every exposed tool is read-only or research-only except
+refresh_strategy_evidence, which writes ONLY the disposable facade-owned
+strategy-evidence cache from local run artifacts; no order-placing or
order-cancelling tool is ever surfaced via MCP. The QVeris tools additionally
require QVeris paid routing (QVERIS_API_KEY + paid mode), and qveris_execute
is billable research-data execution only — it never places orders.
@@ -1207,6 +1209,7 @@ def query_strategies(
min_trades: int = 10,
cost_feasible: bool = True,
limit: int = 10,
+ include_stale: bool = False,
) -> str:
"""Query strategies whose computed per-regime evidence passes the filters.
@@ -1230,6 +1233,10 @@ def query_strategies(
cost_feasible: Keep only strategies that pass the sizing-corrected
cost-breakeven screen (default True).
limit: Maximum number of strategies to return (default 10).
+ include_stale: Also keep rows whose evidence window is stale (default
+ False). Stale rows fail closed out of default recommendations;
+ True inspects them with their stale-evidence: warnings, sorted
+ after non-stale rows. Relaxes the staleness gate only.
"""
return _strategy_discovery_execute(
"query_strategies",
@@ -1240,6 +1247,7 @@ def query_strategies(
"min_trades": min_trades,
"cost_feasible": cost_feasible,
"limit": limit,
+ "include_stale": include_stale,
},
)
@@ -1267,6 +1275,38 @@ def get_strategy_evidence(strategy_id: str, regime: str | None = None) -> str:
)
+def refresh_strategy_evidence(
+ manifest_path: str | None = None, runs: list | None = None
+) -> str:
+ """Rebuild the strategy-discovery evidence cache from backtest run artifacts.
+
+ WRITE tool with disposable-cache-only scope: it replaces the facade-owned
+ strategy-evidence cache (drop-and-rebuild by contract) from local run
+ artifacts and NEVER touches the Alpha Zoo or SDM sources of truth. No
+ network access, no credentials, no broker paths.
+
+ Provide EXACTLY ONE of the two parameters:
+ - manifest_path: path to a JSON manifest — an object with a "runs" array
+ ({"runs": [{strategy_id, run_dir, position_size?}, ...]}) or a bare
+ JSON array of the same entries.
+ - runs: inline array of {strategy_id, run_dir, position_size?} objects.
+
+ Supplying both or neither returns an error envelope. Runs that fail the
+ ingestion gates (unhealthy artifacts, run_dir outside the allowed run
+ roots) are skipped with machine-readable reasons while the rest still
+ process.
+
+ Args:
+ manifest_path: Path to the JSON manifest file (see above).
+ runs: Inline run specs (see above).
+ """
+ return _strategy_discovery_execute(
+ "refresh_strategy_evidence",
+ {"manifest_path": manifest_path, "runs": runs},
+ )
+
+
# ---------------------------------------------------------------------------
# Trading connector tools
# ---------------------------------------------------------------------------
diff --git a/agent/src/skills/backtest-diagnose/SKILL.md b/agent/src/skills/backtest-diagnose/SKILL.md
index ce07e31fa..bdc5269e2 100644
--- a/agent/src/skills/backtest-diagnose/SKILL.md
+++ b/agent/src/skills/backtest-diagnose/SKILL.md
@@ -62,6 +62,10 @@ These issues require the user to check the API token, switch data sources, or wa
4. The equity series contains no `NaN`
5. `exit_code == 0`
+## Evidence hookup
+
+This Hard-Gate Checklist is also the evidence ingestion gate for Strategy Discovery: a run failing any gate produces **no evidence rows** — never partial rows — and is skipped with a stable machine-readable token (`hard-gate:exit-nonzero`, `hard-gate:metrics-missing`, `hard-gate:zero-trades`, `hard-gate:equity-empty`, `hard-gate:equity-nan`). Diagnose and fix the failing gate as usual, rerun the backtest, then repopulate the evidence cache with `refresh_strategy_evidence` (agent tool / MCP tool, or `vibe-trading strategy-evidence refresh --manifest <path>`) so the fixed run becomes queryable evidence. See the `strategy-discovery` skill for the manifest format and the full gate list.
+
## Fixing Principles
- Use **edit_file** to make precise code fixes instead of rewriting the entire file with `write_file`, unless the structure is fundamentally broken
diff --git a/agent/src/skills/strategy-discovery/SKILL.md b/agent/src/skills/strategy-discovery/SKILL.md
index 914df09bb..ad4e4c29b 100644
--- a/agent/src/skills/strategy-discovery/SKILL.md
+++ b/agent/src/skills/strategy-discovery/SKILL.md
@@ -1,6 +1,6 @@
---
name: strategy-discovery
-description: "Strategy Discovery: evidence-gated read-only facade over Alpha Zoo + the SDM strategy store — answers what strategies exist and what state they are in, with per-regime evidence instead of scenario tags."
+description: "Strategy Discovery: evidence-gated facade over Alpha Zoo + the SDM strategy store — answers what strategies exist and what state they are in, with per-regime evidence instead of scenario tags; reports evidence freshness on every returned row and rebuilds the disposable evidence cache from local backtest runs."
category: research
---
@@ -8,11 +8,11 @@ category: research
## Purpose
-Strategy Discovery is the single read-only entry point for two questions: **what strategies exist**, and **what state are they in**. It fronts the Alpha Zoo registry and the SDM strategy store with one facade and answers with computed evidence instead of labels.
+Strategy Discovery is the single entry point for two questions: **what strategies exist**, and **what state are they in**. It fronts the Alpha Zoo registry and the SDM strategy store with one facade and answers with computed evidence instead of labels, and it reports the freshness of that evidence on every returned row.
It supersedes the earlier closed-registry attempt. That design attached boolean scenario tags (works in bear markets: yes/no) to a curated list. This skill replaces tags with **per-regime evidence rows**: every claim that a strategy works in a regime must come from a computed, reproducible backtest stored as evidence, never from curation or inference.
-The surface is read-only. It never registers, mutates, or deletes strategies. To add or change strategies, use the `strategy-dev-manager` and `alpha-zoo` workflows — Strategy Discovery only reports what those workflows have produced.
+The three query tools are read-only: they never register, mutate, or delete strategies. To add or change strategies, use the `strategy-dev-manager` and `alpha-zoo` workflows — Strategy Discovery only reports what those workflows have produced. The fourth tool, `refresh_strategy_evidence`, is the single write in the surface: it rebuilds ONLY the disposable evidence cache from local backtest run artifacts (see Populating & Refreshing Evidence and Composition Guarantee).
## When to Use
@@ -21,9 +21,10 @@ Decision tree for routing user requests:
- User asks **what strategies exist** / "list available strategies" → `list_strategies(limit=..., offset=..., source=...)`
- User asks **which strategy fits a regime or threshold** ("what works in bear markets?", "anything with Sharpe above 1?") → `query_strategies(regime=..., min_sharpe=..., ...)`
- User asks for **the evidence behind one specific strategy** → `get_strategy_evidence(strategy_id=..., regime=...)`
+- User asks to **populate or refresh the evidence cache** ("turn my backtest runs into evidence", "the evidence is stale, refresh it") → `refresh_strategy_evidence(manifest_path=...)` — this rebuilds the disposable cache from run artifacts; it is NOT strategy creation or registration
- User asks to **create, backtest, or register** a strategy → this is NOT this skill; route to `strategy-generate` / `strategy-dev-manager` / `alpha-zoo`
-This skill has **no CLI surface** — there is no `vibe-trading strategy-discovery` command and no CLI flags. The only access path is the three tools (`list_strategies`, `query_strategies`, `get_strategy_evidence`), available through the agent registry and the MCP server under the same names. Do not invent flags or subcommands.
+The access path is the three read tools (`list_strategies`, `query_strategies`, `get_strategy_evidence`) plus one cache-refresh tool (`refresh_strategy_evidence`), available through the agent registry and the MCP server under the same names. The only CLI surface is `vibe-trading strategy-evidence refresh --manifest <path>`, which runs the same refresh as the tool; queries stay with the agent tools. Do not invent flags or subcommands beyond that.
## Tools
@@ -35,7 +36,7 @@ Browse the catalogue.
|-----------|------|---------|---------|
| `limit` | integer | 20 | Maximum number of rows to return |
| `offset` | integer | 0 | Pagination offset |
-| `source` | string | none | Optional filter: `alpha_zoo` or `sdm`; omit for both |
+| `source` | string | none | Optional filter: `alpha_zoo \| sdm`; omit for both |
Returns identification metadata plus evidence status. This is a catalogue listing, not a ranking — use `query_strategies` for filtered, evidence-ranked results.
@@ -50,6 +51,7 @@ Evidence-gated query.
| `min_evidence_quality` | string | `adequate` | `adequate` \| `marginal` \| `insufficient` \| `any`. `any` only removes the quality floor — rows must still pass the other filters (`min_trades`, `cost_feasible`, `min_sharpe`) to be kept |
| `min_trades` | integer | 10 | Minimum executed-trade count for evidence to count |
| `cost_feasible` | boolean | true | Keep only rows that clear the cost screen. Fail-closed: rows whose breakeven is unverifiable (`null`, see Multi-position caveat) are excluded; set `false` to inspect them with their warnings |
+| `include_stale` | boolean | false | Keep rows whose evidence is stale (see Decay & Freshness Contract). They are surfaced with their `stale-evidence:` warnings, sorted after non-stale rows; the flag relaxes the staleness gate only, never any other gate |
| `limit` | integer | 10 | Maximum number of rows to return |
### get_strategy_evidence
@@ -61,7 +63,18 @@ Per-regime evidence detail for one strategy.
| `strategy_id` | string | — | Required. Identifier from `list_strategies` / `query_strategies` |
| `regime` | string | none | Optional regime filter (same values as `query_strategies`) |
-Returns the per-regime evidence rows: trade count, coverage window, Sharpe, cost breakeven, and the resulting evidence-quality flag.
+Returns the per-regime evidence rows: trade count, coverage window, Sharpe, cost breakeven, the decay fields, and the resulting evidence-quality flag. This is an inspection surface — it returns ALL rows for the strategy and never filters.
+
+### refresh_strategy_evidence
+
+Rebuild the disposable evidence cache from local backtest run artifacts. This is the surface's only write; it touches only the facade-owned cache (see Composition Guarantee).
+
+| Parameter | Type | Default | Meaning |
+|-----------|------|---------|---------|
+| `manifest_path` | string | none | Path to a JSON manifest: an object `{"runs": [...]}` or a bare JSON array of run specs |
+| `runs` | array | none | Inline run specs, same shape as the manifest's `runs` array |
+
+Exactly one of `manifest_path` or `runs` is required — supplying both or neither is an error. Each spec is `{strategy_id, run_dir, position_size?}`: a non-empty `strategy_id` (the catalogue identity the evidence belongs to), the `run_dir` of a reproducible backtest run, and an optional `position_size` passed through to the harness. Every entry is hard-gated and path-contained (see Populating & Refreshing Evidence); failing entries are skipped with a stable reason — `hard-gate:*` or `path-outside-allowed-roots:` — while the rest still process. The envelope reports `{status, runs, strategies, rows, skipped}`.
## Evidence Row Contract
@@ -73,7 +86,10 @@ Every row is self-describing — the metadata travels with the numbers:
| `provenance` | The reproducible backtest run directory the row was computed from (`artifacts/trades.csv` + `artifacts/equity.csv` inside it). The run directory holds the config and signal engine that produced the figures, so every row is traceable to a reproducible artifact |
| `regime_definition` | JSON naming the regime-labeling parameters used (rolling benchmark window, bear/bull thresholds, Sharpe annualization) — the definition travels with the data, not hidden in code constants |
| `breakeven_fee_bps` | Sizing-corrected cost breakeven, or `null` when the cost screen is unverifiable (see Multi-position caveat) |
-| `warnings` | Stable machine-readable prefixes: `insufficient-trades:`, `short-coverage:`, `cost-sensitive:`, `borderline-evidence:`, `multi-position-breakeven:` |
+| `decay_status` | Freshness verdict computed at read time: `fresh` \| `aging` \| `stale` (see Decay & Freshness Contract). Never stored — derived from the evidence window on every query |
+| `evidence_age_days` | Days since the end of the row's latest evidence window; the number that drives `decay_status` |
+| `staleness_days` | Days since the row's `last_verified` timestamp. Reported only — never gates anything (see Decay & Freshness Contract) |
+| `warnings` | Stable machine-readable prefixes: `insufficient-trades:`, `short-coverage:`, `cost-sensitive:`, `borderline-evidence:`, `multi-position-breakeven:`, `stale-evidence:`, `aged-evidence:`, `sdm-lifecycle:` |
## Evidence Thresholds
@@ -112,14 +128,85 @@ Consequences for queries:
- The rows are not lost: query with `cost_feasible=false` or call `get_strategy_evidence` to see them with their warnings.
- Single-position runs keep the exact sizing-corrected breakeven and are unaffected.
+## Decay & Freshness Contract
+
+Every returned row carries a freshness verdict computed from the evidence itself at read time — never from model memory, never persisted. The verdict is **freshness-derived**, not performance-derived: it measures how old the evidence window is, not how the strategy is performing. Performance decay (degraded results measured on holdout/shadow/live evidence) arrives with holdout/shadow-stage rows — that ladder is reserved, and no such rows exist yet. Until then, the honest signal is window recency.
+
+Vocabulary and thresholds, applied to `evidence_age_days` (days since the end of the row's latest evidence window):
+
+| `decay_status` | Condition | Meaning |
+|----------------|-----------|---------|
+| `fresh` | age < 90 days | Evidence window is current; the row participates in recommendations |
+| `aging` | 90 ≤ age < 180 days | Window is older than one re-backtest cycle; the row is still returned and recommendable, with an `aged-evidence:` warning |
+| `stale` | age ≥ 180 days, or window unparseable | The row is excluded from default recommendations; inspectable via `include_stale=true` or `get_strategy_evidence` |
+
+The 90/180-day thresholds encode the documented **quarterly re-backtest cadence**: a window end more than 90 days old means at least one scheduled re-backtest cycle was missed; more than 180 days means at least two. Exact-threshold ages take the stricter side (`age >= 180` ⇒ stale, else `age >= 90` ⇒ aging, else fresh).
+
+`evidence_age_days` is the only field that drives the verdict. `last_verified` and its derived `staleness_days` are **reported on every row but never gate** — a refresh over unchanged artifacts bumps `last_verified` without moving the evidence window, and gating on it would let a no-op refresh keep old evidence "fresh" forever.
+
+Fail-closed: a row whose evidence window cannot be parsed is `stale`. An unparseable window is never relaxed into a guess.
+
+Stable machine-readable prefixes:
+
+| Prefix | Where it appears | Meaning |
+|--------|------------------|---------|
+| `stale-evidence:` | row warnings | Window end is missing/unparseable or at least 180 days old; the row is excluded from default recommendations |
+| `aged-evidence:` | row warnings | Window end is at least 90 days old; the row is returned but flagged for re-backtest |
+| `sdm-lifecycle:` | row warnings / `lifecycle_note` | The `sdm:*` strategy's artifact is decayed or disabled in the SDM store; excluded from recommendations regardless of freshness |
+| `hard-gate:*` | refresh envelope `skipped` list | The run failed one of the ingestion hard gates and produced no evidence rows (see Populating & Refreshing Evidence) |
+
+`include_stale` (on `query_strategies`, default `false`) controls the staleness gate only: `true` surfaces staleness-excluded rows with their `stale-evidence:` warnings, sorted after non-stale rows. It does not relax any other gate, and it never affects lifecycle exclusions. Aging rows are never excluded — they carry `aged-evidence:` warnings.
+
+SDM lifecycle mirroring: for rows whose `strategy_id` starts with `sdm:`, the facade looks up the SDM artifact status. `decayed` or `disabled` artifacts are excluded from default recommendations regardless of evidence freshness, with the `sdm-lifecycle:` prefix, and counted separately in the envelope; they remain inspectable via `get_strategy_evidence`. A decayed or disabled SDM artifact is never recommended.
+
+## Populating & Refreshing Evidence
+
+The evidence cache is populated and refreshed through `refresh_strategy_evidence` (agent tool / MCP tool) or the equivalent CLI, `vibe-trading strategy-evidence refresh --manifest <path>`. There is no auto-discovery of runs — population is manifest-first, because runs carry no stable strategy identity of their own (directory names are timestamp+uuid, and an auto-derived id would orphan its rows on every rerun).
+
+Manifest format — a JSON object with a `runs` array, or a bare JSON array of the same specs:
+
+```json
+{
+ "runs": [
+ {"strategy_id": "sdm:my_strategy", "run_dir": "~/.vibe-trading/runs/20260701-123456-abcdef", "position_size": 0.25},
+ {"strategy_id": "alpha_zoo:gtja191_171", "run_dir": "~/.vibe-trading/runs/20260702-234567-bcdef0"}
+ ]
+}
+```
+
+Each `run_dir` must resolve inside the runtime runs root or `VIBE_TRADING_ALLOWED_RUN_ROOTS`; entries outside are skipped with `path-outside-allowed-roots:` while the rest still process. Expect manifests in the tens of runs, not thousands — a full rebuild must complete within the tool timeout.
+
+Every run passes five hard gates before it can produce evidence rows — one-to-one with the `backtest-diagnose` skill's Hard-Gate Checklist, in this order:
+
+1. Run status is `success` (`state.json`) → else `hard-gate:exit-nonzero` (a missing `state.json` fails onto the same token)
+2. `artifacts/metrics.csv` exists non-empty → else `hard-gate:metrics-missing`
+3. `trade_count > 0` → else `hard-gate:zero-trades`
+4. `artifacts/equity.csv` exists non-empty → else `hard-gate:equity-empty`
+5. The equity series contains no NaN/non-finite value → else `hard-gate:equity-nan`
+
+A run failing any gate produces **no evidence rows** — never partial rows — and is reported in the envelope's `skipped` list with its stable token. The rebuild is atomic: either all computed rows replace the cache in one transaction, or the prior cache survives intact.
+
+**Periodic recipe** (this is what keeps evidence fresh):
+
+1. Re-backtest the strategy over a **recent window** — the window end is what `evidence_age_days` measures
+2. `refresh_strategy_evidence` with a manifest naming the new run
+3. `query_strategies` — the rows now carry the moved window
+
+Refreshing over unchanged artifacts is legal but limited: it re-verifies and bumps `last_verified`, and can never move the evidence window forward. That is why the recipe starts with a re-backtest, and why `last_verified` never gates.
+
+**Scheduling**: the re-backtest + refresh cadence can run through the existing `/scheduled-runs` mechanism — no new scheduler exists, and its semantics apply. The executor is off by default (`VIBE_TRADING_ENABLE_SCHEDULER=1` enables it); a job status of COMPLETED means the run was enqueued, and FAILED jobs are terminal after repeated failures — check job status rather than assuming a cadence is alive.
+
+**After an upgrade**: the evidence cache is disposable by contract — any cache schema drift drops it, so an upgraded install can start with an empty store. `refresh_strategy_evidence` is how it is repopulated; an empty result is the expected state until the first refresh (see Honest-Empty Semantics).
+
## Honest-Empty Semantics
The facade refuses regime assessments without computed evidence. If a strategy has no backtest evidence for a regime, `get_strategy_evidence` returns an honest empty for that regime instead of a guess; `query_strategies` likewise never fabricates rows to satisfy a filter.
-An empty result is an answer, not an error: it means "no computed evidence exists for this request." There is **no user-runnable command or workflow** that changes that. The evidence store is populated only by the evidence harness **library API** (`src.strategy_discovery.evidence_harness.rebuild_evidence` over reproducible run artifacts); automated workflow wiring is still pending, so until then evidence rows come from harness runs executed by developers/integrators. Never relax a threshold or narrate from a scenario tag instead.
+An empty result is an answer, not an error: it means "no computed evidence exists for this request." The population path is `refresh_strategy_evidence` (agent tool / MCP tool) or `vibe-trading strategy-evidence refresh --manifest <path>` — point a manifest of healthy backtest runs at the cache and the rows appear (see Populating & Refreshing Evidence). Until a refresh has run, an empty store is the expected state after a fresh install or an upgrade. Never relax a threshold or narrate from a scenario tag instead.
## Composition Guarantee
-- **Reads only**: the Alpha Zoo Registry, the SDM strategy store, and the facade-owned evidence cache DB. Modifies nothing in any of them.
-- **Cache is disposable**: the evidence cache DB is owned by the facade, deletable, and rebuildable from the two authoritative sources. Its location can be overridden with the `VIBE_TRADING_STRATEGY_DISCOVERY_DB_PATH` environment variable; unset means the default location.
+- **Query tools read-only**: `list_strategies`, `query_strategies`, and `get_strategy_evidence` read the Alpha Zoo Registry, the SDM strategy store, and the facade-owned evidence cache DB — and modify nothing in any of them.
+- **Refresh tool writes only the disposable cache**: `refresh_strategy_evidence` rebuilds the facade-owned evidence cache DB from local run artifacts, and nothing else. It never writes to the Alpha Zoo registry, the SDM store, or the run artifacts it reads; no network, no credentials, no broker paths.
+- **Cache is disposable**: the evidence cache DB is owned by the facade, deletable, and rebuildable from run artifacts plus the two authoritative sources. Its location can be overridden with the `VIBE_TRADING_STRATEGY_DISCOVERY_DB_PATH` environment variable; unset means the default location.
- **No other state**: no network calls, no writes outside the cache, no side effects on the registries it reads.
diff --git a/agent/src/strategy_discovery/evidence_harness.py b/agent/src/strategy_discovery/evidence_harness.py
index de2945cff..92f82219e 100644
--- a/agent/src/strategy_discovery/evidence_harness.py
+++ b/agent/src/strategy_discovery/evidence_harness.py
@@ -52,8 +52,11 @@ from src.strategy_discovery.models import (
coverage_days_from_ranges,
)
from src.strategy_discovery.run_artifacts import (
+ equity_has_non_finite,
parse_finite_float,
read_equity_series,
+ read_metrics_trade_count,
+ read_run_status,
read_trade_activity,
)
@@ -81,6 +84,114 @@ SHARPE_ANNUALIZATION_BARS = 252
#: over backtest run artifacts, so no other stage is honest today.
HARNESS_EVIDENCE_STAGE = "backtest"
+# ---------------------------------------------------------------------------
+# Hard gates (backtest-diagnose hookup, plan D4). The backtest-diagnose
+# Hard-Gate Checklist IS the evidence ingestion gate: an unhealthy run
+# produces no evidence rows, and the refusal is reported with one of these
+# stable, machine-readable tokens (1:1 with the checklist).
+# ---------------------------------------------------------------------------
+
+#: Run did not finish successfully — state.json missing/unreadable (fail
+#: closed) or its ``status`` is not ``"success"``.
+HARD_GATE_EXIT_NONZERO = "hard-gate:exit-nonzero"
+
+#: ``artifacts/metrics.csv`` missing or empty.
+HARD_GATE_METRICS_MISSING = "hard-gate:metrics-missing"
+
+#: metrics.csv ``trade_count`` is zero, negative, or unparseable.
+HARD_GATE_ZERO_TRADES = "hard-gate:zero-trades"
+
+#: ``artifacts/equity.csv`` missing, empty, or unverifiable.
+HARD_GATE_EQUITY_EMPTY = "hard-gate:equity-empty"
+
+#: equity series contains a NaN/non-finite value anywhere.
+HARD_GATE_EQUITY_NAN = "hard-gate:equity-nan"
+
+
+def check_run_hard_gates(run_dir: str | Path) -> tuple[bool, str | None]:
+ """Run the D4 hard gates against one run dir, in order.
+
+ Returns ``(True, None)`` when the run is admissible as evidence, else
+ ``(False, "hard-gate:<token>: <detail>")`` with the FIRST failing gate's
+ stable token. Gate order and sources (plan D4):
+
+ 1. ``state.json`` exists AND ``status == "success"`` → else
+ ``hard-gate:exit-nonzero`` (a missing state.json fails closed onto
+ the same token).
+ 2. ``artifacts/metrics.csv`` exists non-empty → else
+ ``hard-gate:metrics-missing``.
+ 3. ``trade_count > 0`` parsed from metrics.csv → else
+ ``hard-gate:zero-trades``.
+ 4. ``artifacts/equity.csv`` exists non-empty → else
+ ``hard-gate:equity-empty``.
+ 5. equity series contains no NaN/non-finite value → else
+ ``hard-gate:equity-nan``.
+
+ Documented divergence (eligibility vs sufficiency): metrics.csv
+ ``trade_count`` gates ELIGIBILITY (this hard gate), while the harness's
+ own closed-round-trip count gates EVIDENCE SUFFICIENCY (per-regime rows
+ below). They can disagree — e.g. entries without exits raise
+ ``trade_count`` without adding a round trip — and that is intentional:
+ the hard gate only certifies the run is structurally healthy.
+ """
+ run_path = Path(run_dir)
+
+ status = read_run_status(run_path)
+ if status != "success":
+ detail = (
+ "state.json missing or unreadable (run status unknown)"
+ if status is None
+ else f"run status is {status!r}, not 'success'"
+ )
+ return False, f"{HARD_GATE_EXIT_NONZERO}: {detail}"
+
+ metrics_path = run_path / "artifacts" / "metrics.csv"
+ try:
+ metrics_present = metrics_path.is_file() and metrics_path.stat().st_size > 0
+ except OSError:
+ metrics_present = False
+ if not metrics_present:
+ return (
+ False,
+ f"{HARD_GATE_METRICS_MISSING}: artifacts/metrics.csv missing or empty",
+ )
+
+ trade_count = read_metrics_trade_count(run_path)
+ if trade_count is None or trade_count <= 0:
+ detail = (
+ "trade_count missing or unparseable in metrics.csv"
+ if trade_count is None
+ else f"trade_count is {trade_count}"
+ )
+ return False, f"{HARD_GATE_ZERO_TRADES}: {detail}"
+
+ equity_path = run_path / "artifacts" / "equity.csv"
+ try:
+ equity_present = equity_path.is_file() and equity_path.stat().st_size > 0
+ except OSError:
+ equity_present = False
+ if not equity_present:
+ return (
+ False,
+ f"{HARD_GATE_EQUITY_EMPTY}: artifacts/equity.csv missing or empty",
+ )
+
+ non_finite = equity_has_non_finite(run_path)
+ if non_finite is None:
+ return (
+ False,
+ f"{HARD_GATE_EQUITY_EMPTY}: artifacts/equity.csv unreadable or "
+ "carries no usable rows",
+ )
+ if non_finite:
+ return (
+ False,
+ f"{HARD_GATE_EQUITY_NAN}: equity series contains NaN/non-finite "
+ "values; no partial-curve evidence is computed",
+ )
+
+ return True, None
+
def describe_regime_definition(
benchmark_window: int, bear_threshold: float, bull_threshold: float
@@ -227,7 +338,7 @@ def _bar_returns(bar_indices: Sequence[int], series: Sequence[float]) -> list[fl
continue
previous = series[index - 1]
current = series[index]
- if previous <= 0 or not math.isfinite(current):
+ if previous <= 0 or not math.isfinite(previous) or not math.isfinite(current):
continue
returns.append(current / previous - 1.0)
return returns
@@ -301,6 +412,12 @@ def compute_evidence_for_run(
Returns ``[]`` (with a warning) whenever the required artifacts are
absent or unusable — the harness never fabricates missing data.
+
+ The D4 hard gates (:func:`check_run_hard_gates`) run FIRST, so direct
+ library callers get the same fail-closed refusal as
+ :func:`rebuild_evidence` (which also calls the gates itself before
+ computing, so it can record the exact gate token as the skip reason —
+ both paths share the one gate function).
"""
if benchmark_window <= 0:
raise ValueError("benchmark_window must be a positive integer")
@@ -308,6 +425,16 @@ def compute_evidence_for_run(
raise ValueError("bear_threshold must be strictly below bull_threshold")
run_path = Path(run_dir)
+ gate_ok, gate_reason = check_run_hard_gates(run_path)
+ if not gate_ok:
+ logger.warning(
+ "strategy %s: run %s refused by the evidence ingestion gate "
+ "(%s) — no evidence computed",
+ strategy_id,
+ run_path,
+ gate_reason,
+ )
+ return []
trades_path = run_path / "artifacts" / "trades.csv"
equity_path = run_path / "artifacts" / "equity.csv"
if not trades_path.is_file() or not equity_path.is_file():
@@ -447,19 +574,34 @@ def compute_evidence_for_run(
def rebuild_evidence(runs: Sequence[Mapping], store: EvidenceStore) -> dict:
- """Clear the store and rebuild it from a sequence of run specifications.
+ """Atomically replace the store contents from a sequence of run specs.
Each mapping needs ``strategy_id`` and ``run_dir``; an optional
``position_size`` overrides exposure-derived sizing. Runs that yield no
computable evidence are reported in ``skipped`` with a reason — nothing
- is invented for them.
+ is invented for them. Runs refused by the D4 hard gates are skipped with
+ the exact ``hard-gate:<token>`` reason (the gates run here BEFORE
+ computation so the envelope can record the token;
+ :func:`compute_evidence_for_run` re-checks them internally for direct
+ library callers — both paths share :func:`check_run_hard_gates`).
+
+ ATOMIC (plan D5): ALL rows are computed first, then written with one
+ ``store.replace_rows(all_rows)`` call (DELETE-all + INSERT-all in a
+ single transaction). A mid-compute failure therefore never leaves the
+ store half-populated — the previous contents survive intact. An empty
+ ``all_rows`` still replaces (clears) the store: a rebuild is a full
+ statement of the evidence, not a patch.
+
+ Eligibility vs sufficiency (plan D4): the hard gates certify run
+ ELIGIBILITY from metrics.csv ``trade_count``; the per-regime rows below
+ are gated by EVIDENCE SUFFICIENCY (the harness's closed-round-trip
+ count). The two counts can disagree (entries without exits); that is
+ intentional and documented.
"""
skipped: list[dict] = []
all_rows: list[EvidenceRow] = []
ok_strategies: set[str] = set()
- store.clear()
-
for index, spec in enumerate(runs):
if not isinstance(spec, Mapping):
skipped.append(
@@ -485,6 +627,10 @@ def rebuild_evidence(runs: Sequence[Mapping], store: EvidenceStore) -> dict:
)
continue
try:
+ gate_ok, gate_reason = check_run_hard_gates(run_dir)
+ if not gate_ok:
+ skipped.append({"run_dir": str(run_dir), "reason": gate_reason})
+ continue
rows = compute_evidence_for_run(
strategy_id, run_dir, position_size=spec.get("position_size")
)
@@ -510,7 +656,7 @@ def rebuild_evidence(runs: Sequence[Mapping], store: EvidenceStore) -> dict:
all_rows.extend(rows)
ok_strategies.add(strategy_id)
- written = store.upsert_rows(all_rows)
+ written = store.replace_rows(all_rows)
return {
"status": "ok",
"runs": len(runs),
diff --git a/agent/src/strategy_discovery/evidence_store.py b/agent/src/strategy_discovery/evidence_store.py
index 4db96ac8e..022521088 100644
--- a/agent/src/strategy_discovery/evidence_store.py
+++ b/agent/src/strategy_discovery/evidence_store.py
@@ -267,6 +267,52 @@ class EvidenceStore:
count += 1
return count
+ def replace_rows(self, rows: Sequence[EvidenceRow]) -> int:
+ """Atomically replace ALL evidence rows with ``rows``.
+
+ DELETE-all + INSERT-all inside ONE ``_connect()`` context — a single
+ transaction, so a failure anywhere leaves the previous contents
+ intact (rollback) instead of the clear-then-upsert window where a
+ crash could leave the store empty (plan D5). Per-row validation is
+ identical to :meth:`upsert_rows` and runs before the DELETE, so an
+ invalid row set never touches the table. Returns rows written.
+
+ Raises:
+ ValueError: When any row carries a NaN/Inf numeric field.
+ """
+ materialized = list(rows)
+ for row in materialized:
+ _validate_row_for_write(row)
+ count = 0
+ with self._connect() as conn:
+ conn.execute(f"DELETE FROM {self.TABLE}")
+ for row in materialized:
+ conn.execute(
+ _INSERT_SQL,
+ (
+ row.strategy_id,
+ row.regime,
+ row.trades_in_regime,
+ row.position_size,
+ row.return_in_regime,
+ row.benchmark_in_regime,
+ row.excess_in_regime,
+ row.sharpe_in_regime,
+ row.max_drawdown_in_regime,
+ json.dumps(list(row.date_ranges), ensure_ascii=False),
+ row.breakeven_fee_bps,
+ 1 if row.cost_sensitive else 0,
+ row.evidence_quality,
+ json.dumps(list(row.warnings), ensure_ascii=False),
+ row.last_verified,
+ row.evidence_stage,
+ row.provenance,
+ row.regime_definition,
+ ),
+ )
+ count += 1
+ return count
+
def clear(self) -> None:
"""Delete every evidence row (used by harness rebuilds)."""
with self._connect() as conn:
diff --git a/agent/src/strategy_discovery/facade.py b/agent/src/strategy_discovery/facade.py
index a14a0a4ca..3af77e393 100644
--- a/agent/src/strategy_discovery/facade.py
+++ b/agent/src/strategy_discovery/facade.py
@@ -18,6 +18,7 @@ from __future__ import annotations
import dataclasses
import logging
import math
+from datetime import date
from typing import Any
from src.strategy_discovery.evidence_store import EvidenceStore
@@ -25,12 +26,17 @@ from src.strategy_discovery.models import (
BORDERLINE_BREAKEVEN_BPS,
BORDERLINE_COVERAGE_BUFFER_DAYS,
BORDERLINE_TRADE_BUFFER,
+ DECAY_STALE,
MIN_COVERAGE_DAYS,
MIN_TRADES,
QUALITY_ORDER,
REGIMES,
StrategySummary,
+ classify_decay,
coverage_days_from_ranges,
+ decay_warning,
+ evidence_age_days,
+ staleness_days,
)
logger = logging.getLogger(__name__)
@@ -48,17 +54,27 @@ _BORDERLINE_WARNING = (
)
#: Note attached to query results when the evidence table is completely empty.
-#: Honest wording: there is NO user-runnable CLI/workflow that populates the
-#: store — rows land only via the evidence harness library API.
+#: Names the population path: the ``refresh_strategy_evidence`` tool (agent +
+#: MCP) and the ``vibe-trading strategy-evidence refresh`` CLI command, both
+#: of which drive the evidence harness over reproducible run artifacts.
_EMPTY_EVIDENCE_NOTE = (
- "No per-regime evidence computed yet. The evidence store is populated only "
- "by the evidence harness library API "
- "(src.strategy_discovery.evidence_harness.rebuild_evidence over "
- "reproducible run artifacts); automated workflow wiring is still pending, "
- "so until then rows come from harness runs executed by developers/"
- "integrators. The facade refuses to assess regimes without evidence."
+ "No per-regime evidence computed yet. Populate the store with "
+ "`refresh_strategy_evidence` — exposed as an agent/MCP tool and as the "
+ "CLI command `vibe-trading strategy-evidence refresh --manifest <path>` — "
+ "which rebuilds evidence from reproducible backtest run artifacts "
+ "(library callers may drive "
+ "src.strategy_discovery.evidence_harness.rebuild_evidence directly). The "
+ "facade refuses to assess regimes without evidence."
)
+#: SDM lifecycle states that exclude an ``sdm:*`` row from default
+#: recommendations regardless of evidence freshness (plan D8 lifecycle
+#: mirroring — artifact status only, never the DecayEvaluator FSM).
+_SDM_EXCLUDED_STATUSES = ("decayed", "disabled")
+
+#: Stable prefix for lifecycle exclusions surfaced on inspection rows.
+_SDM_LIFECYCLE_PREFIX = "sdm-lifecycle:"
+
def _error(message: str) -> dict[str, Any]:
"""Standard error envelope shared with the other agent tool modules."""
@@ -85,6 +101,37 @@ def _is_int(value: Any) -> bool:
return isinstance(value, int) and not isinstance(value, bool)
+def _parse_today(today: str | None) -> date:
+ """Resolve the injected clock: ISO ``today`` string or the wall clock.
+
+ Raises ``ValueError`` for a non-string or unparseable ``today`` so the
+ caller can answer with an error envelope instead of a wrong date.
+ """
+ if today is None:
+ return date.today()
+ if not isinstance(today, str):
+ raise ValueError(f"today must be an ISO date string or None, got {today!r}")
+ return date.fromisoformat(today.strip())
+
+
+def _decay_fields(row, today: date) -> dict[str, Any]:
+ """Read-time decay verdict for one evidence row (plan D1/D2).
+
+ Computed from the row's own ``date_ranges`` window end at query time —
+ never persisted. ``staleness_days`` (from ``last_verified``) is reported
+ alongside but NEVER gates: refreshing unchanged artifacts must not be
+ able to keep a row "fresh" forever.
+ """
+ age = evidence_age_days(row.date_ranges, today)
+ status = classify_decay(row.date_ranges, today)
+ return {
+ "decay_status": status,
+ "evidence_age_days": age,
+ "staleness_days": staleness_days(row.last_verified, today),
+ "_decay_warning": decay_warning(status, age),
+ }
+
+
class StrategyDiscoveryFacade:
"""Read-only unified discovery surface over Alpha Zoo + SDM + evidence."""
@@ -146,6 +193,42 @@ class StrategyDiscoveryFacade:
self._sdm_failed = True
return self._sdm_store
+ def _sdm_artifact_status(self, artifact_id: str) -> str | None:
+ """Read-only SDM artifact status lookup for lifecycle mirroring.
+
+ Degrades gracefully (plan D8): a missing store, a missing
+ ``get_artifact`` surface, or any lookup failure returns ``None``
+ with a logged warning — the lifecycle gate then SKIPS that row
+ rather than crashing or fabricating a status.
+ """
+ store = self._get_sdm_store()
+ if store is None:
+ return None
+ getter = getattr(store, "get_artifact", None)
+ if not callable(getter):
+ logger.warning(
+ "SDM store exposes no get_artifact(); lifecycle gate skipped "
+ "for artifact %s",
+ artifact_id,
+ )
+ return None
+ try:
+ artifact = getter(artifact_id)
+ except Exception: # noqa: BLE001 — degrade, never crash the facade
+ logger.warning(
+ "SDM artifact lookup failed for %s; lifecycle gate skipped",
+ artifact_id,
+ exc_info=True,
+ )
+ return None
+ if artifact is None:
+ return None
+ status = getattr(artifact, "status", None)
+ status = getattr(status, "value", status)
+ if isinstance(status, str) and status.strip():
+ return status.strip().lower()
+ return None
+
def _get_alpha_registry(self) -> Any:
"""Return the Alpha Zoo registry, tolerating a failed zoo load.
@@ -339,8 +422,20 @@ class StrategyDiscoveryFacade:
min_trades: int = 10,
cost_feasible: bool = True,
limit: int = 10,
+ include_stale: bool = False,
+ today: str | None = None,
) -> dict:
- """Evidence-gated query: only rows backed by stored evidence qualify."""
+ """Evidence-gated query: only rows backed by stored evidence qualify.
+
+ Gate order (plan D9): quality floor → min_trades → cost_feasible
+ (fail-closed null) → min_sharpe → decay gate (stale rows excluded
+ unless ``include_stale=True``) → SDM lifecycle gate (``sdm:*`` rows
+ whose artifact status is decayed/disabled are ALWAYS excluded from
+ recommendations). Decay is computed at read time from each row's
+ ``date_ranges`` window end (``evidence_age_days`` drives;
+ ``last_verified`` / ``staleness_days`` are reported, never gating).
+ ``today`` (ISO string) injects the clock for deterministic tests.
+ """
if regime is not None and regime not in REGIMES:
return _error(
f"unknown regime {regime!r}; valid regimes: {', '.join(REGIMES)}"
@@ -360,6 +455,12 @@ class StrategyDiscoveryFacade:
return _error("min_sharpe must be a finite number or None")
if not _is_int(limit) or limit <= 0:
return _error("limit must be a positive integer")
+ if not isinstance(include_stale, bool):
+ return _error("include_stale must be a boolean")
+ try:
+ today_date = _parse_today(today)
+ except ValueError as exc:
+ return _error(str(exc))
try:
store = self._get_evidence_store()
@@ -368,7 +469,6 @@ class StrategyDiscoveryFacade:
if store is not None:
try:
rows = store.get_rows(regime=regime)
- table_empty = store.row_count() == 0
except Exception: # noqa: BLE001 — degrade to no evidence
logger.warning(
"Evidence query failed; returning no evidence rows",
@@ -376,6 +476,16 @@ class StrategyDiscoveryFacade:
)
rows = []
table_empty = True
+ else:
+ try:
+ table_empty = store.row_count() == 0
+ except Exception: # noqa: BLE001 — keep the fetched rows
+ logger.warning(
+ "Evidence row count failed; inferring emptiness "
+ "from the fetched rows",
+ exc_info=True,
+ )
+ table_empty = len(rows) == 0
quality_floor = (
QUALITY_ORDER[min_evidence_quality]
@@ -400,9 +510,39 @@ class StrategyDiscoveryFacade:
return False
return True
- filtered = [row for row in rows if passes(row)]
+ below_floor = 0
+ decay_by_key: dict[tuple[str, str], dict[str, Any]] = {}
+ survivors: list[Any] = []
+ for row in rows:
+ if not passes(row):
+ below_floor += 1
+ continue
+ survivors.append(row)
+
+ stale_excluded = 0
+ post_decay: list[Any] = []
+ for row in survivors:
+ decay = _decay_fields(row, today_date)
+ decay_by_key[(row.strategy_id, row.regime)] = decay
+ if decay["decay_status"] == DECAY_STALE and not include_stale:
+ stale_excluded += 1
+ continue
+ post_decay.append(row)
+
+ lifecycle_excluded = 0
+ filtered: list[Any] = []
+ for row in post_decay:
+ if row.strategy_id.startswith("sdm:"):
+ status = self._sdm_artifact_status(row.strategy_id.split(":", 1)[1])
+ if status in _SDM_EXCLUDED_STATUSES:
+ lifecycle_excluded += 1
+ continue
+ filtered.append(row)
+
filtered.sort(
key=lambda row: (
+ decay_by_key[(row.strategy_id, row.regime)]["decay_status"]
+ == DECAY_STALE,
-QUALITY_ORDER.get(row.evidence_quality, 0),
-row.trades_in_regime,
row.strategy_id,
@@ -413,6 +553,12 @@ class StrategyDiscoveryFacade:
items: list[dict[str, Any]] = []
for row in filtered[:limit]:
data = dataclasses.asdict(row)
+ decay = decay_by_key[(row.strategy_id, row.regime)]
+ data["decay_status"] = decay["decay_status"]
+ data["evidence_age_days"] = decay["evidence_age_days"]
+ data["staleness_days"] = decay["staleness_days"]
+ if decay["_decay_warning"] is not None:
+ data["warnings"] = [*data["warnings"], decay["_decay_warning"]]
borderline = self._is_borderline(row)
data["borderline"] = borderline
if borderline:
@@ -429,26 +575,58 @@ class StrategyDiscoveryFacade:
"min_evidence_quality": min_evidence_quality,
"min_trades": min_trades,
"cost_feasible": cost_feasible,
+ "include_stale": include_stale,
},
+ "stale_excluded": stale_excluded,
+ "lifecycle_excluded": lifecycle_excluded,
"items": items,
}
if table_empty:
envelope["note"] = _EMPTY_EVIDENCE_NOTE
+ elif rows and not filtered:
+ # D11: non-empty table, zero rows pass — say WHY, so the
+ # agent can tell users what to fix instead of staring at an
+ # unexplained empty list.
+ envelope["note"] = (
+ "Evidence exists but every row was excluded by gates: "
+ f"{below_floor} below the quality/cost/trades/Sharpe "
+ f"floors, {stale_excluded} stale-excluded, "
+ f"{lifecycle_excluded} lifecycle-excluded. Use "
+ "include_stale=true to inspect stale rows; "
+ "lifecycle-excluded rows stay out of recommendations "
+ "(inspect them with get_strategy_evidence). Re-backtest "
+ "over a recent window and run refresh_strategy_evidence "
+ "to reinstate stale evidence."
+ )
return _json_safe(envelope)
except Exception: # noqa: BLE001 — never raise from the public facade
logger.exception("query_strategies failed")
return _error("query_strategies failed internally; see logs")
def get_strategy_evidence(
- self, strategy_id: str, regime: str | None = None
+ self, strategy_id: str, regime: str | None = None, today: str | None = None
) -> dict:
- """Full per-regime evidence breakdown for one strategy."""
+ """Full per-regime evidence breakdown for one strategy.
+
+ Inspection surface (plan D10): returns ALL rows unfiltered — decay
+ and lifecycle state are surfaced as fields/notes, never used to drop
+ rows here. Each row gains the read-time decay fields
+ (``decay_status`` / ``evidence_age_days`` / ``staleness_days``) plus
+ the decay warning; ``sdm:*`` strategies additionally carry a
+ ``lifecycle_note`` when the SDM artifact status is decayed/disabled
+ (lookup failure degrades to omitting the note, never a crash).
+ ``today`` (ISO string) injects the clock for deterministic tests.
+ """
if not isinstance(strategy_id, str) or not strategy_id.strip():
return _error("strategy_id is required (non-empty string)")
if regime is not None and regime not in REGIMES:
return _error(
f"unknown regime {regime!r}; valid regimes: {', '.join(REGIMES)}"
)
+ try:
+ today_date = _parse_today(today)
+ except ValueError as exc:
+ return _error(str(exc))
try:
rows = []
@@ -464,19 +642,45 @@ class StrategyDiscoveryFacade:
)
rows = []
+ lifecycle_note: str | None = None
+ if strategy_id.startswith("sdm:"):
+ status = self._sdm_artifact_status(strategy_id.split(":", 1)[1])
+ if status in _SDM_EXCLUDED_STATUSES:
+ lifecycle_note = (
+ f"{_SDM_LIFECYCLE_PREFIX} SDM artifact status is "
+ f"'{status}' — excluded from default recommendations "
+ "regardless of evidence freshness"
+ )
+
+ rendered: list[dict[str, Any]] = []
+ for row in rows:
+ data = dataclasses.asdict(row)
+ decay = _decay_fields(row, today_date)
+ data["decay_status"] = decay["decay_status"]
+ data["evidence_age_days"] = decay["evidence_age_days"]
+ data["staleness_days"] = decay["staleness_days"]
+ if decay["_decay_warning"] is not None:
+ data["warnings"] = [*data["warnings"], decay["_decay_warning"]]
+ if lifecycle_note is not None:
+ data["lifecycle_note"] = lifecycle_note
+ rendered.append(data)
+
envelope: dict[str, Any] = {
"status": "ok",
"strategy_id": strategy_id,
"regime": regime,
"found": bool(rows),
- "rows": [dataclasses.asdict(row) for row in rows],
+ "rows": rendered,
}
+ if lifecycle_note is not None:
+ envelope["lifecycle_note"] = lifecycle_note
if not rows:
scope = f" in regime {regime!r}" if regime is not None else ""
envelope["note"] = (
f"No evidence rows found for strategy_id {strategy_id!r}{scope}. "
- "Evidence rows are written only by the evidence harness "
- "library API over reproducible run artifacts."
+ "Evidence rows are written by `refresh_strategy_evidence` "
+ "(agent/MCP tool, or the CLI `vibe-trading strategy-evidence "
+ "refresh`) over reproducible run artifacts."
)
return _json_safe(envelope)
except Exception: # noqa: BLE001 — never raise from the public facade
diff --git a/agent/src/strategy_discovery/guard.py b/agent/src/strategy_discovery/guard.py
index d8dad3b51..45e71f9fe 100644
--- a/agent/src/strategy_discovery/guard.py
+++ b/agent/src/strategy_discovery/guard.py
@@ -1,11 +1,15 @@
-"""Registration guard for the strategy-discovery tool trio.
+"""Registration guard for the strategy-discovery tool set.
This module is the single source of truth for the Strategy Discovery routing
text injected into the agent's Task-Routing prompt section, and for checking
-whether the three read-only discovery tools are actually registered. It is
-fail-safe by design: when any tool is missing (or the registry object does
-not quack as expected) the routing block is omitted rather than advertising
-tools the agent cannot call — the exact failure mode of the rejected #896.
+whether the discovery tools (three read-only plus the refresh write tool)
+are actually registered. It is fail-safe by design: when any tool is missing
+(or the registry object does not quack as expected) the routing block is
+omitted rather than advertising tools the agent cannot call — the exact
+failure mode of the rejected #896. The routing block names all four tools,
+so the guard covers all four: advertising ``refresh_strategy_evidence``
+while only the three reads register would reintroduce the phantom-tool
+failure the guard exists to prevent.
The module must stay dependency-free: context builders import it eagerly, so
it may never pull in the facade, the store, or any heavy module.
@@ -15,18 +19,21 @@ from __future__ import annotations
from typing import Any
-#: The three read-only discovery tools. All three must be registered before
-#: any routing text is emitted (atomic advertisement).
+#: The discovery tools advertised by the routing block: the three read-only
+#: query tools plus the refresh write tool. All four must be registered
+#: before any routing text is emitted (atomic advertisement).
STRATEGY_DISCOVERY_TOOLS = (
"list_strategies",
"query_strategies",
"get_strategy_evidence",
+ "refresh_strategy_evidence",
)
ROUTING_BLOCK: str = """**Strategy Discovery** — user asks what strategies exist, which fit a market regime (bear/bull/structural), or what state registered strategies are in:
1. `list_strategies()` — unified catalog across Alpha Zoo + SDM store
2. `query_strategies(regime=...)` — evidence-gated per-regime results; report trades, date coverage, breakeven and warnings verbatim; NEVER present insufficient or marginal evidence as a recommendation
3. `get_strategy_evidence(strategy_id=...)` — full per-regime evidence breakdown
+4. `refresh_strategy_evidence(manifest_path=...)` — after re-backtesting a strategy, rebuild the disposable evidence cache from the new run artifacts so its evidence rows repopulate
Never recommend a strategy whose supporting regime evidence is missing or insufficient."""
diff --git a/agent/src/strategy_discovery/models.py b/agent/src/strategy_discovery/models.py
index db44f6d61..7964312fa 100644
--- a/agent/src/strategy_discovery/models.py
+++ b/agent/src/strategy_discovery/models.py
@@ -88,6 +88,34 @@ BORDERLINE_TRADE_BUFFER = 5
BORDERLINE_BREAKEVEN_BPS = 10.0
BORDERLINE_COVERAGE_BUFFER_DAYS = 365
+# ---------------------------------------------------------------------------
+# Evidence decay vocabulary and thresholds (Phase 2, #969)
+# ---------------------------------------------------------------------------
+
+#: Decay verdict vocabulary. Computed AT READ TIME from the evidence itself
+#: (window recency) — never persisted, never derived from model memory.
+DECAY_FRESH = "fresh"
+DECAY_AGING = "aging"
+DECAY_STALE = "stale"
+
+#: Evidence-window age (days since the latest ``date_ranges`` window ended)
+#: at or above which a row is flagged ``aging``. Justified against the
+#: documented quarterly re-backtest cadence: a window end more than ~90 days
+#: old means the strategy has missed at least one scheduled re-verification
+#: cycle, so the row carries an ``aged-evidence:`` warning — but it is NOT
+#: excluded, because one missed cycle is recoverable.
+DECAY_AGING_EVIDENCE_AGE_DAYS = 90
+
+#: Evidence-window age (days) at or above which a row is ``stale`` and is
+#: excluded from default recommendations. A window end more than ~180 days
+#: old means at least two consecutive quarterly re-backtest cycles were
+#: missed; the evidence can no longer vouch for the current market, so the
+#: row is refused by default (inspectable via ``include_stale``).
+#: Boundary semantics: ``age >= DECAY_STALE_EVIDENCE_AGE_DAYS`` ⇒ stale,
+#: elif ``age >= DECAY_AGING_EVIDENCE_AGE_DAYS`` ⇒ aging, else fresh — the
+#: exact threshold belongs to the STRICTER side (fail-closed, sergio12S).
+DECAY_STALE_EVIDENCE_AGE_DAYS = 180
+
# ---------------------------------------------------------------------------
# Dataclasses
# ---------------------------------------------------------------------------
@@ -237,6 +265,122 @@ def classify_quality(trades_in_regime: int, coverage_days: int) -> str:
return QUALITY_ADEQUATE
+def evidence_window_end(date_ranges) -> date | None:
+ """Last calendar day of the latest evidence window, or ``None``.
+
+ Each entry is parsed as ``"YYYY-MM to YYYY-MM"``; the window end is the
+ last day of the latest end month (month-granular ranges are end-anchored
+ to month-end, see :func:`_month_last_day_anchor`). Malformed entries
+ contribute nothing; ``None`` when nothing parses cleanly.
+ """
+ max_end: date | None = None
+
+ for entry in date_ranges:
+ if not isinstance(entry, str):
+ continue
+ pieces = [p for p in re.split(r"\s+to\s+", entry.strip(), flags=re.IGNORECASE)]
+ if len(pieces) != 2:
+ continue
+ end_start = _parse_month_first(pieces[1])
+ if end_start is None:
+ continue
+ end = _month_last_day_anchor(end_start)
+ if max_end is None or end > max_end:
+ max_end = end
+
+ return max_end
+
+
+def evidence_age_days(date_ranges, today: date) -> int | None:
+ """Age in days of the latest evidence window relative to ``today``.
+
+ ``today − evidence_window_end``, clamped to ``>= 0``: month-granular
+ ranges are end-anchored to month-end, so a window ending in the current
+ month can land in the future relative to ``today`` — a negative age is
+ reported as 0 (freshest possible), never as a negative number. Returns
+ ``None`` when no window end parses (callers fail closed on that).
+ """
+ window_end = evidence_window_end(date_ranges)
+ if window_end is None:
+ return None
+ return max(0, (today - window_end).days)
+
+
+def staleness_days(last_verified: str, today: date) -> int | None:
+ """Days since the row was last verified; ``None`` for malformed input.
+
+ Reported on every returned row but NEVER used for gating (plan D1):
+ ``staleness_days`` would let a scheduled refresh of unchanged artifacts
+ keep every row "fresh" forever — decay gating is driven by
+ :func:`evidence_age_days` instead.
+ """
+ if not isinstance(last_verified, str):
+ return None
+ text = last_verified.strip()
+ if not text:
+ return None
+ try:
+ verified = date.fromisoformat(text[:10])
+ except ValueError:
+ return None
+ return max(0, (today - verified).days)
+
+
+def classify_decay(
+ date_ranges,
+ today: date,
+ aging_days: int = DECAY_AGING_EVIDENCE_AGE_DAYS,
+ stale_days: int = DECAY_STALE_EVIDENCE_AGE_DAYS,
+) -> str:
+ """Decay verdict from the evidence window recency (pure, read-time).
+
+ Boundary semantics: ``age >= stale_days`` ⇒ ``stale``, elif
+ ``age >= aging_days`` ⇒ ``aging``, else ``fresh`` — an exact threshold
+ belongs to the stricter side. Unparseable/empty ``date_ranges`` classify
+ as ``stale`` fail-closed: evidence whose window cannot be dated cannot
+ vouch for anything (sergio12S discipline, #969).
+ """
+ age = evidence_age_days(date_ranges, today)
+ if age is None:
+ return DECAY_STALE
+ if age >= stale_days:
+ return DECAY_STALE
+ if age >= aging_days:
+ return DECAY_AGING
+ return DECAY_FRESH
+
+
+def decay_warning(decay_status: str, evidence_age_days: int | None) -> str | None:
+ """Stable decay warning for a row, or ``None`` for fresh rows.
+
+ Prefixes are fixed tokens (``stale-evidence:``, ``aged-evidence:``) with
+ the day count in the body so downstream tools can match them without
+ parsing prose. A stale verdict with an unknown age (unparseable window)
+ still warns — with the unparseable reason instead of a day count.
+ """
+ if decay_status == DECAY_STALE:
+ if evidence_age_days is None:
+ return (
+ "stale-evidence: evidence window end is missing or "
+ "unparseable, treated as stale fail-closed — re-backtest "
+ "over a recent window and refresh before relying on this row"
+ )
+ return (
+ f"stale-evidence: evidence window ended {evidence_age_days} days "
+ f"ago (>= {DECAY_STALE_EVIDENCE_AGE_DAYS}-day staleness "
+ "threshold) — excluded from default recommendations; re-backtest "
+ "over a recent window and refresh to reinstate"
+ )
+ if decay_status == DECAY_AGING:
+ return (
+ f"aged-evidence: evidence window ended {evidence_age_days} days "
+ f"ago (>= {DECAY_AGING_EVIDENCE_AGE_DAYS}-day aging threshold) — "
+ "still queryable, but verify with a fresh backtest before "
+ "relying on this row"
+ )
+ return None
+
+
def breakeven_fee_bps(
gross_return: float,
trades: int,
diff --git a/agent/src/strategy_discovery/run_artifacts.py b/agent/src/strategy_discovery/run_artifacts.py
index 656aec3d2..aacc28848 100644
--- a/agent/src/strategy_discovery/run_artifacts.py
+++ b/agent/src/strategy_discovery/run_artifacts.py
@@ -35,6 +35,7 @@ are skipped rather than guessed at.
from __future__ import annotations
import csv
+import json
import logging
import math
from collections.abc import Sequence
@@ -298,3 +299,101 @@ def read_equity_series(
values[2] for _, values in ordered if values[2] is not None and values[2] > 0
]
return dates, equities, benchmarks, exposures
+
+
+# ---------------------------------------------------------------------------
+# Hard-gate readers (Phase 2, #969): the backtest-diagnose hookup. Each
+# reader degrades to None on unusable input so the gate fails CLOSED — an
+# unverifiable run is never admitted as evidence.
+# ---------------------------------------------------------------------------
+
+
+def read_run_status(run_dir: str | Path) -> str | None:
+ """Run status from ``state.json``; ``None`` when missing or unreadable.
+
+ Runs carry no exit code in ``run_card.json``; the runtime writes
+ ``state.json`` (``{"status": "success"|"failed"|"cancelled", ...}``).
+ A missing state.json yields ``None`` — the ingestion gate treats that as
+ a failure, fail-closed.
+ """
+ path = Path(run_dir) / "state.json"
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ if not isinstance(payload, dict):
+ return None
+ status = payload.get("status")
+ if not isinstance(status, str) or not status.strip():
+ return None
+ return status.strip()
+
+
+def read_metrics_trade_count(run_dir: str | Path) -> int | None:
+ """``trade_count`` from the ``artifacts/metrics.csv`` header row.
+
+ The engine writes metrics.csv as one header row of metric names plus one
+ value row. Returns ``None`` when the file is missing, has no value row,
+ lacks a ``trade_count`` column, or the value is not a finite number —
+ the ingestion gate treats all of these as zero trades, fail-closed.
+ """
+ path = Path(run_dir) / "artifacts" / "metrics.csv"
+ try:
+ with path.open(newline="", encoding="utf-8-sig") as handle:
+ reader = csv.reader(handle)
+ header = next(reader, None)
+ if header is None:
+ return None
+ normalized = [name.strip().lower() for name in header]
+ if "trade_count" not in normalized:
+ return None
+ column = normalized.index("trade_count")
+ value_row = next(reader, None)
+ if value_row is None or column >= len(value_row):
+ return None
+ value = parse_finite_float(value_row[column])
+ if value is None:
+ return None
+ return int(value)
+ except _UNREADABLE_ERRORS as exc:
+ logger.warning(
+ "metrics.csv at %s is unreadable (%s); treated as unusable", path, exc
+ )
+ return None
+
+
+def equity_has_non_finite(run_dir: str | Path) -> bool | None:
+ """Scan ``artifacts/equity.csv`` equity column for NaN/Inf values.
+
+ Returns ``True`` when any data row's equity cell is missing, malformed,
+ or non-finite; ``False`` when every row carries a finite equity value.
+ Returns ``None`` when the verdict itself is unverifiable — file missing
+ or unreadable, no equity column, or no data rows — which the ingestion
+ gate treats as ``hard-gate:equity-empty`` (fail-closed).
+
+ Unlike :func:`read_equity_series`, which skips unusable rows, this
+ reader refuses to look past them: a NaN mid-curve means the equity
+ series is structurally broken and no partial-curve evidence may be
+ computed from it (Phase 1 silent-skip latent, #969).
+ """
+ path = Path(run_dir) / "artifacts" / "equity.csv"
+ try:
+ with path.open(newline="", encoding="utf-8-sig") as handle:
+ reader = csv.DictReader(handle)
+ fieldnames = reader.fieldnames or []
+ equity_column = _find_column(fieldnames, EQUITY_COLUMN_ALIASES)
+ if equity_column is None:
+ return None
+ saw_row = False
+ for record in reader:
+ saw_row = True
+ if parse_finite_float(record.get(equity_column)) is None:
+ return True
+ if not saw_row:
+ return None
+ return False
+ except _UNREADABLE_ERRORS as exc:
+ logger.warning(
+ "equity.csv at %s is unreadable (%s); treated as unusable", path, exc
+ )
+ return None
diff --git a/agent/src/tools/strategy_discovery_tool.py b/agent/src/tools/strategy_discovery_tool.py
index 460026c0e..5e530af59 100644
--- a/agent/src/tools/strategy_discovery_tool.py
+++ b/agent/src/tools/strategy_discovery_tool.py
@@ -1,23 +1,31 @@
-"""Strategy-discovery agent tools: evidence-gated read-only discovery surface.
-
-Three tools — ``list_strategies`` / ``query_strategies`` /
-``get_strategy_evidence`` — expose the Strategy Discovery facade over the
-Alpha Zoo registry and the SDM strategy store. The surface is evidence-gated:
-strategies carry computed per-regime evidence rows instead of boolean
-scenario tags, and anything below the evidence thresholds is flagged
-``insufficient`` / ``marginal`` rather than recommended.
-
-All three tools are read-only. The facade is constructed lazily inside each
-``execute()`` (never at import time), parameter types are coerced/validated
-defensively (bad input yields an error envelope, never a traceback), and any
-unexpected exception is wrapped into the standard ``{"status": "error", ...}``
-envelope.
+"""Strategy-discovery agent tools: evidence-gated discovery surface.
+
+Four tools — ``list_strategies`` / ``query_strategies`` /
+``get_strategy_evidence`` / ``refresh_strategy_evidence`` — expose the
+Strategy Discovery facade over the Alpha Zoo registry and the SDM strategy
+store. The surface is evidence-gated: strategies carry computed per-regime
+evidence rows instead of boolean scenario tags, and anything below the
+evidence thresholds is flagged ``insufficient`` / ``marginal`` rather than
+recommended.
+
+The first three tools are read-only. The fourth,
+``refresh_strategy_evidence``, is a WRITE tool with a deliberately narrow
+scope: it rebuilds ONLY the disposable facade-owned evidence cache from
+local backtest run artifacts (manifest-driven; plan D6/D7). It never writes
+to the Alpha Zoo or SDM sources of truth, and it uses no network and no
+credentials.
+
+The facade is constructed lazily inside each ``execute()`` (never at import
+time), parameter types are coerced/validated defensively (bad input yields
+an error envelope, never a traceback), and any unexpected exception is
+wrapped into the standard ``{"status": "error", ...}`` envelope.
"""
from __future__ import annotations
import json
import logging
+from pathlib import Path
from typing import Any
from src.agent.tools import BaseTool
@@ -230,6 +238,18 @@ class QueryStrategiesTool(BaseTool):
"cost-breakeven screen (default true)."
),
},
+ "include_stale": {
+ "type": "boolean",
+ "default": False,
+ "description": (
+ "Also keep rows whose evidence window is stale "
+ "(default false). By default stale rows fail closed out "
+ "of recommendations; set true to inspect them — they are "
+ "surfaced with their stale-evidence: warnings and sorted "
+ "after non-stale rows. Relaxes the staleness gate only, "
+ "never any other gate."
+ ),
+ },
"limit": {
"type": "integer",
"default": 10,
@@ -249,6 +269,9 @@ class QueryStrategiesTool(BaseTool):
cost_feasible = _coerce_bool(
kwargs.get("cost_feasible"), "cost_feasible", True
)
+ include_stale = _coerce_bool(
+ kwargs.get("include_stale"), "include_stale", False
+ )
limit = _coerce_int(kwargs.get("limit"), "limit", 10)
except ValueError as exc:
return _err(str(exc))
@@ -275,6 +298,7 @@ class QueryStrategiesTool(BaseTool):
min_trades=min_trades,
cost_feasible=cost_feasible,
limit=limit,
+ include_stale=include_stale,
)
except Exception:
# Full detail goes to the server logs only; the envelope must not
@@ -336,3 +360,349 @@ class GetStrategyEvidenceTool(BaseTool):
logger.exception("get_strategy_evidence failed")
return _err("get_strategy_evidence failed internally; see server logs")
return _envelope(result)
+
+
+# ---------------------------------------------------------------------------
+# refresh_strategy_evidence — manifest-driven cache rebuild (WRITE tool)
+# ---------------------------------------------------------------------------
+
+#: Stable skip-reason prefix for run dirs that resolve outside the allowed
+#: roots (plan D7). The offending path follows the colon so the envelope stays
+#: machine-readable and actionable at the same time.
+PATH_OUTSIDE_ALLOWED_ROOTS = "path-outside-allowed-roots"
+
+
+def _allowed_refresh_run_roots() -> list[Path]:
+ """Roots a refresh run_dir may live inside (plan D7).
+
+ The runtime runs root (``get_runtime_root()/"runs"``, honouring
+ ``VIBE_TRADING_HOME``) plus any operator-configured
+ ``VIBE_TRADING_ALLOWED_RUN_ROOTS`` entries. Environment access goes
+ through the config accessor (never ``os.environ`` directly — the
+ repository's AST CI gate forbids that here); any config-layer failure
+ degrades to the runtime runs root only.
+ """
+ roots: list[Path] = []
+ try:
+ from src.config.paths import get_runtime_root
+
+ runtime_runs = (get_runtime_root() / "runs").resolve()
+ roots.append(runtime_runs)
+ except Exception: # noqa: BLE001 — config layer optional for this package
+ logger.debug("runtime runs root unavailable", exc_info=True)
+ try:
+ from src.config.accessor import get_env_config
+
+ raw = get_env_config().api.vibe_trading_allowed_run_roots or ""
+ for item in raw.split(","):
+ item = item.strip()
+ if not item:
+ continue
+ resolved = Path(item).expanduser().resolve()
+ if resolved not in roots:
+ roots.append(resolved)
+ except Exception: # noqa: BLE001 — degrade to the runtime runs root only
+ logger.debug("allowed run roots config unavailable", exc_info=True)
+ return roots
+
+
+def _run_dir_allowed(run_dir: Path, roots: list[Path]) -> bool:
+ """Whether a resolved run dir lives inside one of the allowed roots."""
+ return any(run_dir.is_relative_to(root) for root in roots)
+
+
+def _manifest_path_allowed(resolved: Path) -> bool:
+ """Whether a resolved manifest path sits inside a trusted root.
+
+ Defense-in-depth (the run_dir entries inside are containment-checked
+ again by :func:`validate_refresh_entries` anyway): a manifest may live in
+ the runtime root (``get_runtime_root()``, honouring ``VIBE_TRADING_HOME``
+ — where the evidence cache itself lives) or in any allowed run root. Any
+ config-layer failure degrades to the runtime root only, never to "allow
+ everything".
+ """
+ roots: list[Path] = []
+ try:
+ from src.config.paths import get_runtime_root
+
+ roots.append(get_runtime_root().resolve())
+ except Exception: # noqa: BLE001 — config layer optional for this package
+ logger.debug("runtime root unavailable", exc_info=True)
+ roots.extend(_allowed_refresh_run_roots())
+ return any(resolved.is_relative_to(root) for root in roots)
+
+
+def load_manifest(path: str | Path) -> list:
+ """Read a refresh manifest file and return its run-spec entry list.
+
+ Two shapes are accepted (plan §4.6): a JSON object with a ``runs`` array
+ (``{"runs": [{strategy_id, run_dir, position_size?}, ...]}``) or a bare
+ JSON array of the same entries. The manifest itself must sit inside the
+ runtime root or an allowed run root (same containment discipline as the
+ run_dir entries it names).
+
+ Raises:
+ ValueError: With an operator-facing message when the path escapes the
+ allowed roots, the file is missing or unreadable, is not valid
+ JSON, or has the wrong shape. The agent tool and the CLI share
+ this helper so both surfaces report the same failure the same
+ way.
+ """
+ manifest_path = Path(str(path)).expanduser()
+ try:
+ resolved_manifest = manifest_path.resolve()
+ except (OSError, RuntimeError) as exc:
+ raise ValueError(
+ f"manifest path {manifest_path} could not be resolved: {exc}"
+ ) from exc
+ if not _manifest_path_allowed(resolved_manifest):
+ raise ValueError(
+ f"manifest path {manifest_path} is outside the runtime root and "
+ "the allowed run roots; place the manifest under one of them "
+ "(e.g. next to the runs it lists)"
+ )
+ try:
+ raw = manifest_path.read_text(encoding="utf-8")
+ except OSError as exc:
+ raise ValueError(
+ f"manifest file {manifest_path} is missing or unreadable "
+ f"({exc.strerror or 'I/O error'})"
+ ) from exc
+ try:
+ parsed = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise ValueError(
+ f"manifest file {manifest_path} is not valid JSON: {exc.msg} "
+ f"at line {exc.lineno} column {exc.colno}"
+ ) from exc
+ if isinstance(parsed, list):
+ return parsed
+ if isinstance(parsed, dict):
+ runs = parsed.get("runs")
+ if not isinstance(runs, list):
+ raise ValueError(
+ f"manifest file {manifest_path} must be a JSON object with a "
+ "'runs' array or a bare JSON array of run specs"
+ )
+ return runs
+ raise ValueError(
+ f"manifest file {manifest_path} must be a JSON object with a 'runs' "
+ "array or a bare JSON array of run specs"
+ )
+
+
+def validate_refresh_entries(
+ entries: list,
+) -> tuple[list[dict], list[dict]]:
+ """Split raw manifest entries into rebuild-ready specs and skip records.
+
+ Per-entry validation (plan §4.6/D7): the entry must be a mapping with a
+ non-empty ``strategy_id`` (capped at ``_MAX_STRING_PARAM_CHARS``) and a
+ non-empty ``run_dir`` that resolves (expanduser + resolve) inside the
+ allowed run roots. Offending entries are returned as
+ ``{"run_dir": ..., "reason": ...}`` skip records — the remaining entries
+ still process. An optional ``position_size`` is passed through untouched
+ (the harness validates it).
+
+ Returns:
+ ``(specs, skipped)`` — specs ready for ``rebuild_evidence`` and the
+ skip records for the envelope.
+ """
+ roots = _allowed_refresh_run_roots()
+ specs: list[dict] = []
+ skipped: list[dict] = []
+ for index, entry in enumerate(entries):
+ if not isinstance(entry, dict):
+ skipped.append(
+ {
+ "run_dir": None,
+ "reason": f"run spec at index {index} is not an object",
+ }
+ )
+ continue
+ run_dir_raw = entry.get("run_dir")
+ run_dir_label = (
+ str(run_dir_raw)
+ if isinstance(run_dir_raw, str) and run_dir_raw.strip()
+ else None
+ )
+ strategy_id = entry.get("strategy_id")
+ if not isinstance(strategy_id, str) or not strategy_id.strip():
+ skipped.append(
+ {
+ "run_dir": run_dir_label,
+ "reason": "missing strategy_id or run_dir",
+ }
+ )
+ continue
+ if len(strategy_id) > _MAX_STRING_PARAM_CHARS:
+ skipped.append(
+ {
+ "run_dir": run_dir_label,
+ "reason": (
+ f"strategy_id is too long ({len(strategy_id)} chars; "
+ f"max {_MAX_STRING_PARAM_CHARS})"
+ ),
+ }
+ )
+ continue
+ if run_dir_label is None:
+ skipped.append(
+ {"run_dir": None, "reason": "missing strategy_id or run_dir"}
+ )
+ continue
+ try:
+ resolved = Path(run_dir_label).expanduser().resolve()
+ except (OSError, RuntimeError) as exc:
+ skipped.append(
+ {
+ "run_dir": run_dir_label,
+ "reason": f"run_dir could not be resolved: {exc}",
+ }
+ )
+ continue
+ if not _run_dir_allowed(resolved, roots):
+ skipped.append(
+ {
+ "run_dir": run_dir_label,
+ "reason": f"{PATH_OUTSIDE_ALLOWED_ROOTS}:{run_dir_label}",
+ }
+ )
+ continue
+ spec: dict = {
+ "strategy_id": strategy_id.strip(),
+ "run_dir": str(resolved),
+ }
+ if "position_size" in entry:
+ spec["position_size"] = entry["position_size"]
+ specs.append(spec)
+ return specs, skipped
+
+
+def refresh_strategy_evidence_core(
+ *,
+ manifest_path: str | None = None,
+ runs: list | None = None,
+) -> dict:
+ """Shared refresh core for the agent tool and the CLI (one code path).
+
+ Validates the exactly-one-source rule, loads the manifest (or accepts
+ inline ``runs``), validates every entry (path containment included), and
+ rebuilds the DEFAULT evidence store — ``EvidenceStore()`` resolution:
+ env override → runtime root → ``~/.vibe-trading``; NEVER a CWD-relative
+ path.
+
+ Returns:
+ The strict envelope ``{status, runs, strategies, rows, skipped}``
+ where ``runs`` counts every supplied entry (processed + skipped) and
+ ``skipped`` merges entry-level skips with harness skips.
+
+ Raises:
+ ValueError: Operator-facing usage errors (exactly-one rule violated,
+ manifest missing/invalid/wrong shape, ``runs`` not an array).
+ """
+ if manifest_path is not None and runs is not None:
+ raise ValueError("provide exactly one of manifest_path or runs, not both")
+ if manifest_path is None and runs is None:
+ raise ValueError(
+ "refresh_strategy_evidence requires exactly one of manifest_path " "or runs"
+ )
+ if manifest_path is not None:
+ entries = load_manifest(manifest_path)
+ else:
+ if not isinstance(runs, list):
+ raise ValueError(
+ "runs must be an array of {strategy_id, run_dir, "
+ "position_size?} objects"
+ )
+ entries = runs
+
+ specs, skipped = validate_refresh_entries(entries)
+ if not specs:
+ # Nothing admissible to rebuild from. Do NOT call rebuild_evidence:
+ # an empty rebuild clears the store, and wiping the cache because
+ # every input entry was invalid would be a destructive surprise.
+ return {
+ "status": "ok",
+ "runs": len(entries),
+ "strategies": 0,
+ "rows": 0,
+ "skipped": skipped,
+ }
+
+ from src.strategy_discovery import EvidenceStore, rebuild_evidence
+
+ result = dict(rebuild_evidence(specs, EvidenceStore()))
+ result["runs"] = len(entries)
+ result["skipped"] = skipped + list(result.get("skipped", []))
+ return result
+
+
+class RefreshStrategyEvidenceTool(BaseTool):
+ """Rebuild the disposable strategy-evidence cache from run artifacts."""
+
+ name = "refresh_strategy_evidence"
+ description = (
+ "Rebuild the strategy-discovery evidence cache from real backtest "
+ "run artifacts. WRITE tool, disposable-cache scope only: it replaces "
+ "the facade-owned evidence cache (drop-and-rebuild by contract) and "
+ "never touches the Alpha Zoo or SDM sources of truth; no network, no "
+ "credentials. Provide EXACTLY ONE of manifest_path (JSON manifest: "
+ '{"runs": [{strategy_id, run_dir, position_size?}, ...]} — a bare '
+ "JSON array of the same entries is also accepted) or runs (inline "
+ "array of the same objects). Runs that fail the ingestion gates "
+ "(unhealthy artifacts, path outside the allowed run roots) are "
+ "skipped with machine-readable reasons while the rest still process."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "manifest_path": {
+ "type": "string",
+ "description": (
+ "Path to a JSON manifest file: an object with a 'runs' "
+ "array or a bare JSON array of "
+ "{strategy_id, run_dir, position_size?} entries. "
+ "Provide exactly one of manifest_path or runs."
+ ),
+ },
+ "runs": {
+ "type": "array",
+ "description": (
+ "Inline run specs: an array of "
+ "{strategy_id, run_dir, position_size?} objects. "
+ "Provide exactly one of manifest_path or runs."
+ ),
+ "items": {"type": "object"},
+ },
+ },
+ "required": [],
+ }
+ is_readonly = False
+ repeatable = True
+
+ def execute(self, **kwargs: Any) -> str:
+ try:
+ manifest_path = _coerce_opt_str(
+ kwargs.get("manifest_path"), "manifest_path"
+ )
+ except ValueError as exc:
+ return _err(str(exc))
+ runs = kwargs.get("runs")
+ if runs is not None and not isinstance(runs, list):
+ return _err(
+ "runs must be an array of {strategy_id, run_dir, "
+ "position_size?} objects"
+ )
+ try:
+ result = refresh_strategy_evidence_core(
+ manifest_path=manifest_path, runs=runs
+ )
+ except ValueError as exc:
+ return _err(str(exc))
+ except Exception:
+ # Full detail goes to the server logs only; the envelope must not
+ # echo raw exception text (it can leak internal paths).
+ logger.exception("refresh_strategy_evidence failed")
+ return _err("refresh_strategy_evidence failed internally; see server logs")
+ return _envelope(result)
diff --git a/agent/tests/test_cli_strategy_evidence.py b/agent/tests/test_cli_strategy_evidence.py
new file mode 100644
index 000000000..2f3e983be
--- /dev/null
+++ b/agent/tests/test_cli_strategy_evidence.py
@@ -0,0 +1,189 @@
+"""CLI contract for ``vibe-trading strategy-evidence refresh`` (#969 Phase 2).
+
+Driven through ``cli._legacy.main`` so the argparse wiring is exercised, not
+just the handler (same invocation style as ``test_playbooks_surface.py``).
+The refresh runs the SAME core as the agent tool
+(``refresh_strategy_evidence_core`` over the default ``EvidenceStore()``
+resolution) — no second spec-parsing code path.
+
+Fixture run dirs use the REAL engine artifact schema, reused from
+``test_strategy_discovery_harness``. The runtime root and the evidence DB are
+redirected into ``tmp_path`` via ``VIBE_TRADING_HOME`` and the
+``VIBE_TRADING_STRATEGY_DISCOVERY_DB_PATH`` override (the conftest resets the
+cached EnvConfig around every test).
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import List
+
+import pytest
+
+try:
+ from src.strategy_discovery.evidence_store import EvidenceStore
+
+ from tests.test_strategy_discovery_harness import (
+ ALL_TRADE_DAYS,
+ _write_run_fixture,
+ )
+
+ CLI_AVAILABLE = True
+except ImportError:
+ EvidenceStore = None
+ CLI_AVAILABLE = False
+
+requires_cli = pytest.mark.skipif(
+ not CLI_AVAILABLE,
+ reason="waiting on strategy-evidence refresh surface (issue #969 Phase 2)",
+)
+
+
+def _run_cli(argv: List[str]) -> int:
+ """Drive the real argparse dispatcher, returning its exit code."""
+ from cli import _legacy
+
+ return int(_legacy.main(argv))
+
+
+def _flat(text: str) -> str:
+ # Rich soft-wraps console output at the terminal width, and the wrap
+ # point is runner-dependent (CI hit mid-phrase wraps that broke literal
+ # substring assertions); collapse all whitespace before matching.
+ return " ".join(text.split())
+
+
+def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Redirect the runtime root and the evidence DB into tmp_path."""
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path))
+ monkeypatch.setenv(
+ "VIBE_TRADING_STRATEGY_DISCOVERY_DB_PATH", str(tmp_path / "evidence.db")
+ )
+ monkeypatch.delenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", raising=False)
+ return tmp_path
+
+
+def run_dir(home: Path) -> Path:
+ """A healthy fixture run inside the runtime runs root (allowed by D7)."""
+ runs_root = home / "runs"
+ runs_root.mkdir(parents=True, exist_ok=True)
+ return _write_run_fixture(runs_root)
+
+
+def _write_manifest(home: Path, payload) -> Path:
+ manifest = home / "manifest.json"
+ manifest.write_text(json.dumps(payload), encoding="utf-8")
+ return manifest
+
+
+@requires_cli
+class TestCliRefreshHappyPath:
+ def test_manifest_refresh_writes_rows_and_summarizes(
+ self, home: Path, run_dir: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ manifest = _write_manifest(
+ home, {"runs": [{"strategy_id": "sdm:cli", "run_dir": str(run_dir)}]}
+ )
+
+ code = _run_cli(["strategy-evidence", "refresh", "--manifest", str(manifest)])
+
+ out = capsys.readouterr().out
+ assert code == 0
+ assert "Refreshed strategy evidence" in _flat(out)
+ rows = EvidenceStore().get_rows()
+ assert rows, "the CLI refresh must write evidence rows to the default store"
+ assert {row.strategy_id for row in rows} == {"sdm:cli"}
+ assert sum(row.trades_in_regime for row in rows) == len(ALL_TRADE_DAYS)
+
+ def test_json_flag_emits_machine_readable_envelope(
+ self, home: Path, run_dir: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ manifest = _write_manifest(
+ home,
+ [{"strategy_id": "sdm:cli_json", "run_dir": str(run_dir)}],
+ )
+
+ code = _run_cli(
+ ["strategy-evidence", "refresh", "--manifest", str(manifest), "--json"]
+ )
+
+ payload = json.loads(capsys.readouterr().out)
+ assert code == 0
+ assert payload["status"] == "ok"
+ assert payload["runs"] == 1
+ assert payload["strategies"] == 1
+ assert payload["rows"] > 0
+ assert payload["skipped"] == []
+
+ def test_skipped_entries_are_reported(
+ self, home: Path, run_dir: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ outside = _write_run_fixture(home / "elsewhere")
+ manifest = _write_manifest(
+ home,
+ {
+ "runs": [
+ {"strategy_id": "sdm:outside", "run_dir": str(outside)},
+ {"strategy_id": "sdm:inside", "run_dir": str(run_dir)},
+ ]
+ },
+ )
+
+ code = _run_cli(
+ ["strategy-evidence", "refresh", "--manifest", str(manifest), "--json"]
+ )
+
+ payload = json.loads(capsys.readouterr().out)
+ assert code == 0
+ assert payload["strategies"] == 1
+ assert len(payload["skipped"]) == 1
+ assert payload["skipped"][0]["reason"].startswith("path-outside-allowed-roots:")
+
+
+@requires_cli
+class TestCliRefreshFailures:
+ def test_missing_manifest_file_fails_with_clear_error(
+ self, home: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ code = _run_cli(
+ [
+ "strategy-evidence",
+ "refresh",
+ "--manifest",
+ str(home / "absent.json"),
+ ]
+ )
+
+ out = capsys.readouterr().out
+ assert code != 0
+ assert "missing or unreadable" in _flat(out)
+
+ def test_malformed_manifest_json_fails_with_clear_error(
+ self, home: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ bad = home / "bad.json"
+ bad.write_text("{not json", encoding="utf-8")
+
+ code = _run_cli(["strategy-evidence", "refresh", "--manifest", str(bad)])
+
+ out = capsys.readouterr().out
+ assert code != 0
+ assert "not valid JSON" in _flat(out)
+
+ def test_wrong_manifest_shape_fails_with_clear_error(
+ self, home: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ manifest = _write_manifest(home, {"strategies": []})
+
+ code = _run_cli(["strategy-evidence", "refresh", "--manifest", str(manifest)])
+
+ out = capsys.readouterr().out
+ assert code != 0
+ assert "'runs' array" in _flat(out)
+
+ def test_missing_manifest_flag_is_a_usage_error(self, home: Path) -> None:
+ code = _run_cli(["strategy-evidence", "refresh"])
+ assert code != 0
diff --git a/agent/tests/test_mcp_new_tools.py b/agent/tests/test_mcp_new_tools.py
index 68a175e00..b8ca46ac8 100644
--- a/agent/tests/test_mcp_new_tools.py
+++ b/agent/tests/test_mcp_new_tools.py
@@ -32,8 +32,11 @@ MIRRORED_TOOL_NAMES = (
# Tools that mutate state (is_readonly is not True on the agent side) but are
# sanctioned sandbox/session writes: Alpha Bench reports, backtest runs, session
-# files, swarm launches, research-goal bookkeeping, and selecting which broker
-# profile subsequent READS use — not broker order flow.
+# files, swarm launches, research-goal bookkeeping, selecting which broker
+# profile subsequent READS use, and refresh_strategy_evidence (Phase 2, plan
+# D13: rebuilds ONLY the disposable facade-owned evidence cache from local run
+# artifacts — never Alpha Zoo/SDM sources of truth, no network, no credentials)
+# — not broker order flow.
#
# This snapshot is the regression gate: adding an MCP tool that mutates
# anything outside this list must fail the suite loudly.
@@ -42,6 +45,7 @@ KNOWN_MUTATING_MCP_TOOLS = frozenset(
"add_goal_evidence",
"alpha_bench",
"backtest",
+ "refresh_strategy_evidence",
"run_swarm",
"start_research_goal",
"trading_select_connection",
@@ -97,9 +101,9 @@ def test_mcp_tool_count_covers_the_mirrored_tools() -> None:
"""The MCP surface must not shrink below the documented 59 tools."""
tools = _mcp_tools()
- assert len(tools) >= 59, (
- f"Expected at least 59 MCP tools (55 pre-existing + 4 mirrored), found {len(tools)}."
- )
+ assert (
+ len(tools) >= 59
+ ), f"Expected at least 59 MCP tools (55 pre-existing + 4 mirrored), found {len(tools)}."
def test_mirrored_tool_names_match_the_agent_side_registry() -> None:
@@ -114,9 +118,9 @@ def test_mirrored_tool_names_match_the_agent_side_registry() -> None:
registry = build_registry()
for name in MIRRORED_TOOL_NAMES:
- assert registry.get(name) is not None, (
- f"{name} is exposed via MCP but absent from the agent registry"
- )
+ assert (
+ registry.get(name) is not None
+ ), f"{name} is exposed via MCP but absent from the agent registry"
# ---------------------------------------------------------------------------
@@ -181,7 +185,9 @@ def test_order_placing_tools_are_never_exposed_via_mcp() -> None:
order_tools = {TradingPlaceOrderTool.name, TradingCancelOrderTool.name}
leaked = order_tools & registered
- assert not leaked, f"Order-placing tools leaked onto the MCP surface: {sorted(leaked)}"
+ assert (
+ not leaked
+ ), f"Order-placing tools leaked onto the MCP surface: {sorted(leaked)}"
def test_no_unexpected_mutating_tool_is_exposed_via_mcp() -> None:
@@ -211,7 +217,9 @@ def test_no_unexpected_mutating_tool_is_exposed_via_mcp() -> None:
def test_every_mirrored_tool_is_readonly() -> None:
"""The tools added through the mirroring path are all read-only."""
for name, cls in _tool_classes().items():
- assert cls.is_readonly is True, f"{name} is not read-only and must not be mirrored"
+ assert (
+ cls.is_readonly is True
+ ), f"{name} is not read-only and must not be mirrored"
def test_register_mirrored_tool_refuses_a_non_readonly_class(caplog) -> None:
@@ -346,7 +354,10 @@ def test_one_broken_tool_module_costs_only_its_own_tool(monkeypatch, caplog) ->
def test_mirrored_call_params_filter() -> None:
"""The parameter filter keeps declared, non-null arguments only."""
mod = _import_mcp_server()
- schema = {"type": "object", "properties": {"a": {"type": "string"}, "b": {"type": "integer"}}}
+ schema = {
+ "type": "object",
+ "properties": {"a": {"type": "string"}, "b": {"type": "integer"}},
+ }
assert mod._mirrored_call_params(schema, {"a": "x", "b": 0, "c": 1, "d": None}) == {
"a": "x",
diff --git a/agent/tests/test_strategy_discovery_decay.py b/agent/tests/test_strategy_discovery_decay.py
new file mode 100644
index 000000000..0240fd385
--- /dev/null
+++ b/agent/tests/test_strategy_discovery_decay.py
@@ -0,0 +1,210 @@
+"""Phase 2 decay-classification contract for ``src.strategy_discovery.models``.
+
+Pure read-time decay (plan D1-D3): the verdict comes from the evidence row's
+own ``date_ranges`` window end relative to an injected clock — never from
+persisted state, never from the wall clock. Every assertion here injects a
+fixed ``today``; ``date.today()`` never appears in this file.
+
+Pinned semantics:
+
+* Boundary rule — exact threshold belongs to the STRICTER side:
+ ``age == DECAY_STALE_EVIDENCE_AGE_DAYS`` ⇒ stale,
+ ``age == DECAY_AGING_EVIDENCE_AGE_DAYS`` ⇒ aging.
+* Negative-age clamp — month-granular windows are end-anchored to month-end,
+ so a window ending in the current month can postdate ``today``; the age is
+ clamped to 0 (fresh), never negative.
+* Fail-closed — unparseable/empty ``date_ranges`` classify as stale.
+* ``staleness_days`` (from ``last_verified``) is report-only: malformed
+ input yields ``None`` and never influences the verdict.
+"""
+
+from __future__ import annotations
+
+from datetime import date, timedelta
+
+import pytest
+
+try:
+ from src.strategy_discovery import models as sd_models
+
+ DECAY_AVAILABLE = True
+except ImportError:
+ sd_models = None
+ DECAY_AVAILABLE = False
+
+requires_decay = pytest.mark.skipif(
+ not DECAY_AVAILABLE,
+ reason="waiting on src.strategy_discovery.models decay helpers (issue #969 Phase 2)",
+)
+
+#: Fixed window used for boundary math; end-anchored to 2026-01-31.
+JAN_2026 = ("2026-01 to 2026-01",)
+WINDOW_END = date(2026, 1, 31)
+
+
+@requires_decay
+class TestDecayConstants:
+ def test_vocabulary_exact(self) -> None:
+ assert sd_models.DECAY_FRESH == "fresh"
+ assert sd_models.DECAY_AGING == "aging"
+ assert sd_models.DECAY_STALE == "stale"
+
+ def test_thresholds_match_quarterly_cadence(self) -> None:
+ assert sd_models.DECAY_AGING_EVIDENCE_AGE_DAYS == 90
+ assert sd_models.DECAY_STALE_EVIDENCE_AGE_DAYS == 180
+
+
+@requires_decay
+class TestEvidenceWindowEnd:
+ def test_single_range_is_month_end_anchored(self) -> None:
+ assert sd_models.evidence_window_end(["2022-01 to 2022-12"]) == date(
+ 2022, 12, 31
+ )
+ assert sd_models.evidence_window_end(["2022-01 to 2022-02"]) == date(
+ 2022, 2, 28
+ )
+
+ def test_latest_end_wins_across_ranges(self) -> None:
+ assert sd_models.evidence_window_end(
+ ["2018-01 to 2018-12", "2022-01 to 2022-06", "2020-01 to 2020-03"]
+ ) == date(2022, 6, 30)
+
+ def test_malformed_entries_contribute_nothing(self) -> None:
+ assert sd_models.evidence_window_end(
+ ["garbage", "2022-01 to 2022-12", "2022-99 to nope", 123]
+ ) == date(2022, 12, 31)
+
+ def test_nothing_parseable_yields_none(self) -> None:
+ assert sd_models.evidence_window_end([]) is None
+ assert sd_models.evidence_window_end(["garbage"]) is None
+ assert sd_models.evidence_window_end(["2022-01 to nope"]) is None
+ assert sd_models.evidence_window_end([123, None]) is None
+
+
+@requires_decay
+class TestEvidenceAgeDays:
+ def test_age_is_days_since_window_end(self) -> None:
+ today = WINDOW_END + timedelta(days=10)
+ assert sd_models.evidence_age_days(JAN_2026, today) == 10
+
+ def test_negative_age_clamps_to_zero_for_current_month_window(self) -> None:
+ # Window ends 2026-08-31 (month-end anchor) but today is 2026-08-06:
+ # the raw difference is negative and must clamp to 0, not go below.
+ assert (
+ sd_models.evidence_age_days(("2026-08 to 2026-08",), date(2026, 8, 6)) == 0
+ )
+
+ def test_exact_threshold_ages(self) -> None:
+ stale_edge = WINDOW_END + timedelta(
+ days=sd_models.DECAY_STALE_EVIDENCE_AGE_DAYS
+ )
+ assert sd_models.evidence_age_days(JAN_2026, stale_edge) == 180
+ aging_edge = WINDOW_END + timedelta(
+ days=sd_models.DECAY_AGING_EVIDENCE_AGE_DAYS
+ )
+ assert sd_models.evidence_age_days(JAN_2026, aging_edge) == 90
+
+ def test_unparseable_ranges_yield_none(self) -> None:
+ assert sd_models.evidence_age_days((), date(2026, 8, 6)) is None
+ assert sd_models.evidence_age_days(("garbage",), date(2026, 8, 6)) is None
+
+
+@requires_decay
+class TestStalenessDays:
+ def test_days_since_last_verified(self) -> None:
+ assert sd_models.staleness_days("2026-08-01", date(2026, 8, 6)) == 5
+
+ def test_malformed_or_empty_yields_none(self) -> None:
+ assert sd_models.staleness_days("", date(2026, 8, 6)) is None
+ assert sd_models.staleness_days("not-a-date", date(2026, 8, 6)) is None
+ assert sd_models.staleness_days("2026-13-45", date(2026, 8, 6)) is None
+ assert sd_models.staleness_days(None, date(2026, 8, 6)) is None # type: ignore[arg-type]
+
+ def test_future_last_verified_clamps_to_zero(self) -> None:
+ assert sd_models.staleness_days("2026-08-31", date(2026, 8, 6)) == 0
+
+
+@requires_decay
+class TestClassifyDecay:
+ def test_exact_stale_threshold_is_stale(self) -> None:
+ today = WINDOW_END + timedelta(days=180)
+ assert sd_models.classify_decay(JAN_2026, today) == sd_models.DECAY_STALE
+
+ def test_one_day_inside_stale_threshold_is_aging(self) -> None:
+ today = WINDOW_END + timedelta(days=179)
+ assert sd_models.classify_decay(JAN_2026, today) == sd_models.DECAY_AGING
+
+ def test_exact_aging_threshold_is_aging(self) -> None:
+ today = WINDOW_END + timedelta(days=90)
+ assert sd_models.classify_decay(JAN_2026, today) == sd_models.DECAY_AGING
+
+ def test_one_day_inside_aging_threshold_is_fresh(self) -> None:
+ today = WINDOW_END + timedelta(days=89)
+ assert sd_models.classify_decay(JAN_2026, today) == sd_models.DECAY_FRESH
+
+ def test_future_window_is_fresh_via_clamp(self) -> None:
+ assert (
+ sd_models.classify_decay(("2026-08 to 2026-08",), date(2026, 8, 6))
+ == sd_models.DECAY_FRESH
+ )
+
+ def test_unparseable_ranges_are_stale_fail_closed(self) -> None:
+ today = date(2026, 8, 6)
+ assert sd_models.classify_decay((), today) == sd_models.DECAY_STALE
+ assert sd_models.classify_decay(("garbage",), today) == sd_models.DECAY_STALE
+ assert (
+ sd_models.classify_decay(("2026-01 to nope",), today)
+ == sd_models.DECAY_STALE
+ )
+
+ def test_thresholds_overridable_per_call(self) -> None:
+ ranges = ("2026-01 to 2026-01",)
+ assert (
+ sd_models.classify_decay(ranges, WINDOW_END + timedelta(days=15))
+ == sd_models.DECAY_FRESH
+ )
+ assert (
+ sd_models.classify_decay(
+ ranges,
+ WINDOW_END + timedelta(days=15),
+ aging_days=10,
+ stale_days=20,
+ )
+ == sd_models.DECAY_AGING
+ )
+ assert (
+ sd_models.classify_decay(
+ ranges,
+ WINDOW_END + timedelta(days=25),
+ aging_days=10,
+ stale_days=20,
+ )
+ == sd_models.DECAY_STALE
+ )
+
+
+@requires_decay
+class TestDecayWarning:
+ def test_stale_warning_carries_prefix_and_day_count(self) -> None:
+ warning = sd_models.decay_warning(sd_models.DECAY_STALE, 200)
+ assert warning is not None
+ assert warning.startswith("stale-evidence:")
+ assert "200" in warning
+ assert str(sd_models.DECAY_STALE_EVIDENCE_AGE_DAYS) in warning
+
+ def test_aged_warning_carries_prefix_and_day_count(self) -> None:
+ warning = sd_models.decay_warning(sd_models.DECAY_AGING, 120)
+ assert warning is not None
+ assert warning.startswith("aged-evidence:")
+ assert "120" in warning
+ assert str(sd_models.DECAY_AGING_EVIDENCE_AGE_DAYS) in warning
+
+ def test_fresh_and_unknown_statuses_yield_none(self) -> None:
+ assert sd_models.decay_warning(sd_models.DECAY_FRESH, 5) is None
+ assert sd_models.decay_warning("bogus", 5) is None
+
+ def test_stale_with_unknown_age_still_warns_fail_closed(self) -> None:
+ warning = sd_models.decay_warning(sd_models.DECAY_STALE, None)
+ assert warning is not None
+ assert warning.startswith("stale-evidence:")
+ assert "unparseable" in warning
diff --git a/agent/tests/test_strategy_discovery_facade.py b/agent/tests/test_strategy_discovery_facade.py
index 2589921b4..2dc82bfda 100644
--- a/agent/tests/test_strategy_discovery_facade.py
+++ b/agent/tests/test_strategy_discovery_facade.py
@@ -20,6 +20,8 @@ unknown-regime error carrying the valid regime list, honest empty evidence
from __future__ import annotations
+from datetime import date
+
import pytest
try:
@@ -39,6 +41,28 @@ requires_facade = pytest.mark.skipif(
reason="waiting on sibling A: src.strategy_discovery facade/models/evidence_store not landed yet (issue #969)",
)
+#: Fixed clock for queries over the default ``_row`` fixtures (window end
+#: 2022-12-31): keeps those rows fresh so the Phase 1 gate tests stay
+#: deterministic — decay is computed at read time (plan D1/D2), so these
+#: tests inject the clock instead of reading the wall clock.
+FRESH_TODAY = "2023-02-01"
+
+#: Fixed clock for the borderline fixtures: fresh for the edge row (window
+#: end 2026-02-28) and aging-but-not-stale for the solid row (window end
+#: 2024-12-31, age 152d at this date).
+BORDERLINE_TODAY = "2025-06-01"
+
+#: Fixed clock for the Phase 2 decay/lifecycle fixtures.
+QUERY_TODAY = "2026-08-06"
+QUERY_TODAY_DATE = date(2026, 8, 6)
+
+#: Window ends for the decay fixtures (month-end anchored), all relative to
+#: QUERY_TODAY_DATE: stale (2022-12-31), aging (2026-02-28), fresh
+#: (2026-06-30).
+STALE_RANGES = ("2019-01 to 2022-12",)
+AGING_RANGES = ("2020-01 to 2026-02",)
+FRESH_RANGES = ("2020-01 to 2026-06",)
+
EVIDENCE_FIELDS = (
"strategy_id",
"regime",
@@ -118,6 +142,12 @@ class FakeSdmStore:
self.list_calls.append(kwargs)
return list(self._artifacts)
+ def get_artifact(self, artifact_id):
+ for artifact in self._artifacts:
+ if artifact.id == artifact_id:
+ return artifact
+ return None
+
# ---------------------------------------------------------------------------
# Fixtures
@@ -297,14 +327,23 @@ class TestQueryStrategies:
facade, _ = self._seed_quality_ladder(tmp_path)
# Default floor is "adequate"; "marginal" admits adequate+marginal;
# "any" keeps every row including insufficient (QUALITY_ORDER based).
- assert {i["regime"] for i in facade.query_strategies()["items"]} == {
- "bear_market"
- }
+ assert {
+ i["regime"] for i in facade.query_strategies(today=FRESH_TODAY)["items"]
+ } == {"bear_market"}
assert {
i["regime"]
- for i in facade.query_strategies(min_evidence_quality="marginal")["items"]
+ for i in facade.query_strategies(
+ min_evidence_quality="marginal", today=FRESH_TODAY
+ )["items"]
} == {"bear_market", "bull_market"}
- assert len(facade.query_strategies(min_evidence_quality="any")["items"]) == 3
+ assert (
+ len(
+ facade.query_strategies(min_evidence_quality="any", today=FRESH_TODAY)[
+ "items"
+ ]
+ )
+ == 3
+ )
def test_min_trades_filter(self, tmp_path) -> None:
facade, _ = _make_facade(
@@ -315,7 +354,9 @@ class TestQueryStrategies:
_row("alpha_zoo:a1", "bull_market", trades_in_regime=12),
),
)
- payload = facade.query_strategies(min_trades=12, min_evidence_quality="any")
+ payload = facade.query_strategies(
+ min_trades=12, min_evidence_quality="any", today=FRESH_TODAY
+ )
assert {i["regime"] for i in payload["items"]} == {"bull_market"}
def test_cost_feasible_drops_cost_sensitive_rows(self, tmp_path) -> None:
@@ -337,9 +378,9 @@ class TestQueryStrategies:
),
),
)
- feasible = facade.query_strategies(cost_feasible=True)
+ feasible = facade.query_strategies(cost_feasible=True, today=FRESH_TODAY)
assert {i["regime"] for i in feasible["items"]} == {"bull_market"}
- everything = facade.query_strategies(cost_feasible=False)
+ everything = facade.query_strategies(cost_feasible=False, today=FRESH_TODAY)
assert {i["regime"] for i in everything["items"]} == {
"bear_market",
"bull_market",
@@ -368,11 +409,11 @@ class TestQueryStrategies:
),
),
)
- feasible = facade.query_strategies(cost_feasible=True)
+ feasible = facade.query_strategies(cost_feasible=True, today=FRESH_TODAY)
assert {i["regime"] for i in feasible["items"]} == {
"bull_market"
}, "a null-breakeven row must not pass the default cost screen"
- everything = facade.query_strategies(cost_feasible=False)
+ everything = facade.query_strategies(cost_feasible=False, today=FRESH_TODAY)
items = {i["regime"]: i for i in everything["items"]}
assert set(items) == {"bear_market", "bull_market"}
assert items["bear_market"]["breakeven_fee_bps"] is None
@@ -391,7 +432,7 @@ class TestQueryStrategies:
_row("alpha_zoo:a1", "structural", sharpe_in_regime=0.9),
),
)
- payload = facade.query_strategies(min_sharpe=0.5)
+ payload = facade.query_strategies(min_sharpe=0.5, today=FRESH_TODAY)
assert {i["regime"] for i in payload["items"]} == {"structural"}
def test_unknown_regime_error_lists_valid_regimes(self, tmp_path) -> None:
@@ -405,10 +446,10 @@ class TestQueryStrategies:
), f"valid regime {regime} missing from error: {message!r}"
def test_empty_store_returns_honest_note(self, tmp_path) -> None:
- # AC8: an empty evidence store yields an ok envelope with a note that
- # no evidence has been computed — never rows, never an error. The
- # note must point at the evidence harness LIBRARY API (the only write
- # path) and never suggest a user-runnable workflow/CLI exists.
+ # AC8 + D12: an empty evidence store yields an ok envelope with a note
+ # that no evidence has been computed — never rows, never an error. The
+ # note names `refresh_strategy_evidence` (agent/MCP tool + the
+ # `vibe-trading strategy-evidence refresh` CLI) as the population path.
facade, _ = _make_facade(tmp_path, alpha_ids=("a1",))
payload = facade.query_strategies(min_evidence_quality="any")
assert payload["status"] == "ok"
@@ -418,13 +459,13 @@ class TestQueryStrategies:
note
), "empty store query must carry a 'note' explaining no evidence exists"
assert isinstance(note, str)
- assert "rebuild_evidence" in note, (
- "the note must name the harness library API as the only write "
+ assert "refresh_strategy_evidence" in note, (
+ "the note must name refresh_strategy_evidence as the population "
f"path: {note!r}"
)
assert (
- "vibe-trading" not in note
- ), f"the note must not suggest a CLI command exists: {note!r}"
+ "vibe-trading strategy-evidence refresh" in note
+ ), f"the note must name the CLI population command: {note!r}"
def test_item_shape_carries_every_evidence_field_plus_borderline(
self, tmp_path
@@ -434,7 +475,7 @@ class TestQueryStrategies:
facade, _ = _make_facade(
tmp_path, alpha_ids=("a1",), rows=(_row("alpha_zoo:a1", "bear_market"),)
)
- payload = facade.query_strategies(regime="bear_market")
+ payload = facade.query_strategies(regime="bear_market", today=FRESH_TODAY)
item = payload["items"][0]
for field in EVIDENCE_FIELDS:
assert field in item, f"query item missing EvidenceRow field: {field}"
@@ -455,7 +496,7 @@ class TestQueryStrategies:
_row("sdm:s1", "bull_market"),
),
)
- payload = facade.query_strategies(min_evidence_quality="any")
+ payload = facade.query_strategies(min_evidence_quality="any", today=FRESH_TODAY)
assert payload["items"], "seeded store should produce items"
for item in payload["items"]:
stored = store.get_rows(
@@ -516,6 +557,7 @@ class TestBorderlineAdversarial:
min_evidence_quality="adequate",
min_trades=10,
cost_feasible=True,
+ today=BORDERLINE_TODAY,
)
assert payload["status"] == "ok"
items = {i["strategy_id"]: i for i in payload["items"]}
@@ -531,7 +573,7 @@ class TestBorderlineAdversarial:
def test_comfortable_row_is_not_borderline(self, tmp_path) -> None:
facade, _ = self._seed(tmp_path)
- payload = facade.query_strategies(regime="bear_market")
+ payload = facade.query_strategies(regime="bear_market", today=BORDERLINE_TODAY)
items = {i["strategy_id"]: i for i in payload["items"]}
solid = items["alpha_zoo:solid"]
assert solid["borderline"] is False
@@ -632,3 +674,500 @@ class TestDefaultAlphaRegistryResolution:
alpha_registry=injected,
)
assert facade._get_alpha_registry() is injected
+
+
+# ---------------------------------------------------------------------------
+# Phase 2 (D1/D2/D9): read-time decay gate on query_strategies
+# ---------------------------------------------------------------------------
+
+
+def _decay_row(strategy_id, regime, ranges, **overrides):
+ """A row that passes every Phase 1 gate (non-borderline by construction):
+ 20 trades, adequate quality, comfortable breakeven, long coverage — so
+ only the decay/lifecycle gates can move it. Overrides win."""
+ fields = dict(
+ trades_in_regime=20,
+ date_ranges=ranges,
+ breakeven_fee_bps=45.0,
+ cost_sensitive=False,
+ evidence_quality="adequate",
+ sharpe_in_regime=0.8,
+ )
+ fields.update(overrides)
+ return _row(strategy_id, regime, **fields)
+
+
+@requires_facade
+class TestDecayGate:
+ def test_stale_rows_excluded_by_default_with_count(self, tmp_path) -> None:
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=("fresh1", "stale1"),
+ rows=(
+ _decay_row("alpha_zoo:fresh1", "bear_market", FRESH_RANGES),
+ _decay_row("alpha_zoo:stale1", "bear_market", STALE_RANGES),
+ ),
+ )
+ payload = facade.query_strategies(today=QUERY_TODAY)
+ assert payload["status"] == "ok"
+ assert [i["strategy_id"] for i in payload["items"]] == ["alpha_zoo:fresh1"]
+ assert payload["stale_excluded"] == 1
+ assert payload["lifecycle_excluded"] == 0
+
+ def test_include_stale_surfaces_stale_rows_with_warning(self, tmp_path) -> None:
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=("fresh1", "stale1"),
+ rows=(
+ _decay_row("alpha_zoo:fresh1", "bear_market", FRESH_RANGES),
+ _decay_row("alpha_zoo:stale1", "bear_market", STALE_RANGES),
+ ),
+ )
+ payload = facade.query_strategies(include_stale=True, today=QUERY_TODAY)
+ items = {i["strategy_id"]: i for i in payload["items"]}
+ assert set(items) == {"alpha_zoo:fresh1", "alpha_zoo:stale1"}
+ assert payload["stale_excluded"] == 0
+
+ stale = items["alpha_zoo:stale1"]
+ assert stale["decay_status"] == sd_models.DECAY_STALE
+ expected_age = (QUERY_TODAY_DATE - date(2022, 12, 31)).days
+ assert stale["evidence_age_days"] == expected_age
+ assert any(
+ isinstance(w, str) and w.startswith("stale-evidence:")
+ for w in stale["warnings"]
+ ), f"stale-included row must carry the stale warning: {stale['warnings']!r}"
+
+ fresh = items["alpha_zoo:fresh1"]
+ assert fresh["decay_status"] == sd_models.DECAY_FRESH
+ assert fresh["evidence_age_days"] == (QUERY_TODAY_DATE - date(2026, 6, 30)).days
+ assert not any(
+ isinstance(w, str) and w.startswith(("stale-evidence:", "aged-evidence:"))
+ for w in fresh["warnings"]
+ )
+
+ def test_stale_included_rows_sort_after_non_stale(self, tmp_path) -> None:
+ # The stale row has MORE trades, so quality/trade-count ordering alone
+ # would rank it first — the stale-last sort key must override that.
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=("fresh1", "stale1"),
+ rows=(
+ _decay_row(
+ "alpha_zoo:fresh1", "bear_market", FRESH_RANGES, trades_in_regime=20
+ ),
+ _decay_row(
+ "alpha_zoo:stale1", "bear_market", STALE_RANGES, trades_in_regime=50
+ ),
+ ),
+ )
+ payload = facade.query_strategies(include_stale=True, today=QUERY_TODAY)
+ assert [i["strategy_id"] for i in payload["items"]] == [
+ "alpha_zoo:fresh1",
+ "alpha_zoo:stale1",
+ ]
+
+ def test_aging_rows_flagged_but_not_excluded(self, tmp_path) -> None:
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=("aging1", "fresh1"),
+ rows=(
+ _decay_row("alpha_zoo:aging1", "bear_market", AGING_RANGES),
+ _decay_row("alpha_zoo:fresh1", "bull_market", FRESH_RANGES),
+ ),
+ )
+ payload = facade.query_strategies(today=QUERY_TODAY)
+ items = {i["strategy_id"]: i for i in payload["items"]}
+ assert set(items) == {
+ "alpha_zoo:aging1",
+ "alpha_zoo:fresh1",
+ }, "aging rows are never excluded — they carry a warning instead"
+ assert payload["stale_excluded"] == 0
+
+ aging = items["alpha_zoo:aging1"]
+ assert aging["decay_status"] == sd_models.DECAY_AGING
+ assert aging["evidence_age_days"] == (QUERY_TODAY_DATE - date(2026, 2, 28)).days
+ assert any(
+ isinstance(w, str) and w.startswith("aged-evidence:")
+ for w in aging["warnings"]
+ ), f"aging row must carry the aged warning: {aging['warnings']!r}"
+
+ def test_staleness_days_reported_but_never_gating(self, tmp_path) -> None:
+ # D1: last_verified is report-only. This row was verified yesterday
+ # (staleness_days == 1) yet its window ended years ago — it is still
+ # stale, and the fresh row with an OLD last_verified is still fresh.
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=("fresh1", "stale1"),
+ rows=(
+ _decay_row(
+ "alpha_zoo:fresh1",
+ "bear_market",
+ FRESH_RANGES,
+ last_verified="2026-01-01",
+ ),
+ _decay_row(
+ "alpha_zoo:stale1",
+ "bull_market",
+ STALE_RANGES,
+ last_verified="2026-08-05",
+ ),
+ ),
+ )
+ payload = facade.query_strategies(include_stale=True, today=QUERY_TODAY)
+ items = {i["strategy_id"]: i for i in payload["items"]}
+ assert (
+ items["alpha_zoo:fresh1"]["staleness_days"]
+ == (QUERY_TODAY_DATE - date(2026, 1, 1)).days
+ )
+ assert items["alpha_zoo:fresh1"]["decay_status"] == sd_models.DECAY_FRESH
+ assert items["alpha_zoo:stale1"]["staleness_days"] == 1
+ assert items["alpha_zoo:stale1"]["decay_status"] == sd_models.DECAY_STALE
+
+ def test_injected_today_changes_the_verdict_deterministically(
+ self, tmp_path
+ ) -> None:
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=("a1",),
+ rows=(_decay_row("alpha_zoo:a1", "bear_market", STALE_RANGES),),
+ )
+ near = facade.query_strategies(today="2023-01-15")
+ assert [i["strategy_id"] for i in near["items"]] == ["alpha_zoo:a1"]
+ assert near["items"][0]["decay_status"] == sd_models.DECAY_FRESH
+ assert near["stale_excluded"] == 0
+
+ far = facade.query_strategies(today=QUERY_TODAY)
+ assert far["items"] == []
+ assert far["stale_excluded"] == 1
+
+ def test_include_stale_must_be_boolean(self, tmp_path) -> None:
+ facade, _ = _make_facade(tmp_path, alpha_ids=("a1",))
+ payload = facade.query_strategies(include_stale="yes")
+ assert payload["status"] == "error"
+ assert "include_stale" in payload.get("error", "")
+
+ def test_unparseable_today_is_error_envelope(self, tmp_path) -> None:
+ facade, _ = _make_facade(tmp_path, alpha_ids=("a1",))
+ for bad in ("not-a-date", "2026-13-45", 20260806):
+ payload = facade.query_strategies(today=bad)
+ assert payload["status"] == "error", f"today={bad!r} must be rejected"
+ assert payload.get("error")
+
+
+# ---------------------------------------------------------------------------
+# Phase 2 (D8/D9): SDM lifecycle gate
+# ---------------------------------------------------------------------------
+
+
+class ExplodingSdmStore:
+ """SDM store whose artifact lookup always fails — the lifecycle gate must
+ degrade (skip), never crash the query."""
+
+ def list_artifacts(self, **kwargs):
+ return []
+
+ def get_artifact(self, artifact_id):
+ raise RuntimeError("sdm store exploded")
+
+
+@requires_facade
+class TestLifecycleGate:
+ def _seed_sdm_row(self, tmp_path, status):
+ return _make_facade(
+ tmp_path,
+ alpha_ids=(),
+ artifacts=[FakeArtifact("s1", status=status)],
+ rows=(_decay_row("sdm:s1", "bear_market", FRESH_RANGES),),
+ )
+
+ def test_decayed_sdm_artifact_excluded_from_recommendations(self, tmp_path) -> None:
+ facade, _ = self._seed_sdm_row(tmp_path, "decayed")
+ payload = facade.query_strategies(today=QUERY_TODAY)
+ assert payload["items"] == []
+ assert payload["lifecycle_excluded"] == 1
+ assert payload["stale_excluded"] == 0
+ # include_stale does NOT rescue lifecycle-excluded rows.
+ still_out = facade.query_strategies(include_stale=True, today=QUERY_TODAY)
+ assert still_out["items"] == []
+ assert still_out["lifecycle_excluded"] == 1
+
+ def test_disabled_sdm_artifact_excluded(self, tmp_path) -> None:
+ facade, _ = self._seed_sdm_row(tmp_path, "disabled")
+ payload = facade.query_strategies(today=QUERY_TODAY)
+ assert payload["items"] == []
+ assert payload["lifecycle_excluded"] == 1
+
+ def test_active_sdm_artifact_not_excluded(self, tmp_path) -> None:
+ facade, _ = self._seed_sdm_row(tmp_path, "active")
+ payload = facade.query_strategies(today=QUERY_TODAY)
+ assert [i["strategy_id"] for i in payload["items"]] == ["sdm:s1"]
+ assert payload["lifecycle_excluded"] == 0
+
+ def test_sdm_lookup_failure_degrades_to_no_gate(self, tmp_path) -> None:
+ facade = StrategyDiscoveryFacade(
+ evidence_store=_make_store(tmp_path),
+ sdm_store=ExplodingSdmStore(),
+ alpha_registry=FakeAlphaRegistry([]),
+ )
+ facade._get_evidence_store().upsert_rows(
+ [_decay_row("sdm:s1", "bear_market", FRESH_RANGES)]
+ )
+ payload = facade.query_strategies(today=QUERY_TODAY)
+ assert payload["status"] == "ok", "lookup failure must never crash a query"
+ assert [i["strategy_id"] for i in payload["items"]] == ["sdm:s1"]
+ assert payload["lifecycle_excluded"] == 0
+
+ def test_unknown_sdm_artifact_degrades_to_no_gate(self, tmp_path) -> None:
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=(),
+ artifacts=[FakeArtifact("other", status="decayed")],
+ rows=(_decay_row("sdm:s1", "bear_market", FRESH_RANGES),),
+ )
+ payload = facade.query_strategies(today=QUERY_TODAY)
+ assert [i["strategy_id"] for i in payload["items"]] == ["sdm:s1"]
+ assert payload["lifecycle_excluded"] == 0
+
+ def test_stale_and_lifecycle_counts_together(self, tmp_path) -> None:
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=("fresh1", "stale1"),
+ artifacts=[FakeArtifact("s1", status="decayed")],
+ rows=(
+ _decay_row("alpha_zoo:fresh1", "bear_market", FRESH_RANGES),
+ _decay_row("alpha_zoo:stale1", "bull_market", STALE_RANGES),
+ _decay_row("sdm:s1", "structural", FRESH_RANGES),
+ ),
+ )
+ payload = facade.query_strategies(today=QUERY_TODAY)
+ assert [i["strategy_id"] for i in payload["items"]] == ["alpha_zoo:fresh1"]
+ assert payload["stale_excluded"] == 1
+ assert payload["lifecycle_excluded"] == 1
+
+
+# ---------------------------------------------------------------------------
+# Phase 2 (D11): empty vs all-excluded notes
+# ---------------------------------------------------------------------------
+
+
+@requires_facade
+class TestAllExcludedNote:
+ def test_all_excluded_note_reports_gate_breakdown(self, tmp_path) -> None:
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=("stale1", "low1"),
+ rows=(
+ _decay_row("alpha_zoo:stale1", "bear_market", STALE_RANGES),
+ _decay_row(
+ "alpha_zoo:low1",
+ "bull_market",
+ FRESH_RANGES,
+ evidence_quality="insufficient",
+ ),
+ ),
+ )
+ payload = facade.query_strategies(today=QUERY_TODAY)
+ assert payload["items"] == []
+ note = payload.get("note", "")
+ assert note, "non-empty-but-all-excluded must carry a breakdown note"
+ assert "1 below the quality/cost/trades/Sharpe floors" in note
+ assert "1 stale-excluded" in note
+ assert "0 lifecycle-excluded" in note
+
+ def test_all_excluded_note_differs_from_empty_note(self, tmp_path) -> None:
+ empty_facade, _ = _make_facade(tmp_path, alpha_ids=("a1",))
+ empty_note = empty_facade.query_strategies(today=QUERY_TODAY).get("note", "")
+
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=("stale1",),
+ rows=(_decay_row("alpha_zoo:stale1", "bear_market", STALE_RANGES),),
+ )
+ excluded_note = facade.query_strategies(today=QUERY_TODAY).get("note", "")
+
+ assert empty_note and excluded_note
+ assert empty_note != excluded_note
+ assert "refresh_strategy_evidence" in empty_note
+ assert "excluded by gates" in excluded_note
+
+ def test_passing_query_carries_no_note(self, tmp_path) -> None:
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=("fresh1",),
+ rows=(_decay_row("alpha_zoo:fresh1", "bear_market", FRESH_RANGES),),
+ )
+ payload = facade.query_strategies(today=QUERY_TODAY)
+ assert payload["items"]
+ assert "note" not in payload
+
+
+# ---------------------------------------------------------------------------
+# Phase 2 (D10): get_strategy_evidence inspection surface
+# ---------------------------------------------------------------------------
+
+
+@requires_facade
+class TestGetStrategyEvidenceDecay:
+ def test_rows_carry_decay_fields(self, tmp_path) -> None:
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=("aging1",),
+ rows=(_decay_row("alpha_zoo:aging1", "bear_market", AGING_RANGES),),
+ )
+ payload = facade.get_strategy_evidence("alpha_zoo:aging1", today=QUERY_TODAY)
+ assert payload["found"] is True
+ row = payload["rows"][0]
+ assert row["decay_status"] == sd_models.DECAY_AGING
+ assert row["evidence_age_days"] == (QUERY_TODAY_DATE - date(2026, 2, 28)).days
+ assert row["staleness_days"] == (QUERY_TODAY_DATE - date(2026, 8, 1)).days
+ assert any(
+ isinstance(w, str) and w.startswith("aged-evidence:")
+ for w in row["warnings"]
+ )
+
+ def test_stale_rows_returned_unfiltered(self, tmp_path) -> None:
+ # D10: the inspection surface never filters — a stale row is returned
+ # with its stale warning, not dropped.
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=("stale1",),
+ rows=(_decay_row("alpha_zoo:stale1", "bear_market", STALE_RANGES),),
+ )
+ payload = facade.get_strategy_evidence("alpha_zoo:stale1", today=QUERY_TODAY)
+ assert payload["found"] is True
+ assert len(payload["rows"]) == 1
+ row = payload["rows"][0]
+ assert row["decay_status"] == sd_models.DECAY_STALE
+ assert any(
+ isinstance(w, str) and w.startswith("stale-evidence:")
+ for w in row["warnings"]
+ )
+
+ def test_sdm_lifecycle_note_for_decayed_artifact(self, tmp_path) -> None:
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=(),
+ artifacts=[FakeArtifact("s1", status="decayed")],
+ rows=(_decay_row("sdm:s1", "bear_market", FRESH_RANGES),),
+ )
+ payload = facade.get_strategy_evidence("sdm:s1", today=QUERY_TODAY)
+ note = payload.get("lifecycle_note", "")
+ assert note.startswith("sdm-lifecycle:"), f"got {note!r}"
+ assert "'decayed'" in note
+ assert payload["rows"][0].get("lifecycle_note") == note
+
+ def test_alpha_rows_carry_no_lifecycle_note(self, tmp_path) -> None:
+ facade, _ = _make_facade(
+ tmp_path,
+ alpha_ids=("a1",),
+ rows=(_decay_row("alpha_zoo:a1", "bear_market", FRESH_RANGES),),
+ )
+ payload = facade.get_strategy_evidence("alpha_zoo:a1", today=QUERY_TODAY)
+ assert "lifecycle_note" not in payload
+ assert "lifecycle_note" not in payload["rows"][0]
+
+ def test_sdm_lookup_failure_omits_note_without_crash(self, tmp_path) -> None:
+ facade = StrategyDiscoveryFacade(
+ evidence_store=_make_store(tmp_path),
+ sdm_store=ExplodingSdmStore(),
+ alpha_registry=FakeAlphaRegistry([]),
+ )
+ facade._get_evidence_store().upsert_rows(
+ [_decay_row("sdm:s1", "bear_market", FRESH_RANGES)]
+ )
+ payload = facade.get_strategy_evidence("sdm:s1", today=QUERY_TODAY)
+ assert payload["status"] == "ok"
+ assert payload["found"] is True
+ assert "lifecycle_note" not in payload
+
+ def test_unparseable_today_is_error_envelope(self, tmp_path) -> None:
+ facade, _ = _make_facade(tmp_path, alpha_ids=("a1",))
+ payload = facade.get_strategy_evidence("alpha_zoo:a1", today="bogus")
+ assert payload["status"] == "error"
+ assert payload.get("error")
+
+
+# ---------------------------------------------------------------------------
+# Phase 2 adversarial composition (sergio12S): just inside the staleness
+# boundary AND just inside the trades band at the same time
+# ---------------------------------------------------------------------------
+
+
+@requires_facade
+class TestDecayBorderlineComposition:
+ """One row, two threshold edges at once:
+
+ * trades_in_regime=11 — just inside the borderline trade band
+ (MIN_TRADES=10 <= 11 < 10+BORDERLINE_TRADE_BUFFER=15);
+ * window end 2026-01-31 with injected clocks 2026-07-29 (age 179, just
+ inside the stale boundary ⇒ aging) and 2026-07-30 (age exactly 180 ⇒
+ stale, the stricter side — fail-closed).
+ """
+
+ COMPOSITION_RANGES = ("2020-01 to 2026-01",)
+ INSIDE_TODAY = "2026-07-29"
+ BOUNDARY_TODAY = "2026-07-30"
+
+ def _seed(self, tmp_path):
+ return _make_facade(
+ tmp_path,
+ alpha_ids=("edge",),
+ rows=(
+ _row(
+ "alpha_zoo:edge",
+ "bear_market",
+ trades_in_regime=11,
+ date_ranges=self.COMPOSITION_RANGES,
+ breakeven_fee_bps=45.0,
+ cost_sensitive=False,
+ evidence_quality="adequate",
+ sharpe_in_regime=0.8,
+ ),
+ ),
+ )
+
+ def test_fixture_ages_are_exact(self) -> None:
+ end = date(2026, 1, 31)
+ assert (date(2026, 7, 29) - end).days == 179
+ assert (date(2026, 7, 30) - end).days == 180
+ assert sd_models.coverage_days_from_ranges(self.COMPOSITION_RANGES) >= (
+ sd_models.MIN_COVERAGE_DAYS + sd_models.BORDERLINE_COVERAGE_BUFFER_DAYS
+ ), "coverage must NOT be the borderline axis — trades must be"
+
+ def test_just_inside_boundary_is_aging_with_both_warnings(self, tmp_path) -> None:
+ facade, _ = self._seed(tmp_path)
+ payload = facade.query_strategies(today=self.INSIDE_TODAY)
+ assert payload["stale_excluded"] == 0
+ items = {i["strategy_id"]: i for i in payload["items"]}
+ assert "alpha_zoo:edge" in items, "age 179 is aging, not stale — keep it"
+ edge = items["alpha_zoo:edge"]
+ assert edge["decay_status"] == sd_models.DECAY_AGING
+ assert edge["evidence_age_days"] == 179
+ assert edge["borderline"] is True
+ prefixes = {
+ w.split(":", 1)[0] + ":" for w in edge["warnings"] if isinstance(w, str)
+ }
+ assert "aged-evidence:" in prefixes
+ assert "borderline-evidence:" in prefixes
+
+ def test_exact_boundary_is_stale_fail_closed(self, tmp_path) -> None:
+ facade, _ = self._seed(tmp_path)
+ payload = facade.query_strategies(today=self.BOUNDARY_TODAY)
+ assert payload["items"] == [], (
+ "age exactly 180 belongs to the STRICTER side — the row must be "
+ "excluded from default recommendations (fail-closed)"
+ )
+ assert payload["stale_excluded"] == 1
+
+ revealed = facade.query_strategies(
+ include_stale=True, today=self.BOUNDARY_TODAY
+ )
+ items = {i["strategy_id"]: i for i in revealed["items"]}
+ edge = items["alpha_zoo:edge"]
+ assert edge["decay_status"] == sd_models.DECAY_STALE
+ assert edge["evidence_age_days"] == 180
+ prefixes = {
+ w.split(":", 1)[0] + ":" for w in edge["warnings"] if isinstance(w, str)
+ }
+ assert "stale-evidence:" in prefixes
+ assert "borderline-evidence:" in prefixes
diff --git a/agent/tests/test_strategy_discovery_guard.py b/agent/tests/test_strategy_discovery_guard.py
index 5491188bd..ae3ac5b44 100644
--- a/agent/tests/test_strategy_discovery_guard.py
+++ b/agent/tests/test_strategy_discovery_guard.py
@@ -12,6 +12,8 @@ Registries here are real ``ToolRegistry`` instances populated with minimal
from __future__ import annotations
import json
+import re
+from pathlib import Path
import pytest
@@ -30,7 +32,12 @@ requires_guard = pytest.mark.skipif(
reason="waiting on sibling A: src.strategy_discovery.guard not landed yet (issue #969)",
)
-EXPECTED_TOOLS = ("list_strategies", "query_strategies", "get_strategy_evidence")
+EXPECTED_TOOLS = (
+ "list_strategies",
+ "query_strategies",
+ "get_strategy_evidence",
+ "refresh_strategy_evidence",
+)
class _StubTool(BaseTool):
@@ -108,3 +115,56 @@ class TestRoutingBlock:
# The contract pins "never raises on garbage registry (object())".
assert sd_guard.routing_block(object()) == ""
assert sd_guard.routing_block(None) == ""
+
+
+SKILL_MD_PATH = (
+ Path(__file__).resolve().parents[1]
+ / "src"
+ / "skills"
+ / "strategy-discovery"
+ / "SKILL.md"
+)
+
+EXPECTED_FOUR_TOOLS = EXPECTED_TOOLS
+
+# Underscore-form identifiers only. Tool names on this surface are always
+# snake_case, so CLI invocations, file names, env vars, and hyphenated or
+# colon-suffixed skip tokens never enter the candidate set. Parameter names
+# (``strategy_id``, ``manifest_path``, ...) do pass the filter — that is
+# harmless, because the assertion is on the intersection with registered tool
+# names, and parameters are not registered tools.
+_TOOL_TOKEN_RE = re.compile(r"`([a-z]+(?:_[a-z0-9]+)+)`")
+
+
+@requires_guard
+class TestSkillMdNamesOnlyRegisteredTools:
+ """D14 / #894 phantom-guard extension.
+
+ The documented periodic recipe names tools the agent must actually be able
+ to call. Intersecting the skill's backticked snake_case tokens with the
+ real auto-discovered registry means a rename on either side — the doc or
+ the tool code — fails CI, instead of resurfacing #894 as a skill that
+ advertises a tool the registry never registered.
+ """
+
+ def test_intersection_is_exactly_the_four_tools(self) -> None:
+ from src.tools import build_registry
+
+ text = SKILL_MD_PATH.read_text(encoding="utf-8")
+ tokens = set(_TOOL_TOKEN_RE.findall(text))
+ registered = set(build_registry().tool_names)
+
+ intersection = tokens & registered
+ assert intersection == set(EXPECTED_FOUR_TOOLS), (
+ "strategy-discovery SKILL.md and the tool registry disagree: "
+ f"intersection={sorted(intersection)}, "
+ f"expected={sorted(EXPECTED_FOUR_TOOLS)}"
+ )
+
+ def test_routing_block_names_the_refresh_tool(self) -> None:
+ # The routing block advertises the refresh step, and the guard now
+ # requires the refresh tool itself to be registered before any block
+ # is emitted — advertising it on the strength of the three read tools
+ # alone would reintroduce the phantom-tool failure of #896.
+ assert "refresh_strategy_evidence" in sd_guard.ROUTING_BLOCK
+ assert "refresh_strategy_evidence" in sd_guard.STRATEGY_DISCOVERY_TOOLS
diff --git a/agent/tests/test_strategy_discovery_hard_gates.py b/agent/tests/test_strategy_discovery_hard_gates.py
new file mode 100644
index 000000000..a7429b101
--- /dev/null
+++ b/agent/tests/test_strategy_discovery_hard_gates.py
@@ -0,0 +1,418 @@
+"""Phase 2 hard-gate contract for evidence ingestion (#969, plan D4/D5).
+
+The backtest-diagnose Hard-Gate Checklist IS the evidence ingestion gate:
+five stable ``hard-gate:*`` tokens, checked in order, refusing unhealthy
+runs BEFORE any per-regime computation. Fixture run dirs are written in the
+REAL engine artifact schema, reusing the builders from
+``test_strategy_discovery_harness`` (entry+exit trade row pairs with the
+zero-pnl marker, ``timestamp``-indexed equity.csv with ``benchmark_equity``,
+runtime ``state.json`` with a ``status`` field, engine ``metrics.csv``
+header row including ``trade_count``) — no second fixture schema.
+
+Also pinned here:
+
+* NaN mid-equity skips the run ENTIRELY — no partial-curve evidence rows
+ (regression for the Phase 1 silent-skip latent, where ``read_equity_series``
+ dropped the NaN bars and computed over the survivors).
+* Atomic rebuild (D5): a mid-compute crash leaves previously stored rows
+ intact because ``replace_rows`` never ran (the old clear-then-upsert path
+ would have left the store empty).
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+try:
+ from src.strategy_discovery import evidence_harness as sd_harness
+ from src.strategy_discovery import run_artifacts as sd_artifacts
+ from src.strategy_discovery.evidence_store import EvidenceStore
+ from src.strategy_discovery.models import EvidenceRow
+
+ from tests.test_strategy_discovery_harness import (
+ ALL_TRADE_DAYS,
+ ENGINE_METRICS_COLUMNS,
+ _engine_equity_frame,
+ _write_run_fixture,
+ _write_run_state,
+ )
+
+ GATES_AVAILABLE = True
+except ImportError:
+ sd_harness = None
+ sd_artifacts = None
+ EvidenceStore = None
+ EvidenceRow = None
+ GATES_AVAILABLE = False
+
+requires_gates = pytest.mark.skipif(
+ not GATES_AVAILABLE,
+ reason="waiting on src.strategy_discovery hard gates (issue #969 Phase 2)",
+)
+
+
+def _prior_row(strategy_id="alpha_zoo:prior") -> "EvidenceRow":
+ return EvidenceRow(
+ strategy_id=strategy_id,
+ regime="bear_market",
+ trades_in_regime=12,
+ date_ranges=("2018-01 to 2018-12",),
+ last_verified="2026-08-01",
+ )
+
+
+def _make_store(tmp_path: Path) -> "EvidenceStore":
+ return EvidenceStore(tmp_path / "evidence.db")
+
+
+def _write_metrics_without_trade_count(run_dir: Path) -> None:
+ columns = [c for c in ENGINE_METRICS_COLUMNS if c != "trade_count"]
+ pd.DataFrame([[0.0] * len(columns)], columns=columns).to_csv(
+ run_dir / "artifacts" / "metrics.csv", index=False
+ )
+
+
+def _write_nan_equity(run_dir: Path) -> None:
+ equity = _engine_equity_frame()
+ equity.loc[equity.index[20], "equity"] = float("nan")
+ equity.to_csv(run_dir / "artifacts" / "equity.csv")
+
+
+# ---------------------------------------------------------------------------
+# The three gate readers
+# ---------------------------------------------------------------------------
+
+
+@requires_gates
+class TestGateReaders:
+ def test_read_run_status_success(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ assert sd_artifacts.read_run_status(run_dir) == "success"
+
+ def test_read_run_status_missing_or_unusable(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ (run_dir / "state.json").unlink()
+ assert sd_artifacts.read_run_status(run_dir) is None
+
+ (run_dir / "state.json").write_text("{not json", encoding="utf-8")
+ assert sd_artifacts.read_run_status(run_dir) is None
+
+ (run_dir / "state.json").write_text("[1, 2, 3]", encoding="utf-8")
+ assert sd_artifacts.read_run_status(run_dir) is None
+
+ (run_dir / "state.json").write_text('{"status": ""}', encoding="utf-8")
+ assert sd_artifacts.read_run_status(run_dir) is None
+
+ def test_read_metrics_trade_count(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ assert sd_artifacts.read_metrics_trade_count(run_dir) == len(ALL_TRADE_DAYS)
+
+ def test_read_metrics_trade_count_missing_or_unusable(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ metrics = run_dir / "artifacts" / "metrics.csv"
+
+ metrics.unlink()
+ assert sd_artifacts.read_metrics_trade_count(run_dir) is None
+
+ _write_metrics_without_trade_count(run_dir)
+ assert sd_artifacts.read_metrics_trade_count(run_dir) is None
+
+ metrics.write_text(
+ ",".join(ENGINE_METRICS_COLUMNS) + "\n", encoding="utf-8"
+ ) # header only, no value row
+ assert sd_artifacts.read_metrics_trade_count(run_dir) is None
+
+ values = ["0.0"] * len(ENGINE_METRICS_COLUMNS)
+ values[ENGINE_METRICS_COLUMNS.index("trade_count")] = "not-a-number"
+ metrics.write_text(
+ ",".join(ENGINE_METRICS_COLUMNS) + "\n" + ",".join(values) + "\n",
+ encoding="utf-8",
+ )
+ assert sd_artifacts.read_metrics_trade_count(run_dir) is None
+
+ def test_equity_has_non_finite_false_for_healthy_curve(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ assert sd_artifacts.equity_has_non_finite(run_dir) is False
+
+ def test_equity_has_non_finite_true_for_nan_mid_curve(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ _write_nan_equity(run_dir)
+ assert sd_artifacts.equity_has_non_finite(run_dir) is True
+
+ def test_equity_has_non_finite_none_when_unverifiable(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ equity = run_dir / "artifacts" / "equity.csv"
+
+ equity.unlink()
+ assert sd_artifacts.equity_has_non_finite(run_dir) is None
+
+ equity.write_text("timestamp,ret,equity,drawdown,benchmark_equity,active_ret\n")
+ assert sd_artifacts.equity_has_non_finite(run_dir) is None # no data rows
+
+ equity.write_bytes(b"\x93\xfd\x00binary\xff\xfe")
+ assert sd_artifacts.equity_has_non_finite(run_dir) is None
+
+
+# ---------------------------------------------------------------------------
+# check_run_hard_gates: the five tokens, in order
+# ---------------------------------------------------------------------------
+
+
+@requires_gates
+class TestCheckRunHardGates:
+ def test_healthy_run_passes(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ assert sd_harness.check_run_hard_gates(run_dir) == (True, None)
+
+ def test_failed_state_is_exit_nonzero(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ _write_run_state(run_dir, trade_count=len(ALL_TRADE_DAYS), status="failed")
+ ok, reason = sd_harness.check_run_hard_gates(run_dir)
+ assert ok is False
+ assert reason.startswith(sd_harness.HARD_GATE_EXIT_NONZERO + ":")
+ assert "'failed'" in reason
+
+ def test_missing_state_json_is_exit_nonzero_fail_closed(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ (run_dir / "state.json").unlink()
+ ok, reason = sd_harness.check_run_hard_gates(run_dir)
+ assert ok is False
+ assert reason.startswith(sd_harness.HARD_GATE_EXIT_NONZERO + ":")
+
+ def test_missing_metrics_is_metrics_missing(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ (run_dir / "artifacts" / "metrics.csv").unlink()
+ ok, reason = sd_harness.check_run_hard_gates(run_dir)
+ assert ok is False
+ assert reason.startswith(sd_harness.HARD_GATE_METRICS_MISSING + ":")
+
+ def test_empty_metrics_file_is_metrics_missing(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ (run_dir / "artifacts" / "metrics.csv").write_bytes(b"")
+ ok, reason = sd_harness.check_run_hard_gates(run_dir)
+ assert ok is False
+ assert reason.startswith(sd_harness.HARD_GATE_METRICS_MISSING + ":")
+
+ def test_zero_trade_count_is_zero_trades(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ _write_run_state(run_dir, trade_count=0)
+ ok, reason = sd_harness.check_run_hard_gates(run_dir)
+ assert ok is False
+ assert reason.startswith(sd_harness.HARD_GATE_ZERO_TRADES + ":")
+
+ def test_unparseable_trade_count_is_zero_trades_fail_closed(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ metrics = run_dir / "artifacts" / "metrics.csv"
+ values = ["0.0"] * len(ENGINE_METRICS_COLUMNS)
+ values[ENGINE_METRICS_COLUMNS.index("trade_count")] = "not-a-number"
+ metrics.write_text(
+ ",".join(ENGINE_METRICS_COLUMNS) + "\n" + ",".join(values) + "\n",
+ encoding="utf-8",
+ )
+ ok, reason = sd_harness.check_run_hard_gates(run_dir)
+ assert ok is False
+ assert reason.startswith(sd_harness.HARD_GATE_ZERO_TRADES + ":")
+
+ def test_missing_equity_is_equity_empty(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ (run_dir / "artifacts" / "equity.csv").unlink()
+ ok, reason = sd_harness.check_run_hard_gates(run_dir)
+ assert ok is False
+ assert reason.startswith(sd_harness.HARD_GATE_EQUITY_EMPTY + ":")
+
+ def test_nan_equity_is_equity_nan(self, tmp_path) -> None:
+ run_dir = _write_run_fixture(tmp_path)
+ _write_nan_equity(run_dir)
+ ok, reason = sd_harness.check_run_hard_gates(run_dir)
+ assert ok is False
+ assert reason.startswith(sd_harness.HARD_GATE_EQUITY_NAN + ":")
+
+ def test_gate_order_first_failure_wins(self, tmp_path) -> None:
+ # state.json missing AND metrics.csv missing → the status gate (1)
+ # reports before the metrics gate (2).
+ run_dir = _write_run_fixture(tmp_path)
+ (run_dir / "state.json").unlink()
+ (run_dir / "artifacts" / "metrics.csv").unlink()
+ ok, reason = sd_harness.check_run_hard_gates(run_dir)
+ assert ok is False
+ assert reason.startswith(sd_harness.HARD_GATE_EXIT_NONZERO + ":")
+
+
+# ---------------------------------------------------------------------------
+# End to end through rebuild_evidence: gated runs yield zero evidence rows
+# ---------------------------------------------------------------------------
+
+
+@requires_gates
+class TestHardGatesEndToEnd:
+ def test_healthy_run_still_produces_rows(self, tmp_path) -> None:
+ store = _make_store(tmp_path)
+ run_dir = _write_run_fixture(tmp_path / "ok")
+ envelope = sd_harness.rebuild_evidence(
+ [{"strategy_id": "sdm:ok_run", "run_dir": str(run_dir)}], store
+ )
+ assert envelope["status"] == "ok"
+ assert envelope["skipped"] == []
+ rows = store.get_rows()
+ assert rows, "a healthy run must still produce evidence rows"
+ assert {r.strategy_id for r in rows} == {"sdm:ok_run"}
+ assert sum(r.trades_in_regime for r in rows) == len(ALL_TRADE_DAYS)
+
+ def test_gated_run_yields_zero_rows_with_gate_token(self, tmp_path) -> None:
+ store = _make_store(tmp_path)
+ run_dir = _write_run_fixture(tmp_path / "failed_state")
+ _write_run_state(run_dir, trade_count=len(ALL_TRADE_DAYS), status="failed")
+ envelope = sd_harness.rebuild_evidence(
+ [{"strategy_id": "sdm:failed_run", "run_dir": str(run_dir)}], store
+ )
+ assert envelope["rows"] == 0
+ assert store.row_count() == 0
+ assert len(envelope["skipped"]) == 1
+ assert envelope["skipped"][0]["run_dir"] == str(run_dir)
+ assert envelope["skipped"][0]["reason"].startswith(
+ sd_harness.HARD_GATE_EXIT_NONZERO + ":"
+ )
+
+ def test_missing_state_json_yields_zero_rows_end_to_end(self, tmp_path) -> None:
+ store = _make_store(tmp_path)
+ run_dir = _write_run_fixture(tmp_path / "no_state")
+ (run_dir / "state.json").unlink()
+ envelope = sd_harness.rebuild_evidence(
+ [{"strategy_id": "sdm:no_state", "run_dir": str(run_dir)}], store
+ )
+ assert envelope["rows"] == 0
+ assert store.row_count() == 0
+ assert envelope["skipped"][0]["reason"].startswith(
+ sd_harness.HARD_GATE_EXIT_NONZERO + ":"
+ )
+
+ def test_nan_equity_skips_entirely_not_partial_rows(self, tmp_path) -> None:
+ # Regression for the Phase 1 silent-skip latent: read_equity_series
+ # drops the NaN bars and returns the SURVIVING partial curve, which
+ # pre-gate harnesses turned into partial-curve evidence rows. The
+ # hard gate must refuse the whole run instead.
+ run_dir = _write_run_fixture(tmp_path / "nan_equity")
+ _write_nan_equity(run_dir)
+ equity_path = run_dir / "artifacts" / "equity.csv"
+
+ partial = sd_artifacts.read_equity_series(equity_path)
+ assert partial is not None, "the Phase 1 reader still skips NaN bars"
+ assert len(partial[0]) == 38, "one bar was silently skipped"
+
+ store = _make_store(tmp_path)
+ envelope = sd_harness.rebuild_evidence(
+ [{"strategy_id": "sdm:nan_run", "run_dir": str(run_dir)}], store
+ )
+ assert envelope["rows"] == 0
+ assert store.row_count() == 0, "no partial-curve evidence may be stored"
+ assert envelope["skipped"][0]["reason"].startswith(
+ sd_harness.HARD_GATE_EQUITY_NAN + ":"
+ )
+
+ # Direct library callers get the same refusal (internal guard).
+ assert sd_harness.compute_evidence_for_run("sdm:nan_run", run_dir) == []
+
+ def test_rebuild_with_only_gated_runs_clears_store(self, tmp_path) -> None:
+ # A rebuild is a FULL statement of the evidence: even when every run
+ # is refused, the (atomic) replace still happens — with zero rows.
+ store = _make_store(tmp_path)
+ store.upsert_rows([_prior_row()])
+ run_dir = _write_run_fixture(tmp_path / "gated")
+ (run_dir / "state.json").unlink()
+ envelope = sd_harness.rebuild_evidence(
+ [{"strategy_id": "sdm:gated", "run_dir": str(run_dir)}], store
+ )
+ assert envelope["rows"] == 0
+ assert store.row_count() == 0
+ assert envelope["skipped"][0]["reason"].startswith("hard-gate:")
+
+
+# ---------------------------------------------------------------------------
+# Atomicity (D5): compute-all first, ONE replace_rows, crash-safe
+# ---------------------------------------------------------------------------
+
+
+@requires_gates
+class TestAtomicRebuild:
+ def test_replace_rows_replaces_all_contents_atomically(self, tmp_path) -> None:
+ store = _make_store(tmp_path)
+ store.upsert_rows([_prior_row("alpha_zoo:old1"), _prior_row("alpha_zoo:old2")])
+ new_row = EvidenceRow(
+ strategy_id="sdm:new", regime="bull_market", trades_in_regime=11
+ )
+ assert store.replace_rows([new_row]) == 1
+ rows = store.get_rows()
+ assert len(rows) == 1
+ assert rows[0].strategy_id == "sdm:new"
+
+ assert store.replace_rows([]) == 0
+ assert store.row_count() == 0
+
+ def test_replace_rows_invalid_row_leaves_prior_rows_intact(self, tmp_path) -> None:
+ store = _make_store(tmp_path)
+ store.upsert_rows([_prior_row()])
+ good = EvidenceRow(
+ strategy_id="sdm:good", regime="bull_market", trades_in_regime=11
+ )
+ bad = EvidenceRow(
+ strategy_id="sdm:bad",
+ regime="structural",
+ trades_in_regime=1,
+ sharpe_in_regime=float("nan"),
+ )
+ with pytest.raises(ValueError):
+ store.replace_rows([good, bad])
+ rows = store.get_rows()
+ assert len(rows) == 1
+ assert rows[0].strategy_id == "alpha_zoo:prior"
+
+ def test_mid_compute_crash_leaves_prior_rows_intact(
+ self, tmp_path, monkeypatch
+ ) -> None:
+ # D5: a hard crash (SystemExit bypasses the per-run `except
+ # Exception`) mid-compute must leave the store untouched, because
+ # replace_rows is only reached after ALL rows computed. The old
+ # clear-then-upsert path would have left the store empty here.
+ store = _make_store(tmp_path)
+ store.upsert_rows([_prior_row()])
+ good_run = _write_run_fixture(tmp_path / "good")
+ crash_run = _write_run_fixture(tmp_path / "crash")
+
+ def crashing_compute(strategy_id, run_dir, **kwargs):
+ if str(run_dir) == str(crash_run):
+ raise SystemExit("simulated hard crash mid-compute")
+ return [
+ EvidenceRow(
+ strategy_id=strategy_id,
+ regime="structural",
+ trades_in_regime=len(ALL_TRADE_DAYS),
+ )
+ ]
+
+ monkeypatch.setattr(sd_harness, "compute_evidence_for_run", crashing_compute)
+
+ replace_calls: list = []
+ original_replace = store.replace_rows
+
+ def replace_spy(rows):
+ replace_calls.append(list(rows))
+ return original_replace(rows)
+
+ monkeypatch.setattr(store, "replace_rows", replace_spy)
+
+ with pytest.raises(SystemExit):
+ sd_harness.rebuild_evidence(
+ [
+ {"strategy_id": "sdm:good", "run_dir": str(good_run)},
+ {"strategy_id": "sdm:crash", "run_dir": str(crash_run)},
+ ],
+ store,
+ )
+
+ assert replace_calls == [], "replace_rows must never have run"
+ rows = store.get_rows()
+ assert len(rows) == 1, "prior rows survive a mid-compute crash"
+ assert rows[0].strategy_id == "alpha_zoo:prior"
diff --git a/agent/tests/test_strategy_discovery_harness.py b/agent/tests/test_strategy_discovery_harness.py
index 64b4fd4d1..879433287 100644
--- a/agent/tests/test_strategy_discovery_harness.py
+++ b/agent/tests/test_strategy_discovery_harness.py
@@ -173,6 +173,46 @@ def _write_trades_csv(artifacts: Path, rows: list[dict]) -> None:
)
+#: Engine metrics.csv header (base.py::_write_artifacts flattens the metrics
+#: dict into one header row + one value row). trade_count is the column the
+#: Phase 2 hard gate reads for run ELIGIBILITY.
+ENGINE_METRICS_COLUMNS = [
+ "final_value",
+ "total_return",
+ "annual_return",
+ "max_drawdown",
+ "sharpe",
+ "calmar",
+ "sortino",
+ "win_rate",
+ "profit_loss_ratio",
+ "profit_factor",
+ "max_consecutive_loss",
+ "avg_holding_days",
+ "trade_count",
+ "benchmark_return",
+ "excess_return",
+ "information_ratio",
+]
+
+
+def _write_run_state(run_dir: Path, *, trade_count: int, status: str = "success"):
+ """Real-runtime state.json + engine metrics.csv for a fixture run.
+
+ The Phase 2 hard gates read ``state.json`` (runtime-written, ``{"status":
+ "success"}``) and ``artifacts/metrics.csv`` (engine-written header+value
+ rows), so every fixture that must pass ingestion carries both.
+ """
+ (run_dir / "state.json").write_text(
+ json.dumps({"status": status}), encoding="utf-8"
+ )
+ values = [1_000_000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0.0]
+ values += [trade_count, 0.0, 0.0, 0.0]
+ pd.DataFrame([values], columns=ENGINE_METRICS_COLUMNS).to_csv(
+ run_dir / "artifacts" / "metrics.csv", index=False
+ )
+
+
def _write_run_fixture(
base_dir: Path, *, include_trades: bool = True, include_equity: bool = True
) -> Path:
@@ -198,6 +238,7 @@ def _write_run_fixture(
]
_write_trades_csv(artifacts, _engine_trade_rows(round_trips))
+ _write_run_state(run_dir, trade_count=len(ALL_TRADE_DAYS))
return run_dir
@@ -215,6 +256,7 @@ def _write_multi_position_fixture(base_dir: Path) -> Path:
_exit_row(date(2024, 1, 21), "BBB.US", pnl=40.0, reason="take_profit"),
]
_write_trades_csv(artifacts, rows)
+ _write_run_state(run_dir, trade_count=2)
return run_dir
@@ -245,6 +287,7 @@ def _write_legacy_fixture(base_dir: Path) -> Path:
for trade_date in ALL_TRADE_DAYS
]
pd.DataFrame(legacy_rows).to_csv(artifacts / "trades.csv", index=False)
+ _write_run_state(run_dir, trade_count=len(ALL_TRADE_DAYS))
return run_dir
diff --git a/agent/tests/test_strategy_discovery_mcp.py b/agent/tests/test_strategy_discovery_mcp.py
index c4788ea5d..a5a018034 100644
--- a/agent/tests/test_strategy_discovery_mcp.py
+++ b/agent/tests/test_strategy_discovery_mcp.py
@@ -1,10 +1,11 @@
"""Frozen-contract tests for Strategy Discovery tools over MCP — issue #969.
AC1 (no phantom tools): ``list_strategies`` / ``query_strategies`` /
-``get_strategy_evidence`` must be registered on the FastMCP server and each
-wrapper must delegate to ``registry.execute(<own name>, <args>)`` — never the
-generic "Tool not found" path when the facade layer can answer, and never a
-crash when the registry is missing or broken (actionable JSON instead).
+``get_strategy_evidence`` / ``refresh_strategy_evidence`` must be registered
+on the FastMCP server and each wrapper must delegate to
+``registry.execute(<own name>, <args>)`` — never the generic "Tool not
+found" path when the facade layer can answer, and never a crash when the
+registry is missing or broken (actionable JSON instead).
Follows the ``test_qveris_mcp.py`` fixture pattern: a fresh/monkeypatched
``mcp_server._registry`` per test. No network: delegation is verified against
@@ -21,7 +22,12 @@ import pytest
import mcp_server
from src.agent.tools import ToolRegistry
-SD_TOOLS = ("list_strategies", "query_strategies", "get_strategy_evidence")
+SD_TOOLS = (
+ "list_strategies",
+ "query_strategies",
+ "get_strategy_evidence",
+ "refresh_strategy_evidence",
+)
def _unwrapped(name: str):
diff --git a/agent/tests/test_strategy_discovery_refresh.py b/agent/tests/test_strategy_discovery_refresh.py
new file mode 100644
index 000000000..719e05cf0
--- /dev/null
+++ b/agent/tests/test_strategy_discovery_refresh.py
@@ -0,0 +1,444 @@
+"""Phase 2 refresh-surface contract for ``refresh_strategy_evidence`` (#969).
+
+Covers the agent tool in ``src.tools.strategy_discovery_tool``: the strict
+envelope on the ok path (fixture run dirs in the REAL engine artifact schema,
+reused from ``test_strategy_discovery_harness`` — no second schema), the
+exactly-one-source rule, both manifest shapes (object with ``runs`` + bare
+array), manifest failure envelopes, per-entry validation, and the D7 path
+containment rule (offending entries skipped with the stable
+``path-outside-allowed-roots:`` token while the rest still process).
+
+The store is isolated per test through the
+``VIBE_TRADING_STRATEGY_DISCOVERY_DB_PATH`` env override (the conftest
+resets the cached EnvConfig around every test); the runtime runs root is
+redirected via ``VIBE_TRADING_HOME``.
+
+Atomicity failure-injection is NOT duplicated here — Unit 1 pins it in
+``test_strategy_discovery_hard_gates.py::TestAtomicRebuild``.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+try:
+ from src.strategy_discovery.evidence_store import EvidenceStore
+ from src.tools import strategy_discovery_tool as sdt
+
+ from tests.test_strategy_discovery_harness import (
+ ALL_TRADE_DAYS,
+ _write_run_fixture,
+ )
+
+ REFRESH_AVAILABLE = True
+except ImportError:
+ EvidenceStore = None
+ sdt = None
+ REFRESH_AVAILABLE = False
+
+requires_refresh = pytest.mark.skipif(
+ not REFRESH_AVAILABLE,
+ reason="waiting on refresh_strategy_evidence tool (issue #969 Phase 2)",
+)
+
+TOOL_NAME = "refresh_strategy_evidence"
+SKIP_TOKEN = "path-outside-allowed-roots"
+
+
+def _strict_json_loads(text: str) -> dict:
+ def _reject(constant):
+ raise ValueError(f"non-strict constant {constant!r} in tool output")
+
+ payload = json.loads(text, parse_constant=_reject)
+ assert isinstance(
+ payload, dict
+ ), f"tool output must be a JSON object, got {type(payload)}"
+ return payload
+
+
+def isolated_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Redirect the runtime root and the evidence DB into tmp_path."""
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path))
+ monkeypatch.setenv(
+ "VIBE_TRADING_STRATEGY_DISCOVERY_DB_PATH", str(tmp_path / "evidence.db")
+ )
+ monkeypatch.delenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", raising=False)
+ return tmp_path
+
+
+def runs_root(isolated_home: Path) -> Path:
+ """The runtime runs root (inside the allowed roots by construction)."""
+ root = isolated_home / "runs"
+ root.mkdir(parents=True, exist_ok=True)
+ return root
+
+
+def _tool() -> "sdt.RefreshStrategyEvidenceTool":
+ return sdt.RefreshStrategyEvidenceTool()
+
+
+def _write_manifest(path: Path, payload) -> Path:
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ return path
+
+
+def _store() -> "EvidenceStore":
+ return EvidenceStore()
+
+
+@requires_refresh
+class TestToolIdentity:
+ def test_tool_metadata(self) -> None:
+ tool = _tool()
+ assert tool.name == TOOL_NAME
+ assert tool.is_readonly is False, "the refresh tool is a WRITE tool"
+ assert tool.repeatable is True
+ assert tool.parameters["properties"].keys() == {"manifest_path", "runs"}
+ assert tool.parameters.get("required", []) == []
+
+
+@requires_refresh
+class TestEnvelopeOkPath:
+ def test_manifest_object_form(self, runs_root: Path) -> None:
+ run_dir = _write_run_fixture(runs_root)
+ manifest = _write_manifest(
+ runs_root.parent / "manifest.json",
+ {"runs": [{"strategy_id": "sdm:refreshed", "run_dir": str(run_dir)}]},
+ )
+
+ payload = _strict_json_loads(_tool().execute(manifest_path=str(manifest)))
+
+ assert payload["status"] == "ok"
+ assert payload["runs"] == 1
+ assert payload["strategies"] == 1
+ assert payload["rows"] > 0
+ assert payload["skipped"] == []
+ rows = _store().get_rows()
+ assert rows, "evidence rows must land in the default store"
+ assert {row.strategy_id for row in rows} == {"sdm:refreshed"}
+ assert sum(row.trades_in_regime for row in rows) == len(ALL_TRADE_DAYS)
+
+ def test_manifest_bare_array_form(self, runs_root: Path) -> None:
+ run_dir = _write_run_fixture(runs_root)
+ manifest = _write_manifest(
+ runs_root.parent / "manifest.json",
+ [{"strategy_id": "sdm:bare_array", "run_dir": str(run_dir)}],
+ )
+
+ payload = _strict_json_loads(_tool().execute(manifest_path=str(manifest)))
+
+ assert payload["status"] == "ok"
+ assert payload["strategies"] == 1
+ assert payload["rows"] > 0
+
+ def test_inline_runs_parameter(self, runs_root: Path) -> None:
+ run_dir = _write_run_fixture(runs_root)
+
+ payload = _strict_json_loads(
+ _tool().execute(
+ runs=[{"strategy_id": "sdm:inline", "run_dir": str(run_dir)}]
+ )
+ )
+
+ assert payload["status"] == "ok"
+ assert payload["strategies"] == 1
+ assert payload["rows"] > 0
+ assert {row.strategy_id for row in _store().get_rows()} == {"sdm:inline"}
+
+ def test_position_size_is_forwarded(self, runs_root: Path) -> None:
+ run_dir = _write_run_fixture(runs_root)
+
+ payload = _strict_json_loads(
+ _tool().execute(
+ runs=[
+ {
+ "strategy_id": "sdm:sized",
+ "run_dir": str(run_dir),
+ "position_size": 2500.0,
+ }
+ ]
+ )
+ )
+
+ assert payload["status"] == "ok"
+ rows = _store().get_rows()
+ assert rows
+ assert all(row.position_size == 2500.0 for row in rows)
+
+ def test_gated_run_reports_hard_gate_token(self, runs_root: Path) -> None:
+ run_dir = _write_run_fixture(runs_root)
+ (run_dir / "state.json").unlink()
+
+ payload = _strict_json_loads(
+ _tool().execute(
+ runs=[{"strategy_id": "sdm:gated", "run_dir": str(run_dir)}]
+ )
+ )
+
+ assert payload["status"] == "ok"
+ assert payload["rows"] == 0
+ assert len(payload["skipped"]) == 1
+ assert payload["skipped"][0]["reason"].startswith("hard-gate:")
+
+
+@requires_refresh
+class TestExactlyOneSource:
+ def test_neither_parameter_is_an_error(self) -> None:
+ payload = _strict_json_loads(_tool().execute())
+ assert payload["status"] == "error"
+ assert "exactly one" in payload["error"]
+
+ def test_both_parameters_is_an_error(self, runs_root: Path) -> None:
+ manifest = _write_manifest(runs_root.parent / "manifest.json", {"runs": []})
+ payload = _strict_json_loads(
+ _tool().execute(manifest_path=str(manifest), runs=[])
+ )
+ assert payload["status"] == "error"
+ assert "exactly one" in payload["error"]
+
+ def test_runs_must_be_an_array(self) -> None:
+ payload = _strict_json_loads(_tool().execute(runs={"strategy_id": "x"}))
+ assert payload["status"] == "error"
+ assert "array" in payload["error"]
+
+ def test_overlong_manifest_path_is_rejected(self) -> None:
+ payload = _strict_json_loads(_tool().execute(manifest_path="m" * 501))
+ assert payload["status"] == "error"
+ assert "too long" in payload["error"].lower()
+
+
+@requires_refresh
+class TestManifestFailures:
+ def test_missing_manifest_file(self, isolated_home: Path) -> None:
+ payload = _strict_json_loads(
+ _tool().execute(manifest_path=str(isolated_home / "absent.json"))
+ )
+ assert payload["status"] == "error"
+ assert "missing or unreadable" in payload["error"]
+
+ def test_invalid_json_manifest(self, isolated_home: Path) -> None:
+ bad = isolated_home / "bad.json"
+ bad.write_text("{not json", encoding="utf-8")
+ payload = _strict_json_loads(_tool().execute(manifest_path=str(bad)))
+ assert payload["status"] == "error"
+ assert "not valid JSON" in payload["error"]
+
+ @pytest.mark.parametrize(
+ "payload_factory",
+ [
+ lambda: {"strategies": []}, # object without a runs array
+ lambda: {"runs": "not-a-list"}, # runs present but wrong type
+ lambda: "just a string", # neither object nor array
+ ],
+ ids=["no-runs-key", "runs-not-list", "bare-string"],
+ )
+ def test_wrong_manifest_shape(self, isolated_home: Path, payload_factory) -> None:
+ manifest = _write_manifest(isolated_home / "shape.json", payload_factory())
+ payload = _strict_json_loads(_tool().execute(manifest_path=str(manifest)))
+ assert payload["status"] == "error"
+ assert (
+ "'runs' array" in payload["error"] or "bare JSON array" in payload["error"]
+ )
+
+
+@requires_refresh
+class TestPathContainment:
+ def test_outside_entry_skipped_with_stable_token_rest_process(
+ self, runs_root: Path, isolated_home: Path
+ ) -> None:
+ inside = _write_run_fixture(runs_root)
+ outside = _write_run_fixture(isolated_home / "elsewhere")
+
+ payload = _strict_json_loads(
+ _tool().execute(
+ runs=[
+ {"strategy_id": "sdm:outside", "run_dir": str(outside)},
+ {"strategy_id": "sdm:inside", "run_dir": str(inside)},
+ ]
+ )
+ )
+
+ assert payload["status"] == "ok"
+ assert payload["runs"] == 2
+ assert payload["strategies"] == 1, "the inside entry still processes"
+ assert payload["rows"] > 0
+ assert {row.strategy_id for row in _store().get_rows()} == {"sdm:inside"}
+ assert len(payload["skipped"]) == 1
+ skip = payload["skipped"][0]
+ assert skip["run_dir"] == str(outside)
+ assert skip["reason"].startswith(f"{SKIP_TOKEN}:")
+ assert str(outside) in skip["reason"]
+
+ def test_configured_allowed_run_root_is_accepted(
+ self, isolated_home: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ extra_root = tmp_path / "extra-roots" / "research"
+ extra_root.mkdir(parents=True)
+ run_dir = _write_run_fixture(extra_root)
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(extra_root))
+
+ payload = _strict_json_loads(
+ _tool().execute(
+ runs=[{"strategy_id": "sdm:extra_root", "run_dir": str(run_dir)}]
+ )
+ )
+
+ assert payload["status"] == "ok"
+ assert payload["skipped"] == []
+ assert payload["rows"] > 0
+
+ def test_symlink_escape_is_contained(
+ self, runs_root: Path, isolated_home: Path
+ ) -> None:
+ outside = _write_run_fixture(isolated_home / "elsewhere")
+ link = runs_root / "sneaky_link"
+ try:
+ link.symlink_to(outside)
+ except OSError:
+ pytest.skip("symlinks unavailable on this platform")
+
+ payload = _strict_json_loads(
+ _tool().execute(runs=[{"strategy_id": "sdm:sneaky", "run_dir": str(link)}])
+ )
+
+ assert payload["rows"] == 0
+ assert payload["skipped"][0]["reason"].startswith(f"{SKIP_TOKEN}:")
+
+ def test_manifest_outside_allowed_roots_is_refused(
+ self, isolated_home: Path, runs_root: Path
+ ) -> None:
+ # Defense-in-depth: the manifest file itself is containment-checked
+ # (runtime root or allowed run roots), not just the run_dir entries.
+ import shutil
+ import tempfile
+
+ outside_dir = Path(tempfile.mkdtemp(prefix="sd-manifest-outside-"))
+ try:
+ run_dir = _write_run_fixture(runs_root)
+ manifest = _write_manifest(
+ outside_dir / "manifest.json",
+ {
+ "runs": [
+ {"strategy_id": "sdm:outside_manifest", "run_dir": str(run_dir)}
+ ]
+ },
+ )
+ payload = _strict_json_loads(_tool().execute(manifest_path=str(manifest)))
+ assert payload["status"] == "error"
+ assert "outside the runtime root" in payload["error"]
+ assert _store().row_count() == 0, "refused manifest must not rebuild"
+ finally:
+ shutil.rmtree(outside_dir, ignore_errors=True)
+
+ def test_manifest_inside_configured_run_root_is_accepted(
+ self,
+ isolated_home: Path,
+ runs_root: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ ) -> None:
+ extra_root = tmp_path / "extra-roots" / "manifests"
+ extra_root.mkdir(parents=True)
+ run_dir = _write_run_fixture(runs_root)
+ manifest = _write_manifest(
+ extra_root / "manifest.json",
+ {"runs": [{"strategy_id": "sdm:manifest_root", "run_dir": str(run_dir)}]},
+ )
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(extra_root))
+
+ payload = _strict_json_loads(_tool().execute(manifest_path=str(manifest)))
+
+ assert payload["status"] == "ok"
+ assert payload["rows"] > 0
+
+
+@requires_refresh
+class TestEntryValidation:
+ def test_invalid_entries_skipped_with_reasons(self, runs_root: Path) -> None:
+ valid = _write_run_fixture(runs_root)
+ payload = _strict_json_loads(
+ _tool().execute(
+ runs=[
+ {"run_dir": str(valid)}, # missing strategy_id
+ {"strategy_id": " ", "run_dir": str(valid)}, # blank id
+ {"strategy_id": "a" * 501, "run_dir": str(valid)}, # too long
+ {"strategy_id": "sdm:no_dir"}, # missing run_dir
+ "not-an-object",
+ {
+ "strategy_id": "sdm:valid",
+ "run_dir": str(valid),
+ },
+ ]
+ )
+ )
+
+ assert payload["status"] == "ok"
+ assert payload["runs"] == 6
+ assert payload["strategies"] == 1
+ assert payload["rows"] > 0
+ reasons = [entry["reason"] for entry in payload["skipped"]]
+ assert len(reasons) == 5
+ assert reasons.count("missing strategy_id or run_dir") == 3
+ assert any("too long" in reason for reason in reasons)
+ assert any("not an object" in reason for reason in reasons)
+
+ def test_all_entries_invalid_leaves_store_untouched(
+ self, runs_root: Path, isolated_home: Path
+ ) -> None:
+ # A rebuild is a full statement of the evidence — but entries refused
+ # at the validation boundary never reach the rebuild, so a fully
+ # invalid manifest must NOT clear the existing cache.
+ from src.strategy_discovery.models import EvidenceRow
+
+ store = _store()
+ store.upsert_rows(
+ [
+ EvidenceRow(
+ strategy_id="alpha_zoo:prior",
+ regime="bear_market",
+ trades_in_regime=12,
+ date_ranges=("2018-01 to 2018-12",),
+ last_verified="2026-08-01",
+ )
+ ]
+ )
+ outside = _write_run_fixture(isolated_home / "elsewhere")
+
+ payload = _strict_json_loads(
+ _tool().execute(
+ runs=[{"strategy_id": "sdm:outside", "run_dir": str(outside)}]
+ )
+ )
+
+ assert payload["status"] == "ok"
+ assert payload["rows"] == 0
+ assert len(payload["skipped"]) == 1
+ assert _store().row_count() == 1, "prior rows survive an all-invalid refresh"
+
+
+@requires_refresh
+class TestRegistryDiscovery:
+ def test_auto_discovered_and_executable_through_registry(
+ self, runs_root: Path
+ ) -> None:
+ from src.tools import build_registry
+
+ registry = build_registry()
+ assert TOOL_NAME in registry.tool_names
+ tool = registry.get(TOOL_NAME)
+ assert tool is not None
+ assert tool.is_readonly is False
+
+ run_dir = _write_run_fixture(runs_root)
+ result = registry.execute(
+ TOOL_NAME,
+ {"runs": [{"strategy_id": "sdm:via_registry", "run_dir": str(run_dir)}]},
+ )
+ payload = _strict_json_loads(result)
+ assert payload["status"] == "ok"
+ assert payload["rows"] > 0
diff --git a/agent/tests/test_strategy_discovery_routing.py b/agent/tests/test_strategy_discovery_routing.py
index 51bfa56a1..8b5cf50df 100644
--- a/agent/tests/test_strategy_discovery_routing.py
+++ b/agent/tests/test_strategy_discovery_routing.py
@@ -2,9 +2,9 @@
AC2 (routing validated at startup): ``ContextBuilder.build_system_prompt()``
must include the Strategy Discovery routing block when — and only when — all
-three tools are present in the tool registry, and must degrade to a clean
-prompt (no block, no crash) when ``src.strategy_discovery`` cannot be
-imported. The expected block text is derived from
+four tools (three read-only plus ``refresh_strategy_evidence``) are present
+in the tool registry, and must degrade to a clean prompt (no block, no
+crash) when ``src.strategy_discovery`` cannot be imported. The expected block text is derived from
``src.strategy_discovery.guard.routing_block`` so these tests stay decoupled
from the block's exact wording.
@@ -34,7 +34,12 @@ except ImportError:
sd_guard = None
GUARD_AVAILABLE = False
-SD_TOOLS = ("list_strategies", "query_strategies", "get_strategy_evidence")
+SD_TOOLS = (
+ "list_strategies",
+ "query_strategies",
+ "get_strategy_evidence",
+ "refresh_strategy_evidence",
+)
class _StubTool(BaseTool):
diff --git a/agent/tests/test_strategy_discovery_tools.py b/agent/tests/test_strategy_discovery_tools.py
index e2f392283..a1deb7e1b 100644
--- a/agent/tests/test_strategy_discovery_tools.py
+++ b/agent/tests/test_strategy_discovery_tools.py
@@ -1,10 +1,13 @@
"""Frozen-contract tests for ``src.tools.strategy_discovery_tool`` — issue #969.
-AC1 (tools callable at runtime): the module must expose exactly three
+AC1 (tools callable at runtime): the module must expose exactly four
``BaseTool`` classes whose ``name`` attributes are ``list_strategies`` /
-``query_strategies`` / ``get_strategy_evidence``, all read-only, returning
-strict-JSON envelopes with ``status`` ok/error and never raising on invalid
-parameter types.
+``query_strategies`` / ``get_strategy_evidence`` /
+``refresh_strategy_evidence``. The three query tools are read-only; the
+refresh tool is the single WRITE tool (``is_readonly=False``, scope limited
+to the disposable evidence cache — Phase 2, plan D13). All return strict-JSON
+envelopes with ``status`` ok/error and never raise on invalid parameter
+types.
The sibling-built ``StrategyDiscoveryFacade`` construction is intercepted at
module level (patching ``sdt.StrategyDiscoveryFacade``) so a ``FakeFacade``
@@ -32,7 +35,9 @@ requires_tools = pytest.mark.skipif(
reason="waiting on sibling B: src.tools.strategy_discovery_tool not landed yet (issue #969)",
)
-EXPECTED_NAMES = {"list_strategies", "query_strategies", "get_strategy_evidence"}
+READ_TOOL_NAMES = {"list_strategies", "query_strategies", "get_strategy_evidence"}
+WRITE_TOOL_NAME = "refresh_strategy_evidence"
+EXPECTED_NAMES = READ_TOOL_NAMES | {WRITE_TOOL_NAME}
def _strict_json_loads(text: str) -> dict:
@@ -109,8 +114,8 @@ def _discover_tool_classes():
def _instantiate_tools() -> dict:
classes = _discover_tool_classes()
- assert len(classes) == 3, (
- f"expected exactly 3 BaseTool classes in strategy_discovery_tool, found "
+ assert len(classes) == 4, (
+ f"expected exactly 4 BaseTool classes in strategy_discovery_tool, found "
f"{[c.__name__ for c in classes]}"
)
tools = {cls().name: cls() for cls in classes}
@@ -122,9 +127,9 @@ def _instantiate_tools() -> dict:
@requires_tools
class TestToolClasses:
- def test_three_tools_with_exact_names_all_read_only(self, fake_facade) -> None:
+ def test_query_tools_with_exact_names_are_read_only(self, fake_facade) -> None:
tools = _instantiate_tools()
- for name in EXPECTED_NAMES:
+ for name in READ_TOOL_NAMES:
tool = tools[name]
assert isinstance(tool, BaseTool)
assert (
@@ -132,6 +137,27 @@ class TestToolClasses:
), f"{name} must declare a JSON-schema parameters block"
assert tool.is_readonly is True, f"{name} must be read-only"
+ def test_refresh_tool_is_the_single_write_tool(self, fake_facade) -> None:
+ # Phase 2 (plan D13): refresh_strategy_evidence is a WRITE tool, but
+ # its scope is the disposable evidence cache only — it rebuilds that
+ # cache from run artifacts and never touches Alpha Zoo/SDM sources of
+ # truth. It must be the ONLY non-read-only tool in the module.
+ tools = _instantiate_tools()
+ tool = tools[WRITE_TOOL_NAME]
+ assert isinstance(tool, BaseTool)
+ assert tool.parameters, "refresh tool must declare a parameters block"
+ assert tool.is_readonly is False, (
+ "refresh_strategy_evidence writes the disposable evidence cache "
+ "and must not be marked read-only"
+ )
+ assert tool.repeatable is True, "the cache rebuild is safely repeatable"
+ non_readonly = [
+ name for name, instance in tools.items() if instance.is_readonly is False
+ ]
+ assert non_readonly == [
+ WRITE_TOOL_NAME
+ ], f"only {WRITE_TOOL_NAME} may be non-read-only, got {non_readonly}"
+
@requires_tools
class TestExecuteEnvelopes:
@@ -161,6 +187,30 @@ class TestExecuteEnvelopes:
assert "bear_market" in combined
assert "marginal" in combined
+ def test_query_strategies_schema_exposes_include_stale(self) -> None:
+ # SKILL.md documents include_stale on query_strategies; the tool
+ # schema must actually expose it or the documented inspection path
+ # for stale rows is unreachable (adversarial-review MAJOR).
+ tool = _instantiate_tools()["query_strategies"]
+ properties = tool.parameters["properties"]
+ assert "include_stale" in properties
+ assert properties["include_stale"]["type"] == "boolean"
+ assert properties["include_stale"]["default"] is False
+
+ def test_query_strategies_forwards_include_stale(self, fake_facade) -> None:
+ tool = _instantiate_tools()["query_strategies"]
+ payload = _strict_json_loads(tool.execute(include_stale=True))
+ assert payload["status"] == "ok"
+ _, args, kwargs = fake_facade.instances[-1].calls[-1]
+ assert kwargs.get("include_stale") is True or True in args
+
+ def test_query_strategies_defaults_include_stale_false(self, fake_facade) -> None:
+ tool = _instantiate_tools()["query_strategies"]
+ payload = _strict_json_loads(tool.execute())
+ assert payload["status"] == "ok"
+ _, args, kwargs = fake_facade.instances[-1].calls[-1]
+ assert kwargs.get("include_stale", False) is False
+
def test_get_strategy_evidence_forwards_strategy_id(self, fake_facade) -> None:
tool = _instantiate_tools()["get_strategy_evidence"]
payload = _strict_json_loads(tool.execute(strategy_id="alpha_zoo:a1"))
@@ -193,6 +243,14 @@ class TestInvalidParameters:
assert payload["status"] == "error"
assert payload.get("error")
+ def test_query_strategies_rejects_unparseable_include_stale(
+ self, fake_facade
+ ) -> None:
+ tool = _instantiate_tools()["query_strategies"]
+ payload = _strict_json_loads(tool.execute(include_stale="maybe"))
+ assert payload["status"] == "error"
+ assert payload.get("error")
+
def test_get_strategy_evidence_rejects_non_string_strategy_id(
self, fake_facade
) -> None: