Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(strategy): bind adaptation generation and backtest evidence across surfaces

Haozhe Wu01189405a6fb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a54f2b40e..66339d5d3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,7 @@
# Changelog
+- Strategy adaptation now binds each child to its own description, universe, date window and hashed backtest artifacts; scoped refresh preserves other strategies' evidence. Agent/MCP, CLI, authenticated REST and the Web welcome entry share the workflow.
+
All notable changes to Vibe-Trading are documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/).
diff --git a/README.md b/README.md
index 0be344736..1f0cf105d 100644
--- a/README.md
+++ b/README.md
@@ -1672,7 +1672,7 @@ Posting `{}` schedules a template on its own suggested cadence with its declared
## 🔌 MCP Plugin
-Vibe-Trading exposes 80 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 81 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`:
@@ -1741,7 +1741,7 @@ with `--host` / `--port`.
</details>
-**MCP tools exposed (80):** `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`, `read_run_artifact`, `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_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**MCP tools exposed (81):** `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`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `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_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
`quantlib_call` attribution requires finite sector weights and returns, finite Carino return inputs, and a finite non-negative weight-sum tolerance. Invalid data is rejected explicitly rather than returned as an attribution result containing `NaN`. Missing returns for a zero-weight sector may still be inferred from the other side.
@@ -2134,7 +2134,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 — 80 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 81 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
@@ -2149,7 +2149,7 @@ Vibe-Trading/
│ │ ├── memory/ # Cross-session persistent memory
│ │ │ └── persistent.py # file-based memory (~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 111 auto-discovered agent tools
+│ │ ├── tools/ # 112 auto-discovered agent tools
│ │ │ ├── backtest_tool.py # run backtests
│ │ │ ├── remember_tool.py # cross-session memory (save/recall/forget)
│ │ │ ├── skill_writer_tool.py # skill CRUD (save/patch/delete/file)
diff --git a/README_ar.md b/README_ar.md
index cdd89da0e..3bcd3cb0d 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -1293,7 +1293,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \
## 🔌 MCP Plugin
-يعرض Vibe-Trading 80 أداة MCP لأي عميل متوافق مع MCP. يعمل كعملية stdio فرعية، دون إعداد خادم. أدوات البحث الأساسية تعمل دون أي مفاتيح API لأسواق HK/US/crypto؛ وأدوات connector للتداول تستخدم profile الموصل المختار، ويحتاج `run_swarm` وحده إلى مفتاح LLM.
+يعرض Vibe-Trading 81 أداة MCP لأي عميل متوافق مع MCP. يعمل كعملية stdio فرعية، دون إعداد خادم. أدوات البحث الأساسية تعمل دون أي مفاتيح API لأسواق HK/US/crypto؛ وأدوات connector للتداول تستخدم profile الموصل المختار، ويحتاج `run_swarm` وحده إلى مفتاح LLM.
**متغيرات البيئة:** العميل هو من يشغّل الخادم بنفسه، لذا لا يصل إليه `export` من الـ shell أبداً —— اضبطها في كتلة `env` الخاصة بالعميل. كود الاختبار الخلفي المولَّد محصور ضمن جذور التشغيل المسموح بها، لذا تحتاج إلى `VIBE_TRADING_ALLOWED_RUN_ROOTS` لكتابة النتائج في دليل عمل خاص بك:
@@ -1349,7 +1349,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)
</details>
-**أدوات MCP المعروضة (80):** `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`, `read_run_artifact`, `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_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**أدوات MCP المعروضة (81):** `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`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `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_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
### أدوات MCP الخارجية في SWARM
@@ -1709,7 +1709,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 — 80 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 81 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
@@ -1724,7 +1724,7 @@ Vibe-Trading/
│ │ ├── memory/ # Cross-session persistent memory
│ │ │ └── persistent.py # file-based memory (~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 111 auto-discovered agent tools
+│ │ ├── tools/ # 112 auto-discovered agent tools
│ │ │ ├── backtest_tool.py # run backtests
│ │ │ ├── remember_tool.py # cross-session memory (save/recall/forget)
│ │ │ ├── skill_writer_tool.py # skill CRUD (save/patch/delete/file)
diff --git a/README_es.md b/README_es.md
index 8f6fc2433..f65c6d8d6 100644
--- a/README_es.md
+++ b/README_es.md
@@ -1353,7 +1353,7 @@ Enviar `{}` programa una plantilla con su propia cadencia sugerida y sus valores
## 🔌 MCP Plugin
-Vibe-Trading expone 80 MCP tools para cualquier cliente compatible con MCP. Se ejecuta como un subproceso stdio — no requiere configuración de servidor. Las herramientas de investigación principales funcionan sin ninguna API key para HK/US/crypto; las herramientas del conector de trading usan el perfil de conector seleccionado, y `run_swarm` necesita una LLM key.
+Vibe-Trading expone 81 MCP tools para cualquier cliente compatible con MCP. Se ejecuta como un subproceso stdio — no requiere configuración de servidor. Las herramientas de investigación principales funcionan sin ninguna API key para HK/US/crypto; las herramientas del conector de trading usan el perfil de conector seleccionado, y `run_swarm` necesita una LLM key.
**Variables de entorno:** el cliente lanza el servidor él mismo, así que un `export` de shell nunca le llega — configúralas en el bloque `env` del cliente. El código de backtest generado está confinado a los run roots permitidos, así que para escribir resultados en un workspace propio necesitas `VIBE_TRADING_ALLOWED_RUN_ROOTS`:
@@ -1424,7 +1424,7 @@ dirección de bind con `--host` / `--port`.
</details>
-**MCP tools expuestas (80):** `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`, `read_run_artifact`, `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_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**MCP tools expuestas (81):** `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`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `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_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
### SWARM external MCP tools
@@ -1797,7 +1797,7 @@ Vibe-Trading/
├── agent/ # Backend (Python)
│ ├── cli/ # Paquete CLI — TUI interactiva + subcomandos
│ ├── api_server.py # Servidor FastAPI — runs, sesiones, carga, swarm, SSE
-│ ├── mcp_server.py # Servidor MCP — 80 herramientas para OpenClaw / Claude Desktop
+│ ├── mcp_server.py # Servidor MCP — 81 herramientas para OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # Núcleo del agente ReAct
@@ -1812,7 +1812,7 @@ Vibe-Trading/
│ │ ├── memory/ # Memoria persistente entre sesiones
│ │ │ └── persistent.py # memoria basada en archivos (~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 111 herramientas de agente autodescubiertas
+│ │ ├── tools/ # 112 herramientas de agente autodescubiertas
│ │ │ ├── backtest_tool.py # ejecuta backtests
│ │ │ ├── remember_tool.py # memoria entre sesiones (save/recall/forget)
│ │ │ ├── skill_writer_tool.py # CRUD de skills (save/patch/delete/file)
diff --git a/README_id.md b/README_id.md
index d4023b080..c339df133 100644
--- a/README_id.md
+++ b/README_id.md
@@ -1599,7 +1599,7 @@ Mengirim `{}` akan menjadwalkan template memakai cadence yang disarankan beserta
<a id="-mcp-plugin"></a>
## 🔌 Plugin MCP
-Vibe-Trading mengekspos 80 tool MCP untuk client yang kompatibel MCP. Berjalan sebagai subprocess stdio — tidak perlu setup server. Tool riset inti bekerja tanpa API key untuk HK/AS/crypto; tool connector trading menggunakan profil connector terpilih, dan `run_swarm` memerlukan LLM key.
+Vibe-Trading mengekspos 81 tool MCP untuk client yang kompatibel MCP. Berjalan sebagai subprocess stdio — tidak perlu setup server. Tool riset inti bekerja tanpa API key untuk HK/AS/crypto; tool connector trading menggunakan profil connector terpilih, dan `run_swarm` memerlukan LLM key.
**Environment variable:** client menjalankan server sendiri, sehingga `export` dari shell tidak pernah sampai ke proses tersebut — atur di block `env` client. Kode backtest yang dihasilkan dibatasi ke root run yang diizinkan, jadi menulis hasil ke workspace Anda sendiri memerlukan `VIBE_TRADING_ALLOWED_RUN_ROOTS`:
@@ -1668,7 +1668,7 @@ dengan `--host` / `--port`.
</details>
-**Tool MCP yang diekspos (80):** `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`, `read_run_artifact`, `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_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**Tool MCP yang diekspos (81):** `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`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `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_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
### Tool MCP eksternal untuk SWARM
@@ -2042,7 +2042,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 — 80 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 81 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
@@ -2057,7 +2057,7 @@ Vibe-Trading/
│ │ ├── memory/ # Cross-session persistent memory
│ │ │ └── persistent.py # file-based memory (~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 111 auto-discovered agent tools
+│ │ ├── tools/ # 112 auto-discovered agent tools
│ │ │ ├── backtest_tool.py # run backtests
│ │ │ ├── remember_tool.py # cross-session memory (save/recall/forget)
│ │ │ ├── skill_writer_tool.py # skill CRUD (save/patch/delete/file)
diff --git a/README_ja.md b/README_ja.md
index 427b06e61..915fe7ef9 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -1295,7 +1295,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \
## 🔌 MCP Plugin
-Vibe-Trading は MCP-compatible client 向けに 80 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 向けに 81 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` が必要です:
@@ -1351,7 +1351,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)
</details>
-**公開される MCP tools(80):** `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`, `read_run_artifact`, `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_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**公開される MCP tools(81):** `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`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
### SWARM の外部 MCP tools
@@ -1717,7 +1717,7 @@ Vibe-Trading/
├── agent/ # バックエンド (Python)
│ ├── cli/ # CLI パッケージ — インタラクティブ TUI + サブコマンド
│ ├── api_server.py # FastAPI サーバー — runs、sessions、upload、swarm、SSE
-│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 80 tools
+│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 81 tools
│ │
│ ├── src/
│ │ ├── agent/ # ReAct エージェントコア
@@ -1732,7 +1732,7 @@ Vibe-Trading/
│ │ ├── memory/ # クロスセッション永続メモリ
│ │ │ └── persistent.py # ファイルベースメモリ (~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 111 個の自動検出エージェントツール
+│ │ ├── tools/ # 112 個の自動検出エージェントツール
│ │ │ ├── backtest_tool.py # バックテスト実行
│ │ │ ├── remember_tool.py # クロスセッションメモリ (save/recall/forget)
│ │ │ ├── skill_writer_tool.py # skill CRUD (save/patch/delete/file)
diff --git a/README_ko.md b/README_ko.md
index cd981eae3..0ee397df1 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -1296,7 +1296,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \
## 🔌 MCP Plugin
-Vibe-Trading은 모든 MCP-compatible client를 위해 80개 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를 위해 81개 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`가 필요합니다:
@@ -1352,7 +1352,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)
</details>
-**노출되는 MCP tools(80):** `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`, `read_run_artifact`, `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_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**노출되는 MCP tools(81):** `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`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `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_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
### SWARM 외부 MCP tools
@@ -1714,7 +1714,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 — 80 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 81 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
@@ -1729,7 +1729,7 @@ Vibe-Trading/
│ │ ├── memory/ # Cross-session persistent memory
│ │ │ └── persistent.py # file-based memory (~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 111 auto-discovered agent tools
+│ │ ├── tools/ # 112 auto-discovered agent tools
│ │ │ ├── backtest_tool.py # run backtests
│ │ │ ├── remember_tool.py # cross-session memory (save/recall/forget)
│ │ │ ├── skill_writer_tool.py # skill CRUD (save/patch/delete/file)
diff --git a/README_zh.md b/README_zh.md
index 860a4ccd1..ca90b47a8 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -1300,7 +1300,7 @@ POST `{}` 即按模板自身的建议节奏和默认变量排程。渲染后的
## 🔌 MCP Plugin
-Vibe-Trading 为任何 MCP-compatible client 暴露 80 个 MCP tools。它作为 stdio subprocess 运行,无需 server setup。核心 research tools 对港股/美股/加密零 API key 可用;trading connector tools 使用当前选择的 connector profile;只有 `run_swarm` 需要 LLM key。
+Vibe-Trading 为任何 MCP-compatible client 暴露 81 个 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`:
@@ -1356,7 +1356,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)
</details>
-**暴露的 MCP tools(80):** `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`, `read_run_artifact`, `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_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
+**暴露的 MCP tools(81):** `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`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_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`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`.
### SWARM 的外部 MCP tools
@@ -1712,7 +1712,7 @@ Vibe-Trading/
├── agent/ # 后端(Python)
│ ├── cli/ # CLI 包 —— 交互式 TUI + 子命令
│ ├── api_server.py # FastAPI server —— runs、sessions、upload、swarm、SSE
-│ ├── mcp_server.py # MCP server —— 80 个工具,面向 OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server —— 81 个工具,面向 OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent 内核
@@ -1727,7 +1727,7 @@ Vibe-Trading/
│ │ ├── memory/ # 跨 session 持久记忆
│ │ │ └── persistent.py # 基于文件的记忆(~/.vibe-trading/memory/)
│ │ │
-│ │ ├── tools/ # 111 个自动发现的 agent 工具
+│ │ ├── tools/ # 112 个自动发现的 agent 工具
│ │ │ ├── backtest_tool.py # 运行回测
│ │ │ ├── remember_tool.py # 跨 session 记忆(save/recall/forget)
│ │ │ ├── skill_writer_tool.py # skill CRUD(save/patch/delete/file)
diff --git a/agent/SKILL.md b/agent/SKILL.md
index f60263d11..268d4bc7d 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 (80)
+## Available MCP Tools (81)
| Tool | Description | API Key |
|------|-------------|---------|
@@ -186,6 +186,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 |
+| `adapt_strategy` | Prepare an evidence-gated child strategy for generation and its own backtest |
| `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 |
diff --git a/agent/api_server.py b/agent/api_server.py
index 8477c8745..28f0006ef 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -220,6 +220,8 @@ register_custom_provider_routes(app, require_local_or_auth, require_settings_wri
from src.api.pixel_office_routes import register_pixel_office_routes # noqa: E402
register_pixel_office_routes(app, require_local_or_auth, require_settings_write_auth)
+from src.api.strategy_adaptation_routes import register_strategy_adaptation_routes # noqa: E402
+register_strategy_adaptation_routes(app, require_settings_write_auth)
# --- Uploads ---
from src.api.uploads_routes import register_uploads_routes # noqa: E402
diff --git a/agent/cli/commands/strategy_evidence.py b/agent/cli/commands/strategy_evidence.py
index 6d3528c8a..ec566be84 100644
--- a/agent/cli/commands/strategy_evidence.py
+++ b/agent/cli/commands/strategy_evidence.py
@@ -63,7 +63,7 @@ def _cmd_refresh(args: argparse.Namespace) -> int:
manifest = getattr(args, "strategy_evidence_manifest", None)
try:
- envelope = refresh_strategy_evidence_core(manifest_path=manifest)
+ envelope = refresh_strategy_evidence_core(manifest_path=manifest, scope=getattr(args, "scope", "all"))
except ValueError as exc:
message = str(exc)
if getattr(args, "strategy_evidence_json", False):
@@ -90,7 +90,25 @@ def _cmd_refresh(args: argparse.Namespace) -> int:
return 0
+def _cmd_adapt(args: argparse.Namespace) -> int:
+ """Prepare an adaptation; generation and backtesting use the returned plan."""
+ from pathlib import Path
+ from src.strategy_discovery.adaptation_workflow import prepare_adaptation
+
+ try:
+ result = prepare_adaptation(strategy_id=args.strategy_id, name=args.name,
+ universe=args.universe,
+ config=json.loads(Path(args.config).read_text()),
+ position_sizing=args.position_sizing)
+ except (OSError, ValueError, TypeError) as exc:
+ print(json.dumps({"status": "error", "error": str(exc)}))
+ return 2
+ print(json.dumps(result, ensure_ascii=False, indent=2))
+ return 0
+
+
_DISPATCH = {
+ "adapt": _cmd_adapt,
"refresh": _cmd_refresh,
}
@@ -110,8 +128,8 @@ def add_subparser(subparsers: Any) -> argparse.ArgumentParser:
"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 "
+ "Prepare strategy adaptations and refresh their evidence. "
+ "Querying evidence stays with the agent tools "
"(list_strategies / query_strategies / get_strategy_evidence)."
),
)
@@ -142,6 +160,15 @@ def add_subparser(subparsers: Any) -> argparse.ArgumentParser:
help="Emit the machine-readable envelope instead of a summary",
)
+ p_refresh.add_argument("--scope", choices=["all", "strategies"], default="all",
+ help="Replace all evidence, or only successful named strategies")
+ p_adapt = sub.add_parser("adapt", help="Prepare a child strategy for generation and backtest")
+ p_adapt.add_argument("--strategy-id", required=True)
+ p_adapt.add_argument("--name", required=True)
+ p_adapt.add_argument("--universe", required=True)
+ p_adapt.add_argument("--config", required=True, help="JSON backtest config with codes and dates")
+ p_adapt.add_argument("--position-sizing")
+
_STRATEGY_EVIDENCE_PARSER = parser
return parser
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index b78efa586..b7402375b 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -1398,7 +1398,21 @@ def get_strategy_evidence(strategy_id: str, regime: str | None = None) -> str:
@mcp.tool
-def refresh_strategy_evidence(manifest_path: str | None = None, runs: list | None = None) -> str:
+def adapt_strategy(strategy_id: str, name: str, universe: str, config: dict, position_sizing: str | None = None) -> str:
+ """Prepare a child from fresh adequate SDM evidence, preserving signal logic.
+
+ Returns description and a bound run_dir. Load strategy-generate, write the
+ child's code, backtest there, then refresh its evidence with scope=strategies.
+ Does not generate code or run a backtest by itself, or copy parent metrics.
+ """
+ return _strategy_discovery_execute("adapt_strategy", {
+ "strategy_id": strategy_id, "name": name, "universe": universe,
+ "config": config, "position_sizing": position_sizing,
+ })
+
+
+def refresh_strategy_evidence(manifest_path: str | None = None, runs: list | None = None, scope: str = "all") -> str:
"""Rebuild the strategy-discovery evidence cache from backtest run artifacts.
WRITE tool with disposable-cache-only scope: it replaces the facade-owned
@@ -1420,10 +1434,11 @@ def refresh_strategy_evidence(manifest_path: str | None = None, runs: list | Non
Args:
manifest_path: Path to the JSON manifest file (see above).
runs: Inline run specs (see above).
+ scope: all replaces the whole cache; strategies updates successful named strategies only.
"""
return _strategy_discovery_execute(
"refresh_strategy_evidence",
- {"manifest_path": manifest_path, "runs": runs},
+ {"manifest_path": manifest_path, "runs": runs, "scope": scope},
)
diff --git a/agent/src/agent/write_targets.py b/agent/src/agent/write_targets.py
index ec2cb912f..3a7e6f0bd 100644
--- a/agent/src/agent/write_targets.py
+++ b/agent/src/agent/write_targets.py
@@ -10,8 +10,8 @@ orchestrator.
State stays on the loop: ``written_files`` is passed in and mutated in
place by ``record_written_target``; the provenance identity fields are
-read at delegation time in ``loop.py``. Behavior is unchanged — every
-branch condition, regex, and message string moved verbatim.
+read at delegation time in ``loop.py``. The extraction preserved behavior. Prepared adaptation runs now also receive
+writer provenance when their code is written from another active run.
"""
from __future__ import annotations
@@ -55,9 +55,28 @@ def record_written_target(
try:
relative = resolved.relative_to(run_root).as_posix()
except ValueError:
- return
+ relative = ""
if relative not in {"config.json", "code/signal_engine.py"}:
- return
+ # Adaptation code is written to a separate, prepared run. Resolve its
+ # identity from that run's own config; never stamp the active run's
+ # code identity onto a file written somewhere else.
+ candidate = resolved.parent.parent if resolved.name == "signal_engine.py" and resolved.parent.name == "code" else resolved.parent
+ if resolved.name not in {"config.json", "signal_engine.py"}:
+ return
+ try:
+ from src.tools.path_utils import safe_run_dir
+
+ candidate = safe_run_dir(str(candidate))
+ config = json.loads((candidate / "config.json").read_text(encoding="utf-8"))
+ token = config["strategy_adaptation"]["token"]
+ if not isinstance(token, str) or candidate.name != f"adaptation-{token}":
+ return
+ relative = resolved.relative_to(candidate).as_posix()
+ if relative not in {"config.json", "code/signal_engine.py"}:
+ return
+ run_root = candidate
+ except (OSError, ValueError, KeyError, TypeError):
+ return
metadata_path = run_root / "strategy_provenance.json"
try:
diff --git a/agent/src/api/strategy_adaptation_routes.py b/agent/src/api/strategy_adaptation_routes.py
new file mode 100644
index 000000000..e29b4f531
--- /dev/null
+++ b/agent/src/api/strategy_adaptation_routes.py
@@ -0,0 +1,38 @@
+"""Authenticated strategy adaptation and evidence refresh entry points."""
+
+from typing import Any
+
+from fastapi import Depends, FastAPI, HTTPException
+from pydantic import BaseModel, ConfigDict
+
+
+class AdaptationRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ strategy_id: str
+ name: str
+ universe: str
+ config: dict[str, Any]
+ position_sizing: str | None = None
+
+
+class EvidenceRefreshRequest(BaseModel):
+ runs: list[dict[str, Any]]
+
+
+def register_strategy_adaptation_routes(app: FastAPI, write_auth) -> None:
+ """Mount mutation routes behind the settings-write guard."""
+
+ @app.post("/api/strategy-adaptations", dependencies=[Depends(write_auth)])
+ def prepare(payload: AdaptationRequest):
+ from src.strategy_discovery.adaptation_workflow import prepare_adaptation
+
+ try:
+ return prepare_adaptation(**payload.model_dump())
+ except (ValueError, TypeError) as exc:
+ raise HTTPException(400, str(exc)) from exc
+
+ @app.post("/api/strategy-adaptations/evidence", dependencies=[Depends(write_auth)])
+ def refresh(payload: EvidenceRefreshRequest):
+ from src.tools.strategy_discovery_tool import refresh_strategy_evidence_core
+
+ return refresh_strategy_evidence_core(runs=payload.runs, scope="strategies")
diff --git a/agent/src/skills/strategy-discovery/SKILL.md b/agent/src/skills/strategy-discovery/SKILL.md
index ad4e4c29b..4181a71c8 100644
--- a/agent/src/skills/strategy-discovery/SKILL.md
+++ b/agent/src/skills/strategy-discovery/SKILL.md
@@ -12,7 +12,7 @@ Strategy Discovery is the single entry point for two questions: **what strategie
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 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).
+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`, writes only the disposable cache: it rebuilds ONLY the disposable evidence cache from local backtest run artifacts (see Populating & Refreshing Evidence and Composition Guarantee).
## When to Use
@@ -24,7 +24,7 @@ Decision tree for routing user requests:
- 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`
-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.
+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. CLI: `vibe-trading strategy-evidence refresh --manifest <path> [--scope strategies]` runs the same refresh as the tool. `vibe-trading strategy-evidence adapt --strategy-id sdm:<id> --name <child> --universe <description> --config <json-path>` prepares an adaptation; queries stay with the agent tools. Do not invent flags or subcommands beyond that.
## Tools
@@ -210,3 +210,10 @@ An empty result is an answer, not an error: it means "no computed evidence exist
- **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.
+
+
+## Description-driven adaptation
+
+`adapt_strategy` accepts `(strategy_id, name, universe, config, position_sizing?)` and is the fifth tool and writes a new SDM child plus an immutable input/run binding. It requires adequate, fresh evidence belonging to the parent and refuses disabled/decayed parents. Read the parent's description and regime definitions with `get_strategy_evidence` first. Only name, universe and optional sizing change; the signal/entry/exit descriptions remain fixed. The child starts unvalidated with no metrics or inherited sign-off.
+
+Load `strategy-generate` and follow its adaptation workflow: generate the child's code in the assigned run, backtest, then `refresh_strategy_evidence(..., scope="strategies")`. This replaces only successful named strategies, not the whole cache. No background model call or live trading is started by preparation. REST preparation is `POST /api/strategy-adaptations`; `POST /api/strategy-adaptations/evidence` performs scoped refresh. The Web welcome screen offers “Adapt a registered strategy”.
diff --git a/agent/src/skills/strategy-generate/SKILL.md b/agent/src/skills/strategy-generate/SKILL.md
index 31fcb520b..cc11ad8aa 100644
--- a/agent/src/skills/strategy-generate/SKILL.md
+++ b/agent/src/skills/strategy-generate/SKILL.md
@@ -16,6 +16,14 @@ category: strategy
**You only need to write `signal_engine.py` and `config.json`. The `backtest` tool automatically handles data loading and backtest execution.**
+## Adapting a registered strategy
+
+1. Read `get_strategy_evidence(strategy_id="sdm:...")` for the parent's description and computed regime definitions. A stale, disabled, decayed or inadequately evidenced parent cannot be adapted.
+2. Call `adapt_strategy(strategy_id=..., name=..., universe=..., config=...)` with explicit codes and date window. Only name, universe and optional position sizing may change. Signal definition, entry and exit rules remain the parent's. Missing inputs require a question, never a fabricated metric or threshold.
+3. Use the returned assigned `run_dir` and seeded `config.json`. Generate the child's `code/signal_engine.py` from its description using the contract below; never copy a parent run's metrics. Preserve the bound codes, dates and `strategy_adaptation` metadata. Record model provenance through the normal write tool.
+4. Call `backtest(run_dir=...)`, inspect its artifacts, then `refresh_strategy_evidence(runs=[{"strategy_id": "sdm:<child>", "run_dir": "<assigned>"}], scope="strategies")`. This updates only successful named strategies and preserves the parent's evidence. Refresh refuses a different run or changed config/code/results against the run card.
+5. Read the child's evidence and report its actual quality, cost and decay warnings. A successful backtest is not adequate regime evidence or independent approval. An unchanged mathematical signal can legitimately generate identical code for another universe; hashes establish provenance, not semantic correctness of generated Python.
+
## Requirements Parsing
Extract the following from the user's description:
diff --git a/agent/src/strategy_discovery/adaptation_workflow.py b/agent/src/strategy_discovery/adaptation_workflow.py
new file mode 100644
index 000000000..caa57be72
--- /dev/null
+++ b/agent/src/strategy_discovery/adaptation_workflow.py
@@ -0,0 +1,160 @@
+"""Prepare a description-preserving child and validate its own backtest evidence."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import uuid
+from dataclasses import asdict
+from datetime import date
+from pathlib import Path
+from typing import Any
+
+from src.strategy_store.adaptation import AdaptationPatch, register_adaptation
+
+_DESCRIPTION_FIELDS = ("signal_definition", "entry_rules", "exit_rules", "position_sizing")
+
+
+def prepare_adaptation(
+ *, strategy_id: str, name: str, universe: str, config: dict[str, Any],
+ position_sizing: str | None = None, store=None, evidence_store=None,
+ today: date | None = None,
+) -> dict:
+ """Create a child, seed its config, and return the generation instructions.
+
+ Args:
+ strategy_id: Existing SDM strategy id, with its ``sdm:`` prefix.
+ name: New child's name.
+ universe: Description of the target universe.
+ config: Explicit backtest config including codes and the date window.
+ position_sizing: Optional allowed description change.
+ store: Injectable SDM store; defaults to the shared store.
+ evidence_store: Injectable evidence cache.
+ today: Reference date for the existing parent freshness gate.
+
+ Returns:
+ Child identity, description, assigned paths and next tool calls.
+
+ Raises:
+ ValueError: Invalid inputs or inadequate/stale parent evidence.
+ """
+ from src.config.paths import get_runtime_root
+ from src.strategy_discovery.evidence_store import EvidenceStore
+ from src.strategy_store._shared import get_store
+
+ if not isinstance(strategy_id, str) or not strategy_id.startswith("sdm:"):
+ raise ValueError("adaptation requires an sdm: strategy id; a factor is not a strategy")
+ for label, value in (("name", name), ("universe", universe)):
+ if not isinstance(value, str) or not value.strip() or len(value) > 500:
+ raise ValueError(f"{label} must be a non-empty string of at most 500 characters")
+ if position_sizing is not None and (not isinstance(position_sizing, str) or not position_sizing.strip()):
+ raise ValueError("position_sizing must be a non-empty description")
+ if not isinstance(config, dict):
+ raise ValueError("config must be a backtest configuration object")
+ config = json.loads(json.dumps(config, allow_nan=False))
+ if not isinstance(config.get("source"), str) or not config["source"].strip():
+ raise ValueError("config requires an explicit data source (for example auto or local)")
+ codes = config.get("codes")
+ if (not isinstance(codes, list) or not codes or len(codes) > 500
+ or any(not isinstance(code, str) or not code.strip() for code in codes)
+ or len(set(codes)) != len(codes)):
+ raise ValueError("config.codes must contain distinct non-empty instrument codes")
+ try:
+ start = date.fromisoformat(config["start_date"])
+ end = date.fromisoformat(config["end_date"])
+ except (ValueError, TypeError, KeyError) as exc:
+ raise ValueError("config requires ISO start_date and end_date") from exc
+ if start >= end:
+ raise ValueError("start_date must precede end_date")
+ from backtest.runner import BacktestConfigSchema
+
+ BacktestConfigSchema(**config)
+ store = store if store is not None else get_store()
+ evidence_store = evidence_store if evidence_store is not None else EvidenceStore()
+ parent_id = strategy_id.removeprefix("sdm:")
+ parent = store.get_artifact(parent_id)
+ if parent is None or not parent.signal_definition:
+ raise ValueError("parent strategy must have an explicit signal_definition")
+ token = uuid.uuid4().hex
+ run_dir = (get_runtime_root() / "runs" / f"adaptation-{token}").resolve()
+ config["strategy_adaptation"] = {"token": token, "parent_id": strategy_id}
+ description = {key: getattr(parent, key) for key in _DESCRIPTION_FIELDS}
+ if position_sizing is not None:
+ description["position_sizing"] = position_sizing
+ binding = {
+ "run_dir": str(run_dir), "parent_id": parent_id,
+ "codes": codes, "start_date": config["start_date"], "end_date": config["end_date"],
+ "strategy_adaptation": config["strategy_adaptation"], "description": description,
+ "universe": universe.strip(),
+ }
+ child_id = register_adaptation(
+ store, parent_id, AdaptationPatch(name=name.strip(), universe=universe.strip(), position_sizing=position_sizing),
+ parent_evidence=evidence_store.get_rows(strategy_id=strategy_id),
+ today=today or date.today(), run_binding=binding,
+ )
+ # Registration and binding are atomic. If disk creation fails, the child
+ # remains CREATED without evidence and cannot be refreshed from another run.
+ (run_dir / "code").mkdir(parents=True, exist_ok=False)
+ (run_dir / "config.json").write_text(json.dumps(config, ensure_ascii=False, indent=2) + "\n")
+ return {
+ "status": "ok", "strategy_id": f"sdm:{child_id}", "derived_from": strategy_id,
+ "artifact": asdict(store.get_artifact(child_id)), "run_dir": str(run_dir),
+ "parent_evidence": [asdict(row) for row in evidence_store.get_rows(strategy_id=strategy_id)],
+ "next_steps": [
+ "Load strategy-generate. Generate code/signal_engine.py in the assigned run_dir from the child's description; preserve signal_definition, entry_rules and exit_rules.",
+ "Run backtest with this run_dir. Do not reuse a parent's artifacts or alter the bound codes/date window/strategy_adaptation token.",
+ "Call refresh_strategy_evidence(runs=[{strategy_id: the child id, run_dir: this directory}], scope='strategies'). Report the child's own evidence quality and warnings, never the parent's metrics as the child's.",
+ ],
+ }
+
+
+def validate_adapted_run(strategy_id: str, run_dir: str | Path, *, store=None) -> None:
+ """Refuse evidence from another run or changed/unsealed child artifacts.
+
+ Hash checks bind the evidence to persisted backtest output. They do not
+ certify that generated Python implements its natural-language description.
+ """
+ if not strategy_id.startswith("sdm:"):
+ return
+ from src.strategy_store._shared import get_store
+
+ store = store if store is not None else get_store()
+ child_id = strategy_id.removeprefix("sdm:")
+ child = store.get_artifact(child_id)
+ if child is None or not child.derived_from:
+ return
+ binding = store.get_adaptation_binding(child_id)
+ if not binding:
+ raise ValueError("adapted strategy has no bound run; prepare a new adaptation before refreshing")
+ root = Path(run_dir).resolve()
+ if str(root) != binding["run_dir"] or child.run_dir != binding["run_dir"]:
+ raise ValueError("adaptation evidence must come from the child's assigned run_dir")
+ if child.derived_from != binding["parent_id"] or child.universe != binding["universe"]:
+ raise ValueError("adaptation identity changed after preparation")
+ if any(getattr(child, key) != value for key, value in binding["description"].items()):
+ raise ValueError("adaptation description changed after preparation")
+ if child.signal_engine_path != str(root / "code/signal_engine.py"):
+ raise ValueError("adaptation must use its own signal_engine.py")
+ try:
+ def read(relative):
+ path = root / relative
+ if not path.resolve().is_relative_to(root) or path.is_symlink():
+ raise ValueError("adaptation artifact escapes its run directory")
+ return path.read_bytes()
+
+ config = json.loads(read("config.json"))
+ for key in ("codes", "start_date", "end_date", "strategy_adaptation"):
+ if config.get(key) != binding[key]:
+ raise ValueError(f"adaptation config changed: {key}")
+ card = json.loads(read("run_card.json"))
+ manifest = {item["path"]: item["sha256"] for item in card["artifacts"]}
+ required = ("config.json", "code/signal_engine.py", "artifacts/metrics.csv",
+ "artifacts/equity.csv", "artifacts/trades.csv")
+ for relative in required:
+ digest = hashlib.sha256(read(relative)).hexdigest()
+ if digest != manifest.get(relative):
+ raise ValueError(f"adaptation artifact is not sealed by the run card: {relative}")
+ if card["reproducibility"].get("strategy_hash") != manifest["code/signal_engine.py"]:
+ raise ValueError("run card does not identify the child's strategy code")
+ except (OSError, KeyError, TypeError, json.JSONDecodeError) as exc:
+ raise ValueError("adaptation requires a complete run card and its unchanged backtest artifacts") from exc
diff --git a/agent/src/strategy_discovery/evidence_harness.py b/agent/src/strategy_discovery/evidence_harness.py
index 282831544..5eb987e51 100644
--- a/agent/src/strategy_discovery/evidence_harness.py
+++ b/agent/src/strategy_discovery/evidence_harness.py
@@ -586,7 +586,7 @@ def compute_evidence_for_run(
return rows
-def rebuild_evidence(runs: Sequence[Mapping], store: EvidenceStore) -> dict:
+def rebuild_evidence(runs: Sequence[Mapping], store: EvidenceStore, *, scope: str = "all") -> dict:
"""Atomically replace the store contents from a sequence of run specs.
Each mapping needs ``strategy_id`` and ``run_dir``; an optional
@@ -605,12 +605,18 @@ def rebuild_evidence(runs: Sequence[Mapping], store: EvidenceStore) -> dict:
``all_rows`` still replaces (clears) the store: a rebuild is a full
statement of the evidence, not a patch.
+ ``scope="strategies"`` replaces only successful strategies' full regime
+ sets, preserving all other evidence and failed retries. The default
+ ``scope="all"`` retains the original full-rebuild semantics.
+
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.
"""
+ if scope not in {"all", "strategies"}:
+ raise ValueError("scope must be all or strategies")
skipped: list[dict] = []
all_rows: list[EvidenceRow] = []
ok_strategies: set[str] = set()
@@ -640,6 +646,9 @@ def rebuild_evidence(runs: Sequence[Mapping], store: EvidenceStore) -> dict:
)
continue
try:
+ from src.strategy_discovery.adaptation_workflow import validate_adapted_run
+
+ validate_adapted_run(strategy_id, run_dir)
gate_ok, gate_reason = check_run_hard_gates(run_dir)
if not gate_ok:
skipped.append({"run_dir": str(run_dir), "reason": gate_reason})
@@ -669,7 +678,12 @@ def rebuild_evidence(runs: Sequence[Mapping], store: EvidenceStore) -> dict:
all_rows.extend(rows)
ok_strategies.add(strategy_id)
- written = store.replace_rows(all_rows)
+ if scope == "strategies":
+ # Replace complete regime sets for successful named runs only. A bad
+ # retry cannot erase earlier valid evidence or another strategy's rows.
+ written = store.replace_rows(all_rows, strategy_ids=sorted(ok_strategies))
+ else:
+ 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 022521088..a210083da 100644
--- a/agent/src/strategy_discovery/evidence_store.py
+++ b/agent/src/strategy_discovery/evidence_store.py
@@ -267,10 +267,12 @@ class EvidenceStore:
count += 1
return count
- def replace_rows(self, rows: Sequence[EvidenceRow]) -> int:
+ def replace_rows(self, rows: Sequence[EvidenceRow], *, strategy_ids: Sequence[str] | None = None) -> int:
"""Atomically replace ALL evidence rows with ``rows``.
- DELETE-all + INSERT-all inside ONE ``_connect()`` context — a single
+ With strategy_ids, delete only those complete regime sets and reject
+ rows outside that scope. Otherwise replace the whole cache.
+ DELETE + INSERT 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
@@ -285,7 +287,13 @@ class EvidenceStore:
_validate_row_for_write(row)
count = 0
with self._connect() as conn:
- conn.execute(f"DELETE FROM {self.TABLE}")
+ if strategy_ids is None:
+ conn.execute(f"DELETE FROM {self.TABLE}")
+ else:
+ if any(row.strategy_id not in strategy_ids for row in materialized):
+ raise ValueError("row outside replacement strategy scope")
+ conn.executemany(f"DELETE FROM {self.TABLE} WHERE strategy_id = ?",
+ [(sid,) for sid in strategy_ids])
for row in materialized:
conn.execute(
_INSERT_SQL,
diff --git a/agent/src/strategy_discovery/facade.py b/agent/src/strategy_discovery/facade.py
index 3af77e393..e48ae1e2c 100644
--- a/agent/src/strategy_discovery/facade.py
+++ b/agent/src/strategy_discovery/facade.py
@@ -672,6 +672,20 @@ class StrategyDiscoveryFacade:
"found": bool(rows),
"rows": rendered,
}
+ if strategy_id.startswith("sdm:"):
+ try:
+ sdm = self._get_sdm_store()
+ artifact = sdm.get_artifact(strategy_id.split(":", 1)[1]) if sdm else None
+ except Exception:
+ logger.warning("SDM description unavailable", exc_info=True)
+ artifact = None
+ if artifact is not None:
+ envelope["description"] = {
+ key: getattr(artifact, key, None) for key in (
+ "name", "universe", "signal_definition", "entry_rules", "exit_rules",
+ "position_sizing", "derived_from", "run_dir", "signal_engine_path",
+ )
+ }
if lifecycle_note is not None:
envelope["lifecycle_note"] = lifecycle_note
if not rows:
diff --git a/agent/src/strategy_discovery/guard.py b/agent/src/strategy_discovery/guard.py
index 45e71f9fe..51c3b5795 100644
--- a/agent/src/strategy_discovery/guard.py
+++ b/agent/src/strategy_discovery/guard.py
@@ -2,12 +2,12 @@
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 discovery tools (three read-only plus the refresh write tool)
+whether the discovery tools (three read-only plus the refresh and adaptation write 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. The routing block names all four tools,
-so the guard covers all four: advertising ``refresh_strategy_evidence``
+failure mode of the rejected #896. The routing block names all five tools,
+so the guard covers all five: advertising ``refresh_strategy_evidence``
while only the three reads register would reintroduce the phantom-tool
failure the guard exists to prevent.
@@ -20,13 +20,14 @@ from __future__ import annotations
from typing import Any
#: The discovery tools advertised by the routing block: the three read-only
-#: query tools plus the refresh write tool. All four must be registered
+#: query tools plus the refresh and adaptation write tools. All five must be registered
#: before any routing text is emitted (atomic advertisement).
STRATEGY_DISCOVERY_TOOLS = (
"list_strategies",
"query_strategies",
"get_strategy_evidence",
"refresh_strategy_evidence",
+ "adapt_strategy",
)
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:
@@ -34,6 +35,7 @@ ROUTING_BLOCK: str = """**Strategy Discovery** — user asks what strategies exi
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
+5. `adapt_strategy(strategy_id=..., name=..., universe=..., config=...)` — prepare a child from adequate fresh parent evidence, load strategy-generate, write its own code, backtest in its assigned directory, then refresh only the child with scope="strategies". Signal/entry/exit definitions stay fixed; NEVER inherit parent performance.
Never recommend a strategy whose supporting regime evidence is missing or insufficient."""
diff --git a/agent/src/strategy_store/adaptation.py b/agent/src/strategy_store/adaptation.py
index 508649ee5..ea5466086 100644
--- a/agent/src/strategy_store/adaptation.py
+++ b/agent/src/strategy_store/adaptation.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from dataclasses import dataclass, replace
from datetime import date
+from pathlib import Path
from typing import TYPE_CHECKING, Protocol, Sequence
from src.strategy_store.models import (
@@ -33,7 +34,7 @@ class AdaptationPatch:
class _ArtifactStore(Protocol):
def get_artifact(self, artifact_id: str) -> Artifact | None: ...
- def register_artifact(self, artifact: Artifact) -> str: ...
+ def register_artifact(self, artifact: Artifact, **kwargs) -> str: ...
def adapt_artifact(parent: Artifact, patch: AdaptationPatch) -> Artifact:
@@ -77,6 +78,7 @@ def adapt_artifact(parent: Artifact, patch: AdaptationPatch) -> Artifact:
derived_from=parent.id,
status=ArtifactStatus.CREATED,
run_dir=None,
+ signal_engine_path=None,
created_at="",
updated_at="",
disabled_at=None,
@@ -97,6 +99,7 @@ def register_adaptation(
*,
parent_evidence: "Sequence[EvidenceRow]",
today: date,
+ run_binding: dict | None = None,
) -> str:
"""Persist an adapted child through the strategy store. Returns the new id.
@@ -112,6 +115,8 @@ def register_adaptation(
patch: Description-driven changes; signal fields are not on this type.
parent_evidence: Evidence rows computed for *parent_id*.
today: Reference date the decay verdict is taken against.
+ run_binding: Optional prepared run contract, persisted atomically with
+ the child by the SQLite store; omitted for description-only use.
Returns:
The new child artifact's id.
@@ -126,6 +131,10 @@ def register_adaptation(
if parent is None:
raise AdaptationError(f"parent artifact {parent_id!r} not found")
+ if parent.status in (ArtifactStatus.DECAYED, ArtifactStatus.DISABLED):
+ raise AdaptationError("a decayed or disabled parent cannot be adapted")
+ if any(row.strategy_id != f"sdm:{parent_id}" for row in parent_evidence):
+ raise AdaptationError("evidence must belong to the parent strategy")
blockers = parent_adaptation_blockers(parent_evidence, today)
if blockers:
raise AdaptationError(
@@ -133,4 +142,8 @@ def register_adaptation(
)
child = adapt_artifact(parent, patch)
+ if run_binding is not None:
+ child = replace(child, run_dir=run_binding["run_dir"],
+ signal_engine_path=str(Path(run_binding["run_dir"]) / "code/signal_engine.py"))
+ return store.register_artifact(child, adaptation_binding=run_binding)
return store.register_artifact(child)
diff --git a/agent/src/strategy_store/sqlite_store.py b/agent/src/strategy_store/sqlite_store.py
index 26b866914..a8f9651b1 100644
--- a/agent/src/strategy_store/sqlite_store.py
+++ b/agent/src/strategy_store/sqlite_store.py
@@ -216,6 +216,11 @@ class SqliteStrategyStore:
created_at TEXT NOT NULL
);
+ CREATE TABLE IF NOT EXISTS adaptation_bindings (
+ artifact_id TEXT PRIMARY KEY REFERENCES artifacts(id) ON DELETE CASCADE,
+ contract TEXT NOT NULL
+ );
+
CREATE TABLE IF NOT EXISTS decay_snapshots (
id INTEGER PRIMARY KEY AUTOINCREMENT,
artifact_id TEXT NOT NULL
@@ -370,7 +375,7 @@ class SqliteStrategyStore:
# -- Artifact CRUD ------------------------------------------------------
@_synchronized
- def register_artifact(self, artifact: Artifact) -> str:
+ def register_artifact(self, artifact: Artifact, *, adaptation_binding: dict | None = None) -> str:
"""Register a new artifact. Returns the artifact_id."""
# A brand-new record has no prior validation history, so its implicit
# "current" state is UNVALIDATED — registering directly with
@@ -436,6 +441,11 @@ class SqliteStrategyStore:
artifact.validation_date,
),
)
+ if adaptation_binding is not None:
+ self._conn.execute(
+ "INSERT INTO adaptation_bindings VALUES (?, ?)",
+ (artifact_id, _json_dumps(adaptation_binding)),
+ )
except sqlite3.IntegrityError as exc:
if "artifacts.name" in str(exc):
raise ValueError(
@@ -453,6 +463,14 @@ class SqliteStrategyStore:
).fetchone()
return self._row_to_artifact(row) if row else None
+ @_synchronized
+ def get_adaptation_binding(self, artifact_id: str) -> dict | None:
+ """Return the immutable input contract of a prepared adaptation."""
+ row = self._conn.execute(
+ "SELECT contract FROM adaptation_bindings WHERE artifact_id = ?", (artifact_id,)
+ ).fetchone()
+ return json.loads(row["contract"]) if row else None
+
@_synchronized
def list_artifacts(
self,
diff --git a/agent/src/tools/strategy_discovery_tool.py b/agent/src/tools/strategy_discovery_tool.py
index 5e530af59..39a2245c4 100644
--- a/agent/src/tools/strategy_discovery_tool.py
+++ b/agent/src/tools/strategy_discovery_tool.py
@@ -1,7 +1,7 @@
"""Strategy-discovery agent tools: evidence-gated discovery surface.
-Four tools — ``list_strategies`` / ``query_strategies`` /
-``get_strategy_evidence`` / ``refresh_strategy_evidence`` — expose the
+Five tools — ``list_strategies`` / ``query_strategies`` /
+``get_strategy_evidence`` / ``refresh_strategy_evidence`` / ``adapt_strategy`` 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
@@ -13,7 +13,8 @@ The first three tools are read-only. The fourth,
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.
+credentials. ``adapt_strategy`` prepares a new SDM child for the existing
+generate/backtest workflow and binds its own evidence inputs.
The facade is constructed lazily inside each ``execute()`` (never at import
time), parameter types are coerced/validated defensively (bad input yields
@@ -583,6 +584,7 @@ def refresh_strategy_evidence_core(
*,
manifest_path: str | None = None,
runs: list | None = None,
+ scope: str = "all",
) -> dict:
"""Shared refresh core for the agent tool and the CLI (one code path).
@@ -617,7 +619,20 @@ def refresh_strategy_evidence_core(
)
entries = runs
+ if scope not in {"all", "strategies"}:
+ raise ValueError("scope must be all or strategies")
specs, skipped = validate_refresh_entries(entries)
+ from src.strategy_discovery.adaptation_workflow import validate_adapted_run
+
+ validated = []
+ for spec in specs:
+ try:
+ validate_adapted_run(spec["strategy_id"], spec["run_dir"])
+ except ValueError as exc:
+ skipped.append({"run_dir": spec["run_dir"], "reason": str(exc)})
+ else:
+ validated.append(spec)
+ specs = validated
if not specs:
# Nothing admissible to rebuild from. Do NOT call rebuild_evidence:
# an empty rebuild clears the store, and wiping the cache because
@@ -632,7 +647,7 @@ def refresh_strategy_evidence_core(
from src.strategy_discovery import EvidenceStore, rebuild_evidence
- result = dict(rebuild_evidence(specs, EvidenceStore()))
+ result = dict(rebuild_evidence(specs, EvidenceStore(), scope=scope))
result["runs"] = len(entries)
result["skipped"] = skipped + list(result.get("skipped", []))
return result
@@ -643,9 +658,9 @@ class RefreshStrategyEvidenceTool(BaseTool):
name = "refresh_strategy_evidence"
description = (
- "Rebuild the strategy-discovery evidence cache from real backtest "
+ "Refresh 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 "
+ "the facade-owned evidence cache (default scope=all). Set scope=strategies to replace only successful named strategies, preserving other evidence. It "
"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 '
@@ -657,6 +672,10 @@ class RefreshStrategyEvidenceTool(BaseTool):
parameters = {
"type": "object",
"properties": {
+ "scope": {
+ "type": "string", "enum": ["all", "strategies"], "default": "all",
+ "description": "Use strategies after adaptation to preserve the parent's and other strategies' evidence.",
+ },
"manifest_path": {
"type": "string",
"description": (
@@ -696,7 +715,7 @@ class RefreshStrategyEvidenceTool(BaseTool):
)
try:
result = refresh_strategy_evidence_core(
- manifest_path=manifest_path, runs=runs
+ manifest_path=manifest_path, runs=runs, scope=kwargs.get("scope", "all")
)
except ValueError as exc:
return _err(str(exc))
@@ -706,3 +725,40 @@ class RefreshStrategyEvidenceTool(BaseTool):
logger.exception("refresh_strategy_evidence failed")
return _err("refresh_strategy_evidence failed internally; see server logs")
return _envelope(result)
+
+
+class AdaptStrategyTool(BaseTool):
+ """Prepare a child for the existing strategy-generate/backtest workflow."""
+
+ name = "adapt_strategy"
+ description = (
+ "Prepare a new SDM child from a strategy with adequate, non-stale evidence. "
+ "Preserves signal, entry and exit definitions; only universe, name and sizing "
+ "may change. Returns the description and assigned run directory. Then load "
+ "strategy-generate, write the child's own SignalEngine, backtest it and call "
+ "refresh_strategy_evidence with scope=strategies. Never inherits parent metrics."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "strategy_id": {"type": "string", "description": "Parent sdm: id from list_strategies."},
+ "name": {"type": "string"},
+ "universe": {"type": "string", "description": "Target universe description."},
+ "config": {"type": "object", "description": "Backtest config with explicit codes, start_date and end_date; no guessed costs or data inputs."},
+ "position_sizing": {"type": "string", "description": "Optional new sizing description; omit to preserve parent's."},
+ },
+ "required": ["strategy_id", "name", "universe", "config"],
+ }
+ is_readonly = False
+
+ def execute(self, **kwargs: Any) -> str:
+ from src.strategy_discovery.adaptation_workflow import prepare_adaptation
+
+ try:
+ result = prepare_adaptation(**{key: kwargs[key] for key in self.parameters["properties"] if key in kwargs})
+ return _envelope(result)
+ except (ValueError, TypeError) as exc:
+ return _err(str(exc))
+ except Exception:
+ logger.exception("strategy adaptation preparation failed")
+ return _err("strategy adaptation preparation failed; see server logs")
diff --git a/agent/tests/test_mcp_new_tools.py b/agent/tests/test_mcp_new_tools.py
index b8ca46ac8..eff22d16c 100644
--- a/agent/tests/test_mcp_new_tools.py
+++ b/agent/tests/test_mcp_new_tools.py
@@ -46,6 +46,7 @@ KNOWN_MUTATING_MCP_TOOLS = frozenset(
"alpha_bench",
"backtest",
"refresh_strategy_evidence",
+ "adapt_strategy",
"run_swarm",
"start_research_goal",
"trading_select_connection",
diff --git a/agent/tests/test_strategy_adaptation_workflow.py b/agent/tests/test_strategy_adaptation_workflow.py
new file mode 100644
index 000000000..dcce7b74a
--- /dev/null
+++ b/agent/tests/test_strategy_adaptation_workflow.py
@@ -0,0 +1,233 @@
+"""A prepared child earns evidence from its own sealed backtest only."""
+
+import json
+import shutil
+from dataclasses import replace
+from datetime import date
+from pathlib import Path
+
+import pytest
+
+from src.strategy_discovery.adaptation_workflow import prepare_adaptation, validate_adapted_run
+from src.strategy_discovery.evidence_store import EvidenceStore
+from src.strategy_discovery.models import EvidenceRow
+from src.strategy_store.models import Artifact, ArtifactStatus, ArtifactType, ValidationStatus
+from src.strategy_store.sqlite_store import SqliteStrategyStore
+from src.tools.strategy_discovery_tool import refresh_strategy_evidence_core
+
+
+def context(tmp_path, monkeypatch):
+ import src.strategy_store._shared as shared
+
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path))
+ monkeypatch.setenv("VIBE_TRADING_STRATEGY_DISCOVERY_DB_PATH", str(tmp_path / "evidence.db"))
+ store = SqliteStrategyStore(tmp_path / "sdm.db")
+ monkeypatch.setattr(shared, "_store", store)
+ parent = Artifact(id="parent", type=ArtifactType.STRATEGY, name="parent", universe="old",
+ signal_definition="Alternate 5 held bars and 5 flat bars", entry_rules="next open",
+ exit_rules="next open", position_sizing="full position", run_dir="/parent/run",
+ signal_engine_path="/parent/code.py", status=ArtifactStatus.ACTIVE)
+ store.register_artifact(parent)
+ evidence = EvidenceStore(tmp_path / "evidence.db")
+ evidence.upsert_rows([EvidenceRow(strategy_id="sdm:parent", regime="bull_market",
+ trades_in_regime=40, date_ranges=("2023-01 to 2025-12",),
+ evidence_quality="adequate", provenance="parent-run")])
+ return store, evidence
+
+
+def prepare(context, **overrides):
+ values = dict(strategy_id="sdm:parent", name="child", universe="new",
+ config={"codes": ["AAPL.US"], "start_date": "2024-01-01", "end_date": "2024-02-08",
+ "source": "local", "initial_cash": 100000, "commission": 0.001},
+ store=context[0], evidence_store=context[1], today=date(2026, 1, 31))
+ values.update(overrides)
+ return prepare_adaptation(**values)
+
+
+def seal_fixture(result):
+ from backtest.run_card import write_run_card
+ from tests.test_strategy_discovery_harness import _write_run_fixture
+
+ root = Path(result["run_dir"])
+ fixture = _write_run_fixture(root / "fixture")
+ shutil.copytree(fixture / "artifacts", root / "artifacts")
+ shutil.copyfile(fixture / "state.json", root / "state.json")
+ (root / "code/signal_engine.py").write_text("class SignalEngine: pass\n")
+ write_run_card(root, json.loads((root / "config.json").read_text()), {"trade_count": 9},
+ strategy_path=root / "code/signal_engine.py")
+ return root
+
+
+def test_child_starts_without_evidence_attestation_or_parent_code(context):
+ result = prepare(context)
+ child = context[0].get_artifact(result["strategy_id"].removeprefix("sdm:"))
+ assert child.derived_from == "parent"
+ assert child.signal_definition == context[0].get_artifact("parent").signal_definition
+ assert child.validation_status == ValidationStatus.UNVALIDATED
+ assert child.approver is None and child.model_version is None
+ assert context[1].get_rows(strategy_id=result["strategy_id"]) == []
+ assert child.signal_engine_path.startswith(result["run_dir"])
+ assert not Path(child.signal_engine_path).exists()
+ assert result["parent_evidence"][0]["provenance"] == "parent-run"
+
+
[email protected]("change", ["stale", "insufficient", "disabled", "factor", "wrong-parent"])
+def test_parent_refusals_leave_no_child(context, change):
+ store, evidence = context
+ parent = store.get_artifact("parent")
+ if change == "disabled":
+ store.update_status("parent", ArtifactStatus.DISABLED)
+ elif change == "factor":
+ store.update_artifact(replace(parent, type=ArtifactType.FACTOR))
+ else:
+ row = evidence.get_rows()[0]
+ updates = {"stale": {"date_ranges": ("2020-01 to 2020-12",)},
+ "insufficient": {"evidence_quality": "insufficient"},
+ "wrong-parent": {"strategy_id": "sdm:someone-else"}}[change]
+ evidence.replace_rows([replace(row, **updates)])
+ with pytest.raises(ValueError):
+ prepare(context)
+ assert len(store.list_artifacts()) == 1
+
+
+def test_scoped_refresh_retains_parent_and_reports_childs_own_quality(context):
+ result = prepare(context)
+ root = seal_fixture(result)
+ before = context[1].get_rows(strategy_id="sdm:parent")
+ validate_adapted_run(result["strategy_id"], root)
+ output = refresh_strategy_evidence_core(runs=[{"strategy_id": result["strategy_id"], "run_dir": str(root)}], scope="strategies")
+ assert output["rows"] > 0, output
+ assert context[1].get_rows(strategy_id="sdm:parent") == before
+ rows = context[1].get_rows(strategy_id=result["strategy_id"])
+ assert all(row.provenance != "parent-run" for row in rows)
+ assert all(row.evidence_quality != "adequate" for row in rows)
+
+
[email protected]("mutation", ["other-run", "dates", "codes", "description", "code", "equity", "failed", "no-card", "symlink"])
+def test_alternate_or_changed_run_cannot_be_adopted(context, tmp_path, mutation):
+ result = prepare(context)
+ root = seal_fixture(result)
+ if mutation == "other-run":
+ other = tmp_path / "runs/other"
+ shutil.copytree(root, other)
+ root = other
+ elif mutation in {"dates", "codes"}:
+ config = json.loads((root / "config.json").read_text())
+ config["start_date" if mutation == "dates" else "codes"] = "2020-01-01" if mutation == "dates" else ["MSFT.US"]
+ (root / "config.json").write_text(json.dumps(config))
+ elif mutation == "description":
+ child = context[0].get_artifact(result["strategy_id"].removeprefix("sdm:"))
+ context[0].update_artifact(replace(child, signal_definition="different"))
+ elif mutation in {"code", "equity"}:
+ path = root / ("code/signal_engine.py" if mutation == "code" else "artifacts/equity.csv")
+ path.write_text(path.read_text() + "\nchanged\n")
+ elif mutation == "failed":
+ (root / "state.json").write_text('{"status":"failed"}')
+ elif mutation == "no-card":
+ (root / "run_card.json").unlink()
+ elif mutation == "symlink":
+ path = root / "artifacts/equity.csv"
+ other = tmp_path / "elsewhere.csv"
+ path.rename(other)
+ path.symlink_to(other)
+ before = context[1].get_rows()
+ output = refresh_strategy_evidence_core(runs=[{"strategy_id": result["strategy_id"], "run_dir": str(root)}], scope="strategies")
+ assert output["rows"] == 0 and output["skipped"], output
+ assert context[1].get_rows() == before
+
+
+def test_real_local_backtest_to_child_evidence(context, tmp_path):
+ """Real file loader, code generation write, subprocess engine and refresh; no network/model."""
+ import numpy as np
+ import pandas as pd
+ import yaml
+ from src.tools.backtest_tool import run_backtest
+ from src.tools.write_file_tool import WriteFileTool
+
+ config = {"source": "local", "codes": ["AAPL.US"], "start_date": "2024-01-01", "end_date": "2025-12-31",
+ "benchmark": "AAPL.US", "initial_cash": 100000, "commission": 0.001, "interval": "1D", "engine": "daily"}
+ result = prepare(context, config=config)
+ code = '''import numpy as np
+import pandas as pd
+class SignalEngine:
+ def generate(self, data_map):
+ return {code: pd.Series((np.arange(len(frame)) % 10 < 5).astype(float), index=frame.index) for code, frame in data_map.items()}
+'''
+ written = json.loads(WriteFileTool().execute(path=str(Path(result["run_dir"]) / "code/signal_engine.py"), content=code))
+ assert written["status"] == "ok"
+ index = pd.bdate_range(config["start_date"], config["end_date"])
+ close = 100 + np.arange(len(index)) * 0.1 + np.sin(np.arange(len(index)) / 5)
+ data_file = tmp_path / "synthetic.csv"
+ pd.DataFrame({"date": index, "open": close, "high": close + 1, "low": close - 1, "close": close, "volume": 100000}).to_csv(data_file, index=False)
+ local_config = Path.home() / ".vibe-trading/data-bridge/config.yaml"
+ local_config.parent.mkdir(parents=True, exist_ok=True)
+ local_config.write_text(yaml.safe_dump({"sources": [{"symbol": "AAPL.US", "type": "csv", "path": str(data_file)}]}))
+ try:
+ backtest = json.loads(run_backtest(result["run_dir"]))
+ assert backtest["status"] == "ok", backtest
+ output = refresh_strategy_evidence_core(runs=[{"strategy_id": result["strategy_id"], "run_dir": result["run_dir"]}], scope="strategies")
+ assert output["rows"] > 0 and not output["skipped"], output
+ assert context[1].get_rows(strategy_id="sdm:parent")[0].provenance == "parent-run"
+ finally:
+ local_config.unlink(missing_ok=True)
+
+
+def test_generated_child_code_records_current_model_without_touching_active_run(context, tmp_path):
+ from types import SimpleNamespace
+ from src.agent.write_targets import record_written_target
+
+ result = prepare(context)
+ path = Path(result["run_dir"]) / "code/signal_engine.py"
+ path.write_text("class SignalEngine: pass\n")
+ active = tmp_path / "runs/active"
+ active.mkdir()
+ record_written_target({"path": str(path)}, written_files=set(), run_dir=str(active),
+ llm_runtime=SimpleNamespace(provider="test-provider"),
+ active_model_id="actual-response-model", active_model_source="response")
+ provenance = json.loads((path.parent.parent / "strategy_provenance.json").read_text())
+ assert provenance["files"]["code/signal_engine.py"]["model_id"] == "actual-response-model"
+ assert not (active / "strategy_provenance.json").exists()
+ elsewhere = tmp_path / "elsewhere/code"
+ elsewhere.mkdir(parents=True)
+ record_written_target({"path": str(elsewhere / "signal_engine.py")}, written_files=set(), run_dir=str(active),
+ llm_runtime=SimpleNamespace(provider="test-provider"),
+ active_model_id="actual-response-model", active_model_source="response")
+ assert not (elsewhere.parent / "strategy_provenance.json").exists()
+
+
+def test_api_auth_and_cli_prepare_share_child_contract(context, tmp_path, capsys):
+ from fastapi import FastAPI, HTTPException
+ from fastapi.testclient import TestClient
+ from cli import _legacy
+ from src.api.strategy_adaptation_routes import register_strategy_adaptation_routes
+
+ # API and CLI use the actual clock. Keep their parent's evidence non-stale.
+ row = context[1].get_rows()[0]
+ context[1].replace_rows([replace(row, date_ranges=(f"2023-01 to {date.today():%Y-%m}",))])
+ allow = False
+
+ def auth():
+ if not allow:
+ raise HTTPException(401, "auth required")
+
+ app = FastAPI()
+ register_strategy_adaptation_routes(app, auth)
+ client = TestClient(app)
+ config = {"source": "local", "codes": ["AAPL.US"], "start_date": "2024-01-01", "end_date": "2024-02-08"}
+ payload = {"strategy_id": "sdm:parent", "name": "api child", "universe": "new", "config": config}
+ assert client.post("/api/strategy-adaptations", json=payload).status_code == 401
+ assert client.post("/api/strategy-adaptations/evidence", json={"runs": []}).status_code == 401
+ allow = True
+ response = client.post("/api/strategy-adaptations", json=payload)
+ assert response.status_code == 200, response.text
+ child = response.json()
+ assert child["derived_from"] == "sdm:parent"
+ assert context[0].get_adaptation_binding(child["strategy_id"].removeprefix("sdm:"))["codes"] == config["codes"]
+ config_path = tmp_path / "input.json"
+ config_path.write_text(json.dumps(config))
+ code = _legacy.main(["strategy-evidence", "adapt", "--strategy-id", "sdm:parent", "--name", "cli child",
+ "--universe", "new", "--config", str(config_path)])
+ assert code == 0
+ output = json.loads(capsys.readouterr().out)
+ assert output["derived_from"] == "sdm:parent" and output["strategy_id"] != child["strategy_id"]
diff --git a/agent/tests/test_strategy_discovery_guard.py b/agent/tests/test_strategy_discovery_guard.py
index ae3ac5b44..c5fd2130b 100644
--- a/agent/tests/test_strategy_discovery_guard.py
+++ b/agent/tests/test_strategy_discovery_guard.py
@@ -37,6 +37,7 @@ EXPECTED_TOOLS = (
"query_strategies",
"get_strategy_evidence",
"refresh_strategy_evidence",
+ "adapt_strategy",
)
diff --git a/agent/tests/test_strategy_discovery_mcp.py b/agent/tests/test_strategy_discovery_mcp.py
index a5a018034..57a40f743 100644
--- a/agent/tests/test_strategy_discovery_mcp.py
+++ b/agent/tests/test_strategy_discovery_mcp.py
@@ -27,6 +27,7 @@ SD_TOOLS = (
"query_strategies",
"get_strategy_evidence",
"refresh_strategy_evidence",
+ "adapt_strategy",
)
@@ -96,6 +97,8 @@ class TestDelegation:
{"regime": "bear_market", "min_trades": 12, "cost_feasible": True},
),
("get_strategy_evidence", {"strategy_id": "alpha_zoo:a1", "regime": None}),
+ ("adapt_strategy", {"strategy_id": "sdm:p", "name": "child", "universe": "US", "config": {"codes": ["AAPL.US"]}}),
+ ("refresh_strategy_evidence", {"runs": [], "scope": "strategies"}),
],
)
def test_wrapper_delegates_to_registry_execute_with_own_name(
@@ -148,6 +151,8 @@ class TestDelegation:
fn = _unwrapped(name)
if name == "get_strategy_evidence":
result = fn(strategy_id="alpha_zoo:a1")
+ elif name == "adapt_strategy":
+ result = fn(strategy_id="sdm:p", name="child", universe="US", config={})
else:
result = fn()
payload = json.loads(result)
diff --git a/agent/tests/test_strategy_discovery_refresh.py b/agent/tests/test_strategy_discovery_refresh.py
index 719e05cf0..a41570ad9 100644
--- a/agent/tests/test_strategy_discovery_refresh.py
+++ b/agent/tests/test_strategy_discovery_refresh.py
@@ -98,7 +98,7 @@ class TestToolIdentity:
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["properties"].keys() == {"manifest_path", "runs", "scope"}
assert tool.parameters.get("required", []) == []
diff --git a/agent/tests/test_strategy_discovery_routing.py b/agent/tests/test_strategy_discovery_routing.py
index 8b5cf50df..e2141ccd8 100644
--- a/agent/tests/test_strategy_discovery_routing.py
+++ b/agent/tests/test_strategy_discovery_routing.py
@@ -39,6 +39,7 @@ SD_TOOLS = (
"query_strategies",
"get_strategy_evidence",
"refresh_strategy_evidence",
+ "adapt_strategy",
)
diff --git a/agent/tests/test_strategy_store_adaptation.py b/agent/tests/test_strategy_store_adaptation.py
index 260e2f63c..fec34a4de 100644
--- a/agent/tests/test_strategy_store_adaptation.py
+++ b/agent/tests/test_strategy_store_adaptation.py
@@ -42,13 +42,13 @@ TODAY_STALE = TODAY_FRESH + timedelta(days=180)
def _evidence(
- *, trades: int = 20, date_ranges: tuple[str, ...] = HEALTHY_RANGES
+ parent_id="art_parent", *, trades: int = 20, date_ranges: tuple[str, ...] = HEALTHY_RANGES
) -> tuple[EvidenceRow, ...]:
"""One evidence row for the parent, adequate and fresh unless told otherwise."""
coverage = coverage_days_from_ranges(date_ranges)
return (
EvidenceRow(
- strategy_id="sdm:parent",
+ strategy_id=f"sdm:{parent_id}",
regime="bull_market",
trades_in_regime=trades,
date_ranges=date_ranges,
@@ -107,7 +107,7 @@ class TestAdaptArtifact:
assert child.signal_definition == SIGNAL
assert child.entry_rules == ENTRY
assert child.exit_rules == EXIT
- assert child.signal_engine_path == ENGINE
+ assert child.signal_engine_path is None
assert child.theme == parent.theme
assert child.columns_required == parent.columns_required
assert child.decay_horizon == parent.decay_horizon
@@ -149,7 +149,7 @@ class TestRegisterAdaptation:
store,
parent_id,
AdaptationPatch(universe="SP500"),
- parent_evidence=_evidence(),
+ parent_evidence=_evidence(parent_id),
today=TODAY_FRESH,
)
child = store.get_artifact(child_id)
@@ -171,7 +171,7 @@ class TestRegisterAdaptation:
store,
parent_id,
AdaptationPatch(name="momentum_weekly"),
- parent_evidence=_evidence(),
+ parent_evidence=_evidence(parent_id),
today=TODAY_FRESH,
)
with pytest.raises(ValueError, match="already exists"):
@@ -179,7 +179,7 @@ class TestRegisterAdaptation:
store,
parent_id,
AdaptationPatch(name="momentum_weekly"),
- parent_evidence=_evidence(),
+ parent_evidence=_evidence(parent_id),
today=TODAY_FRESH,
)
@@ -194,7 +194,7 @@ class TestSqliteDerivedFromRoundtrip:
store,
parent_id,
AdaptationPatch(universe="SP500"),
- parent_evidence=_evidence(),
+ parent_evidence=_evidence(parent_id),
today=TODAY_FRESH,
)
fetched = store.get_artifact(child_id)
@@ -282,7 +282,7 @@ class TestEvidenceGateSitsOnTheWritePath:
store,
parent_id,
AdaptationPatch(universe="SP500"),
- parent_evidence=_evidence(),
+ parent_evidence=_evidence(parent_id),
today=TODAY_STALE,
)
diff --git a/frontend/src/components/chat/WelcomeScreen.tsx b/frontend/src/components/chat/WelcomeScreen.tsx
index 6db913ffc..cce96ba32 100644
--- a/frontend/src/components/chat/WelcomeScreen.tsx
+++ b/frontend/src/components/chat/WelcomeScreen.tsx
@@ -20,6 +20,11 @@ const CATEGORIES: Category[] = [
labelKey: "welcome.categories.multiMarketBacktest",
icon: <TrendingUp className="h-4 w-4" />,
examples: [
+ {
+ titleKey: "welcome.examples.adaptStrategy",
+ descKey: "welcome.examples.adaptStrategyDesc",
+ promptKey: "welcome.examples.adaptStrategyPrompt",
+ },
{
titleKey: "welcome.examples.crossMarketPortfolio",
descKey: "welcome.examples.crossMarketPortfolioDesc",
diff --git a/frontend/src/components/chat/__tests__/WelcomeScreen.test.tsx b/frontend/src/components/chat/__tests__/WelcomeScreen.test.tsx
index 8864b5da2..f616a0a2d 100644
--- a/frontend/src/components/chat/__tests__/WelcomeScreen.test.tsx
+++ b/frontend/src/components/chat/__tests__/WelcomeScreen.test.tsx
@@ -140,7 +140,7 @@ describe("WelcomeScreen", () => {
expect(library).toHaveAttribute("aria-hidden", "false");
// One category at a time: 8 tab chips, only the active category's cards.
expect(within(library!).getAllByRole("tab")).toHaveLength(8);
- expect(within(library!).getAllByRole("button")).toHaveLength(3);
+ expect(within(library!).getAllByRole("button")).toHaveLength(4);
expect(within(library!).getAllByRole("button")[0]).toHaveClass(
"focus-visible:ring-2",
"focus-visible:ring-primary/40",
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index 70be6065b..d5244c518 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -394,7 +394,10 @@
"quoteTrendPrompt": "استخدم موصل التداول المحدد لجلب سعر 600519.SH و30 عمودًا يوميًا، ثم لخّص السعر الحالي مقابل الاتجاه الأخير. اجعله للقراءة فقط.",
"trainShadowPrompt": "درّب حسابي الظلّي من يومية التداول التي رفعتها — اعرض القواعد المستخرجة وأكّد أنها تشبه سلوكي",
"shadowDeltaPrompt": "شغّل اختبارًا عكسيًا ظليًا لآخر 90 يومًا وحلّل أين انحرفت أرباحي عن الظلّ (انتهاكات القواعد، الخروج المبكر، إشارات مفقودة)",
- "shadowReportPrompt": "اعرض تقرير الظلّ وأعطِني الرابط — ابدأ بفرق أرباحك مقابل الظلّ"
+ "shadowReportPrompt": "اعرض تقرير الظلّ وأعطِني الرابط — ابدأ بفرق أرباحك مقابل الظلّ",
+ "adaptStrategy": "تكييف استراتيجية مسجلة",
+ "adaptStrategyDesc": "الحفاظ على الإشارة واختبار مجموعة أصول جديدة",
+ "adaptStrategyPrompt": "ساعدني في تكييف استراتيجية مسجلة لمجموعة أصول وفترة جديدتين. اعرض الاستراتيجيات وافحص أدلة الاستراتيجية الأصلية، واسألني عن المعرّف والأصول والتواريخ وحجم المراكز إن نقصت. حافظ على الإشارة وأنشئ كود الاستراتيجية المشتقة واختبرها تاريخياً، ثم اعرض أدلتها المحدّثة الخاصة بها فقط."
},
"taskSubtitle": "اسأل عن سهم أو استراتيجية أو محفظتك — سأجلب البيانات وأجري الحسابات وأعرض كل خطوة.",
"quickActions": "إجراءات سريعة",
diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json
index 0a285943e..c4bdb6e0f 100644
--- a/frontend/src/i18n/locales/de.json
+++ b/frontend/src/i18n/locales/de.json
@@ -399,7 +399,10 @@
"shadowDeltaPrompt": "Führe einen Shadow-Backtest für die letzten 90 Tage durch und zerlege, wo mein PnL vom Shadow abweicht (Regelverletzungen, vorzeitige Exits, verpasste Signale)",
"shadowReport": "Shadow-Bericht erstellen",
"shadowReportDesc": "Ein teilbarer 8-teiliger Bericht: deine Kontokurve, risikobereinigte Rendite und woher jeder Gewinn kam",
- "shadowReportPrompt": "Rendere den Shadow-Bericht und gib mir die URL — beginne mit dem Du-vs-Shadow-Delta"
+ "shadowReportPrompt": "Rendere den Shadow-Bericht und gib mir die URL — beginne mit dem Du-vs-Shadow-Delta",
+ "adaptStrategy": "Registrierte Strategie anpassen",
+ "adaptStrategyDesc": "Signal beibehalten, neues Universum testen",
+ "adaptStrategyPrompt": "Hilf mir, eine registrierte Strategie auf ein neues Universum und einen neuen Zeitraum anzupassen. Liste zuerst Strategien auf und prüfe die Evidenz der Ausgangsstrategie. Frage nach fehlender ID, Instrumenten, Daten und Positionsgrößen. Behalte das Signal bei, generiere den abgeleiteten Code, führe den Backtest aus und berichte nur dessen eigene aktualisierte Evidenz."
},
"taskSubtitle": "Frag nach einer Aktie, einer Strategie oder deinem Portfolio — ich hole die Daten, rechne alles durch und zeige jeden Schritt.",
"quickActions": "Schnellaktionen",
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 1a539a16c..01cb3baa4 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -399,7 +399,10 @@
"shadowDeltaPrompt": "Run a shadow backtest for the last 90 days and break down where my PnL diverged from the shadow (rule violations, early exits, missed signals)",
"shadowReport": "Generate Shadow Report",
"shadowReportDesc": "A shareable 8-part report: your account curve, risk-adjusted return, and where each gain came from",
- "shadowReportPrompt": "Render the shadow report and give me the URL — lead with the you-vs-shadow delta"
+ "shadowReportPrompt": "Render the shadow report and give me the URL — lead with the you-vs-shadow delta",
+ "adaptStrategy": "Adapt a registered strategy",
+ "adaptStrategyDesc": "Keep its signal, test a new universe",
+ "adaptStrategyPrompt": "Help me adapt a registered strategy to a new universe and date window. First list strategies and inspect the parent evidence; ask me for any missing strategy ID, instruments, dates and sizing. Preserve the signal, generate the child code, backtest it, and report only its own refreshed evidence."
},
"taskSubtitle": "Ask about a stock, a strategy, or your portfolio — I'll pull the data, run the numbers, and show every step.",
"quickActions": "Quick actions",
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index e9770503a..d6c9a21da 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -399,7 +399,10 @@
"shadowDeltaPrompt": "Ejecuta un backtest espejo de los últimos 90 días y desglosa dónde mi PnL se desvió del espejo (incumplimientos de reglas, salidas anticipadas, señales perdidas)",
"shadowReport": "Genera informe de cuenta espejo",
"shadowReportDesc": "Un informe compartible de 8 partes: la curva de tu cuenta, el retorno ajustado por riesgo y de dónde vino cada ganancia",
- "shadowReportPrompt": "Genera el informe de cuenta espejo y dame la URL — comienza con la diferencia tú-vs-espejo"
+ "shadowReportPrompt": "Genera el informe de cuenta espejo y dame la URL — comienza con la diferencia tú-vs-espejo",
+ "adaptStrategy": "Adaptar una estrategia registrada",
+ "adaptStrategyDesc": "Conservar la señal y probar otro universo",
+ "adaptStrategyPrompt": "Ayúdame a adaptar una estrategia registrada a otro universo y período. Primero enumera las estrategias y revisa la evidencia de la original; pregunta por el ID, los instrumentos, las fechas y el tamaño de posición que falten. Conserva la señal, genera el código de la derivada, ejecuta el backtest e informa solo de su propia evidencia actualizada."
},
"taskSubtitle": "Pregunta sobre una acción, una estrategia o tu portafolio — obtendré los datos, haré los cálculos y te mostraré cada paso.",
"quickActions": "Acciones rápidas",
diff --git a/frontend/src/i18n/locales/fa.json b/frontend/src/i18n/locales/fa.json
index 67ba04a16..1553ed15e 100644
--- a/frontend/src/i18n/locales/fa.json
+++ b/frontend/src/i18n/locales/fa.json
@@ -399,7 +399,10 @@
"shadowDeltaPrompt": "بک‌تست سایه را برای ۹۰ روز اخیر اجرا کن و نشان بده سود و زیان من کجا از سایه جدا شده (نقض قواعد، خروج زودهنگام، سیگنال‌های ازدست‌رفته)",
"shadowReport": "تولید گزارش سایه",
"shadowReportDesc": "گزارش قابل‌اشتراک ۸ بخشی: منحنی حساب، بازده تنظیم‌شده با ریسک و منشأ هر سود",
- "shadowReportPrompt": "گزارش سایه را بساز و نشانی آن را بده — با اختلاف شما-نسبت-به-سایه شروع کن"
+ "shadowReportPrompt": "گزارش سایه را بساز و نشانی آن را بده — با اختلاف شما-نسبت-به-سایه شروع کن",
+ "adaptStrategy": "تطبیق راهبرد ثبت‌شده",
+ "adaptStrategyDesc": "حفظ سیگنال و آزمون مجموعه دارایی جدید",
+ "adaptStrategyPrompt": "کمک کنید راهبرد ثبت‌شده را برای مجموعه دارایی و بازه زمانی جدید تطبیق دهم. ابتدا راهبردها و شواهد راهبرد اصلی را بررسی کنید و شناسه، دارایی‌ها، تاریخ‌ها و اندازه موقعیت‌های نامشخص را از من بپرسید. سیگنال را حفظ کنید، کد راهبرد فرزند را تولید و پس‌آزمایی کنید و فقط شواهد به‌روز خود آن را گزارش دهید."
},
"taskSubtitle": "درباره یک سهم، یک استراتژی یا پورتفولیوی خود بپرسید — داده را می‌کشم، محاسبه می‌کنم و همه گام‌ها را نشان می‌دهم.",
"quickActions": "اقدامات سریع",
diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json
index 04567d333..9c4295f00 100644
--- a/frontend/src/i18n/locales/id.json
+++ b/frontend/src/i18n/locales/id.json
@@ -399,7 +399,10 @@
"shadowDeltaPrompt": "Jalankan shadow backtest untuk 90 hari terakhir dan uraikan di mana PnL saya berbeda dari shadow (pelanggaran aturan, exit terlalu cepat, sinyal terlewat)",
"shadowReport": "Buat Shadow Report",
"shadowReportDesc": "Laporan 8 bagian yang dapat dibagikan: kurva akun Anda, return yang disesuaikan terhadap risiko, dan sumber setiap keuntungan",
- "shadowReportPrompt": "Render shadow report dan berikan URL-nya — mulai dengan delta Anda vs shadow"
+ "shadowReportPrompt": "Render shadow report dan berikan URL-nya — mulai dengan delta Anda vs shadow",
+ "adaptStrategy": "Adaptasi strategi terdaftar",
+ "adaptStrategyDesc": "Pertahankan sinyal, uji semesta baru",
+ "adaptStrategyPrompt": "Bantu saya mengadaptasi strategi terdaftar ke semesta dan rentang tanggal baru. Daftar strategi dan periksa bukti induknya terlebih dahulu; tanyakan ID, instrumen, tanggal, dan ukuran posisi yang belum ada. Pertahankan sinyal, buat kode turunan, jalankan backtest, dan laporkan hanya bukti terbaru milik strategi turunan."
},
"taskSubtitle": "Tanyakan tentang saham, strategi, atau portofolio Anda — saya akan mengambil data, menghitung angkanya, dan menampilkan setiap langkah.",
"quickActions": "Aksi cepat",
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index 44064a773..18984c8b7 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -394,7 +394,10 @@
"quoteTrendPrompt": "選択したトレーディングコネクタで 600519.SH のクォートと30日足バーを取得し、現在のクォートを最近のトレンドと比較して要約。読み取り専用に保つ。",
"trainShadowPrompt": "アップロードしたトレードジャーナルからシャドウアカウントを学習 — 抽出されたルールを表示し、自分の行動に合っているか確認",
"shadowDeltaPrompt": "過去90日間のシャドウバックテストを実行し、実際のPnLとシャドウが乖離した箇所 (ルール違反、早期退出、シグナル見逃し) を詳細に分析",
- "shadowReportPrompt": "シャドウレポートをレンダリングしてURLを渡す — あなた vs シャドウのデルタを先頭に表示"
+ "shadowReportPrompt": "シャドウレポートをレンダリングしてURLを渡す — あなた vs シャドウのデルタを先頭に表示",
+ "adaptStrategy": "登録済み戦略を適応",
+ "adaptStrategyDesc": "シグナルを維持して新しい銘柄群で検証",
+ "adaptStrategyPrompt": "登録済み戦略を新しい銘柄群と期間に適応してください。まず戦略一覧と親戦略の根拠を確認し、ID・銘柄・期間・配分が不足していれば質問してください。シグナルを維持して子戦略のコードを生成し、バックテスト後は子戦略自身の更新済み根拠のみを報告してください。"
},
"taskSubtitle": "銘柄・戦略・ポートフォリオについて聞いてください。データ取得から計算まで、すべての手順をお見せします。",
"quickActions": "クイックアクション",
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 399acac15..a38be2bac 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -394,7 +394,10 @@
"quoteTrendPrompt": "선택한 트레이딩 커넥터로 600519.SH의 시세와 30일 일봉을 가져온 다음 현재 시세를 최근 추세와 비교하여 요약하세요. 읽기 전용으로 유지하세요.",
"trainShadowPrompt": "방금 업로드한 매매 일지에서 내 섀도우 계좌를 학습 — 추출된 규칙을 보여주고 내 행동과 일치하는지 확인",
"shadowDeltaPrompt": "지난 90일간의 섀도우 백테스트를 실행하고 실제 PnL이 섀도우와 갈라진 부분(규칙 위반, 조기 퇴장, 시그널 놓침)을 세분화하여 분석",
- "shadowReportPrompt": "섀도우 리포트를 렌더링하고 URL을 제공 — 내 PnL vs 섀도우 델타를 선두에 표시"
+ "shadowReportPrompt": "섀도우 리포트를 렌더링하고 URL을 제공 — 내 PnL vs 섀도우 델타를 선두에 표시",
+ "adaptStrategy": "등록 전략 적용",
+ "adaptStrategyDesc": "신호를 유지하고 새 종목군 검증",
+ "adaptStrategyPrompt": "등록된 전략을 새 종목군과 기간에 적용해 주세요. 먼저 전략 목록과 부모 전략의 근거를 확인하고, ID·종목·기간·비중 정보가 없으면 질문해 주세요. 신호를 유지한 자식 전략 코드를 생성해 백테스트하고 자식 전략 자체의 갱신된 근거만 보고해 주세요."
},
"taskSubtitle": "종목, 전략, 포트폴리오에 대해 물어보세요. 데이터 수집부터 계산까지 모든 과정을 보여드립니다.",
"quickActions": "빠른 작업",
diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.json
index 36f537926..2f7ace67c 100644
--- a/frontend/src/i18n/locales/pt-BR.json
+++ b/frontend/src/i18n/locales/pt-BR.json
@@ -399,7 +399,10 @@
"shadowDeltaPrompt": "Execute um backtest de sombra nos últimos 90 dias e analise onde meu PnL divergiu da sombra (violações de regras, saídas antecipadas, sinais perdidos)",
"shadowReport": "Gerar relatório de sombra",
"shadowReportDesc": "Relatório compartilhável em oito partes: curva da conta, retorno ajustado ao risco e origem de cada ganho",
- "shadowReportPrompt": "Renderize o relatório sombra e me forneça o URL – comece com o delta você-vs-sombra"
+ "shadowReportPrompt": "Renderize o relatório sombra e me forneça o URL – comece com o delta você-vs-sombra",
+ "adaptStrategy": "Adaptar estratégia cadastrada",
+ "adaptStrategyDesc": "Manter o sinal e testar outro universo",
+ "adaptStrategyPrompt": "Ajude-me a adaptar uma estratégia cadastrada a outro universo e período. Primeiro liste as estratégias e confira as evidências da original; pergunte pelo ID, ativos, datas e tamanho das posições que faltarem. Preserve o sinal, gere o código da derivada, execute o backtest e relate apenas as evidências atualizadas da própria derivada."
},
"taskSubtitle": "Pergunte sobre uma ação, uma estratégia ou seu portfólio — extrairei os dados, analisarei os números e mostrarei cada etapa.",
"quickActions": "Ações rápidas",
diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.json
index 797c6796f..9a5cc31fc 100644
--- a/frontend/src/i18n/locales/tr.json
+++ b/frontend/src/i18n/locales/tr.json
@@ -356,7 +356,10 @@
"shadowDeltaPrompt": "Run a shadow backtest for the last 90 days and break down where my PnL diverged from the shadow (rule violations, early exits, missed signals)",
"shadowReport": "Generate Shadow Report",
"shadowReportDesc": "A shareable 8-part report: your account curve, risk-adjusted return, and where each gain came from",
- "shadowReportPrompt": "Render the shadow report and give me the URL — lead with the you-vs-shadow delta"
+ "shadowReportPrompt": "Render the shadow report and give me the URL — lead with the you-vs-shadow delta",
+ "adaptStrategy": "Kayıtlı stratejiyi uyarlayın",
+ "adaptStrategyDesc": "Sinyali koruyun, yeni evreni test edin",
+ "adaptStrategyPrompt": "Kayıtlı bir stratejiyi yeni bir varlık evrenine ve tarih aralığına uyarlamama yardım edin. Önce stratejileri listeleyip ana stratejinin kanıtlarını inceleyin; eksik kimlik, varlık, tarih ve pozisyon büyüklüğünü sorun. Sinyali koruyun, türetilen kodu üretip geriye dönük test edin ve yalnızca türetilen stratejinin kendi güncel kanıtlarını raporlayın."
},
"taskSubtitle": "Ask about a stock, a strategy, or your portfolio — I'll pull the data, run the numbers, and show every step.",
"quickActions": "Hızlı işlemler",
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index 2c7d4f03a..5ffccb138 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -394,7 +394,10 @@
"quoteTrendPrompt": "使用选定的交易连接器获取 600519.SH 的报价和 30 日日线数据,然后总结当前报价与近期趋势的对比。保持只读。",
"trainShadowPrompt": "从我刚刚上传的交易日志中训练我的影子账户 —— 展示提取的规则并确认它们符合我的交易习惯",
"shadowDeltaPrompt": "运行过去 90 天的影子回测,并细化分析我的实际盈亏与影子账户发生分歧的地方(违反规则、过早退出、错过信号)",
- "shadowReportPrompt": "渲染影子报告并向我提供 URL —— 以你与影子账户的盈亏差距(Delta)为主导"
+ "shadowReportPrompt": "渲染影子报告并向我提供 URL —— 以你与影子账户的盈亏差距(Delta)为主导",
+ "adaptStrategy": "适配已有策略",
+ "adaptStrategyDesc": "保留信号,回测新标的",
+ "adaptStrategyPrompt": "帮我把已登记策略适配到新的标的和日期区间。先列出策略并检查父策略证据;缺少策略 ID、标的、日期或仓位设置时请问我。保留信号逻辑,生成子策略代码并回测,只报告子策略自己的新证据。"
},
"taskSubtitle": "问一只股票、一个策略,或者你的持仓——我会自己取数据、跑计算,并把每一步摆给你看。",
"quickActions": "快捷操作",