"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: add trust layer run cards
Haozhe Wu3981eb53f858
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b588343e1..a8d13c50d 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -137,6 +137,13 @@ Add a cross-asset correlation matrix component to the frontend:- ECharts heatmap or custom canvas renderer- Wire to a new API endpoint that computes rolling correlations+### Medium: Trust Layer Run Card UI++Backtests now emit `run_card.json` and `run_card.md`. Good follow-up contributions:+- Surface run-card links in CLI/API/Web UI run summaries+- Add a Web UI run-card detail view with config hash, strategy hash, data sources, metrics, validation, warnings, and artifact checksums+- Extend the run-card schema with tool trace and citations once trace capture is promoted into the Trust Layer contract+### Hard: Intraday Backtest EngineCurrent engines run on daily bars. We need sub-daily execution:diff --git a/README.md b/README.mdindex 321e77eb8..996f21dc2 100644--- a/README.md+++ b/README.md@@ -51,6 +51,7 @@## 📰 News+- **2026-05-12** 🧾 **Trust Layer run cards**: Backtests now emit reproducible `run_card.json` and `run_card.md` files alongside artifacts, capturing config and strategy hashes, data sources, scalar metrics, validation payloads, warnings, and artifact checksums. The backtest tool also returns the run-card paths so CLI/API callers can surface the evidence package directly.- **2026-05-11** 🧭 **Memory slugs, swarm accounting, and CLI preflight**: Persistent memory now preserves CJK characters when generating file slugs, preventing silent filename collisions for Chinese/Japanese/Korean notes ([#95](https://github.com/HKUDS/Vibe-Trading/pull/95), thanks @voidborne-d). Swarm run totals now prefer provider-reported token usage with the existing estimate fallback ([#94](https://github.com/HKUDS/Vibe-Trading/pull/94), thanks @Teerapat-Vatpitak), and the CLI run UI gained a startup preflight check for common environment issues ([#96](https://github.com/HKUDS/Vibe-Trading/pull/96), thanks @ykykj).- **2026-05-10** 🧱 **Regression guardrails + run metadata**: Memory recall now treats underscores as token boundaries, so snake_case saved memories such as `mcp_wiring_test` match natural-language queries like "mcp wiring" ([#87](https://github.com/HKUDS/Vibe-Trading/pull/87), thanks @hp083625). The MCP server has a subprocess smoke test covering initialize → `tools/list` → `tools/call` to guard the first-call deadlock path ([#86](https://github.com/HKUDS/Vibe-Trading/pull/86)), while low-risk hardening landed for Windows path-sensitive tests, API best-effort exception handling, backtest `run_dir` allowed-root validation, and SwarmRun provider/model metadata ([#88](https://github.com/HKUDS/Vibe-Trading/pull/88), [#90](https://github.com/HKUDS/Vibe-Trading/pull/90), [#91](https://github.com/HKUDS/Vibe-Trading/pull/91), [#92](https://github.com/HKUDS/Vibe-Trading/pull/92), thanks @Teerapat-Vatpitak).- **2026-05-09** 🛡️ **API path hardening + MCP server stability**: API run/session routes now validate path IDs before lookup, rejecting malformed newline-containing parameters and pinning the behavior in the auth/security regression suite ([#80](https://github.com/HKUDS/Vibe-Trading/pull/80), thanks @SJoon99). The MCP server now pre-warms the tool registry on the main thread before serving `tools/call`, avoiding a first-call deadlock in lazy tool discovery ([#85](https://github.com/HKUDS/Vibe-Trading/pull/85), thanks @Teerapat-Vatpitak). The Vite dev proxy also honors `VITE_API_URL` for non-default backend targets ([#82](https://github.com/HKUDS/Vibe-Trading/pull/82), thanks @voidborne-d).@@ -725,7 +726,7 @@ Vibe-Trading is part of the **[HKUDS](https://github.com/HKUDS)** agent ecosyste| **Portfolio Studio** | Risk x-ray, constraints, turnover-aware optimizer, rebalance notes | Planned || **Alpha Zoo** | Alpha101 / Alpha158 / Alpha191 factor libraries with screening + IC tests | Planned || **Research Delivery** | Scheduled briefs to Slack / Telegram / email-style channels | Planned |-| **Trust Layer** | Reproducible run cards: tool trace, data sources, assumptions, citations | Planned |+| **Trust Layer** | Reproducible run cards: tool trace, data sources, assumptions, citations | In Progress || **Community** | Shareable skills, presets, and strategy cards | Exploring |---diff --git a/README_ar.md b/README_ar.mdindex 6859a70ce..bd6795dac 100644--- a/README_ar.md+++ b/README_ar.md@@ -51,6 +51,7 @@## 📰 أحدث الأخبار+- **2026-05-12** 🧾 **Trust Layer run cards**: أصبحت الاختبارات الخلفية تنشئ الآن `run_card.json` و`run_card.md` قابلين لإعادة الإنتاج بجانب artifacts، مع تسجيل hashes للإعدادات وكود الاستراتيجية، ومصادر البيانات، والمقاييس scalar، ونتائج validation، والتحذيرات، وchecksums للـ artifacts. كما يعيد Backtest tool مسارات run-card حتى تستطيع CLI/API عرض حزمة الأدلة مباشرة.- **2026-05-11** 🧭 **Memory slugs وswarm accounting وCLI preflight**: يحافظ توليد slugs لملفات الذاكرة الدائمة الآن على أحرف CJK، ما يمنع اصطدامات أسماء الملفات الصامتة لملاحظات الصينية/اليابانية/الكورية ([#95](https://github.com/HKUDS/Vibe-Trading/pull/95)، شكراً @voidborne-d). تستخدم مجاميع Swarm run الآن token usage المبلّغ من provider أولاً مع الإبقاء على fallback التقديري الحالي ([#94](https://github.com/HKUDS/Vibe-Trading/pull/94)، شكراً @Teerapat-Vatpitak)، كما حصلت واجهة CLI run على فحص preflight عند البدء لاكتشاف مشكلات البيئة الشائعة مبكراً ([#96](https://github.com/HKUDS/Vibe-Trading/pull/96)، شكراً @ykykj).- **2026-05-10** 🧱 **حواجز انحدار + بيانات run الوصفية**: أصبح Memory recall يتعامل مع الشرطات السفلية كحدود token، لذلك تطابق الذكريات المحفوظة بصيغة snake_case مثل `mcp_wiring_test` استعلامات اللغة الطبيعية مثل "mcp wiring" ([#87](https://github.com/HKUDS/Vibe-Trading/pull/87)، شكراً @hp083625). تمت إضافة اختبار smoke للـ MCP server عبر subprocess يغطي initialize → `tools/list` → `tools/call` لحماية مسار deadlock في أول استدعاء ([#86](https://github.com/HKUDS/Vibe-Trading/pull/86)). كما دخلت تحسينات منخفضة المخاطر لتوافق اختبارات مسارات Windows، وتضييق معالجة استثناءات API best-effort، والتحقق من allowed roots لمسار backtest `run_dir`، وبيانات provider/model الوصفية في SwarmRun ([#88](https://github.com/HKUDS/Vibe-Trading/pull/88)، [#90](https://github.com/HKUDS/Vibe-Trading/pull/90)، [#91](https://github.com/HKUDS/Vibe-Trading/pull/91)، [#92](https://github.com/HKUDS/Vibe-Trading/pull/92)، شكراً @Teerapat-Vatpitak).- **2026-05-09** 🛡️ **تعزيز مسارات API + استقرار MCP server**: تتحقق مسارات run/session في API الآن من معرفات المسار قبل البحث، وترفض المعاملات المشوهة التي تحتوي على أسطر جديدة، مع تثبيت السلوك في اختبارات الانحدار auth/security ([#80](https://github.com/HKUDS/Vibe-Trading/pull/80)، شكراً @SJoon99). يقوم MCP server الآن بتسخين سجل الأدوات مسبقاً على الخيط الرئيسي قبل خدمة `tools/call`، لتجنب deadlock في أول استدعاء أثناء lazy tool discovery ([#85](https://github.com/HKUDS/Vibe-Trading/pull/85)، شكراً @Teerapat-Vatpitak). كما يحترم Vite dev proxy المتغير `VITE_API_URL` للأهداف الخلفية غير الافتراضية ([#82](https://github.com/HKUDS/Vibe-Trading/pull/82)، شكراً @voidborne-d).@@ -654,7 +655,7 @@ Vibe-Trading هو جزء من النظام البيئي للوكلاء **[HKUDS]| **Portfolio Studio** | أشعة مخاطر، قيود، محسّن يراعي الدوران، وملاحظات إعادة التوازن | مخطط || **Alpha Zoo** | مكتبات عوامل Alpha101 / Alpha158 / Alpha191 مع فحص واختبارات IC | مخطط || **Research Delivery** | موجزات مجدولة إلى Slack / Telegram / قنوات شبيهة بالبريد | مخطط |-| **Trust Layer** | بطاقات تشغيل قابلة للإعادة: أثر الأدوات، مصادر البيانات، الافتراضات، الاستشهادات | مخطط |+| **Trust Layer** | بطاقات تشغيل قابلة للإعادة: أثر الأدوات، مصادر البيانات، الافتراضات، الاستشهادات | قيد التنفيذ || **Community** | skills وpresets وstrategy cards قابلة للمشاركة | قيد الاستكشاف |---diff --git a/README_ja.md b/README_ja.mdindex 664d5f503..2706e62ab 100644--- a/README_ja.md+++ b/README_ja.md@@ -51,6 +51,7 @@## 📰 ニュース+- **2026-05-12** 🧾 **Trust Layer run cards**: バックテストは artifacts と並んで再現可能な `run_card.json` と `run_card.md` を出力するようになりました。config と戦略コードの hash、データソース、scalar metrics、validation payload、warnings、artifact checksum を記録します。Backtest ツールも run-card のパスを返すため、CLI/API から evidence package を直接表示できます。- **2026-05-11** 🧭 **Memory slug、swarm集計、CLIプリフライト**: 永続メモリのファイル slug 生成で CJK 文字を保持するようになり、中国語/日本語/韓国語ノートの静かなファイル名衝突を防ぎます([#95](https://github.com/HKUDS/Vibe-Trading/pull/95)、@voidborne-d に感謝)。Swarm run の合計は provider が返す token usage を優先し、従来の推定フォールバックも維持します([#94](https://github.com/HKUDS/Vibe-Trading/pull/94)、@Teerapat-Vatpitak に感謝)。CLI run UI には一般的な環境問題を早めに見つける起動時プリフライトチェックも入りました([#96](https://github.com/HKUDS/Vibe-Trading/pull/96)、@ykykj に感謝)。- **2026-05-10** 🧱 **回帰ガードレール + runメタデータ**: Memory recall はアンダースコアを token 境界として扱うようになり、`mcp_wiring_test` のような snake_case の保存メモリが "mcp wiring" のような自然言語クエリに一致します([#87](https://github.com/HKUDS/Vibe-Trading/pull/87)、@hp083625 に感謝)。MCP server には initialize → `tools/list` → `tools/call` を通す subprocess smoke test を追加し、初回呼び出し deadlock 経路の回帰を防ぎます([#86](https://github.com/HKUDS/Vibe-Trading/pull/86))。さらに Windows のパス依存テスト互換、API の best-effort 例外処理の絞り込み、backtest `run_dir` の allowed-root 検証、SwarmRun の provider/model メタデータという低リスク強化も入りました([#88](https://github.com/HKUDS/Vibe-Trading/pull/88)、[#90](https://github.com/HKUDS/Vibe-Trading/pull/90)、[#91](https://github.com/HKUDS/Vibe-Trading/pull/91)、[#92](https://github.com/HKUDS/Vibe-Trading/pull/92)、@Teerapat-Vatpitak に感謝)。- **2026-05-09** 🛡️ **APIパス強化 + MCP server安定化**: API の run/session ルートは参照前にパスIDを検証し、改行を含む不正なパラメータを拒否し、その挙動を auth/security 回帰テストで固定しました([#80](https://github.com/HKUDS/Vibe-Trading/pull/80)、@SJoon99 に感謝)。MCP server は `tools/call` を処理する前にメインスレッドでツールレジストリを事前ウォームアップし、lazy tool discovery の初回呼び出しデッドロックを回避します([#85](https://github.com/HKUDS/Vibe-Trading/pull/85)、@Teerapat-Vatpitak に感謝)。Vite dev proxy も `VITE_API_URL` を尊重し、非デフォルトのバックエンドターゲットを使えるようになりました([#82](https://github.com/HKUDS/Vibe-Trading/pull/82)、@voidborne-d に感謝)。@@ -651,7 +652,7 @@ Vibe-Tradingは**[HKUDS](https://github.com/HKUDS)**エージェントエコシ| **Portfolio Studio** | リスクX線、制約、回転率考慮オプティマイザー、リバランスノート | Planned || **Alpha Zoo** | Alpha101 / Alpha158 / Alpha191 因子ライブラリ、スクリーニング + IC テスト | Planned || **Research Delivery** | Slack / Telegram / メール型チャネルへの定期ブリーフ配信 | Planned |-| **Trust Layer** | 再現可能な run card: ツール履歴、データソース、仮定、引用 | Planned |+| **Trust Layer** | 再現可能な run card: ツール履歴、データソース、仮定、引用 | In Progress || **Community** | 共有可能な skills、presets、strategy cards | Exploring |---diff --git a/README_ko.md b/README_ko.mdindex 9a844ab79..ca03ece65 100644--- a/README_ko.md+++ b/README_ko.md@@ -51,6 +51,7 @@## 📰 뉴스+- **2026-05-12** 🧾 **Trust Layer run cards**: 백테스트가 이제 artifacts와 함께 재현 가능한 `run_card.json` 및 `run_card.md`를 생성합니다. config와 전략 코드 해시, 데이터 소스, scalar metrics, validation payload, warnings, artifact checksum을 기록합니다. Backtest 도구도 run-card 경로를 반환하므로 CLI/API가 evidence package를 바로 보여줄 수 있습니다.- **2026-05-11** 🧭 **Memory slug, swarm 집계, CLI 프리플라이트**: 영구 메모리 파일 slug 생성 시 CJK 문자를 보존해 중국어/일본어/한국어 노트의 조용한 파일명 충돌을 막습니다([#95](https://github.com/HKUDS/Vibe-Trading/pull/95), @voidborne-d 감사합니다). Swarm run 합계는 provider가 반환한 token usage를 우선 사용하고 기존 추정 fallback도 유지합니다([#94](https://github.com/HKUDS/Vibe-Trading/pull/94), @Teerapat-Vatpitak 감사합니다). CLI run UI에는 일반적인 환경 문제를 더 일찍 드러내는 시작 프리플라이트 체크도 추가되었습니다([#96](https://github.com/HKUDS/Vibe-Trading/pull/96), @ykykj 감사합니다).- **2026-05-10** 🧱 **회귀 가드레일 + run 메타데이터**: Memory recall이 이제 밑줄을 token 경계로 처리하므로 `mcp_wiring_test` 같은 snake_case 저장 메모리가 "mcp wiring" 같은 자연어 쿼리에 매칭됩니다([#87](https://github.com/HKUDS/Vibe-Trading/pull/87), @hp083625 감사합니다). MCP server에는 initialize → `tools/list` → `tools/call` 경로를 실제 subprocess로 검증하는 smoke test를 추가해 첫 호출 deadlock 회귀를 막습니다([#86](https://github.com/HKUDS/Vibe-Trading/pull/86)). 또한 Windows 경로 민감 테스트 호환성, API best-effort 예외 처리 축소, backtest `run_dir` allowed-root 검증, SwarmRun provider/model 메타데이터 같은 저위험 강화도 반영했습니다([#88](https://github.com/HKUDS/Vibe-Trading/pull/88), [#90](https://github.com/HKUDS/Vibe-Trading/pull/90), [#91](https://github.com/HKUDS/Vibe-Trading/pull/91), [#92](https://github.com/HKUDS/Vibe-Trading/pull/92), @Teerapat-Vatpitak 감사합니다).- **2026-05-09** 🛡️ **API 경로 강화 + MCP server 안정성**: API run/session 라우트는 조회 전에 path ID를 검증하여 개행이 포함된 비정상 파라미터를 거부하고, 해당 동작을 auth/security 회귀 테스트로 고정했습니다([#80](https://github.com/HKUDS/Vibe-Trading/pull/80), @SJoon99 감사합니다). MCP server는 `tools/call` 처리 전에 메인 스레드에서 도구 레지스트리를 미리 워밍업해 lazy tool discovery의 첫 호출 deadlock을 피합니다([#85](https://github.com/HKUDS/Vibe-Trading/pull/85), @Teerapat-Vatpitak 감사합니다). Vite dev proxy도 `VITE_API_URL`을 존중해 기본값이 아닌 백엔드 타깃을 사용할 수 있게 했습니다([#82](https://github.com/HKUDS/Vibe-Trading/pull/82), @voidborne-d 감사합니다).@@ -652,7 +653,7 @@ Vibe-Trading은 **[HKUDS](https://github.com/HKUDS)** 에이전트 생태계의| **Portfolio Studio** | 리스크 엑스레이, 제약 조건, 턴오버 고려 옵티마이저, 리밸런싱 노트 | Planned || **Alpha Zoo** | Alpha101 / Alpha158 / Alpha191 팩터 라이브러리와 스크리닝 + IC 테스트 | Planned || **Research Delivery** | Slack / Telegram / 이메일형 채널로 예약 브리프 전달 | Planned |-| **Trust Layer** | 재현 가능한 run card: 도구 추적, 데이터 소스, 가정, 인용 | Planned |+| **Trust Layer** | 재현 가능한 run card: 도구 추적, 데이터 소스, 가정, 인용 | In Progress || **Community** | 공유 가능한 skills, presets, strategy cards | Exploring |---diff --git a/README_zh.md b/README_zh.mdindex 18b88fc6e..460c95e96 100644--- a/README_zh.md+++ b/README_zh.md@@ -51,6 +51,7 @@## 📰 新闻+- **2026-05-12** 🧾 **Trust Layer run cards**:回测现在会在 artifacts 旁边生成可复现的 `run_card.json` 与 `run_card.md`,记录 config 与策略代码 hash、数据来源、标量指标、validation 结果、warnings 和 artifact 校验和。Backtest 工具也会返回 run-card 路径,便于 CLI/API 直接展示证据包。- **2026-05-11** 🧭 **Memory slug、swarm 统计与 CLI 预检**:持久记忆生成文件 slug 时现在会保留 CJK 字符,避免中文/日文/韩文笔记发生静默文件名碰撞([#95](https://github.com/HKUDS/Vibe-Trading/pull/95),感谢 @voidborne-d)。Swarm run 总量会优先使用 provider 返回的 token usage,并保留原有估算回退([#94](https://github.com/HKUDS/Vibe-Trading/pull/94),感谢 @Teerapat-Vatpitak);CLI run UI 也新增启动预检,用于提前暴露常见环境问题([#96](https://github.com/HKUDS/Vibe-Trading/pull/96),感谢 @ykykj)。- **2026-05-10** 🧱 **回归护栏 + run 元数据**:Memory recall 现在会把下划线当作 token 边界,因此 `mcp_wiring_test` 这类 snake_case 记忆可以被 "mcp wiring" 这类自然语言查询命中([#87](https://github.com/HKUDS/Vibe-Trading/pull/87),感谢 @hp083625)。MCP server 新增 subprocess smoke test,覆盖 initialize → `tools/list` → `tools/call`,防止首次调用死锁路径回归([#86](https://github.com/HKUDS/Vibe-Trading/pull/86))。同时合入低风险加固:Windows 路径敏感测试兼容、API best-effort 异常处理收窄、backtest `run_dir` allowed-root 校验,以及 SwarmRun provider/model 元数据([#88](https://github.com/HKUDS/Vibe-Trading/pull/88)、[#90](https://github.com/HKUDS/Vibe-Trading/pull/90)、[#91](https://github.com/HKUDS/Vibe-Trading/pull/91)、[#92](https://github.com/HKUDS/Vibe-Trading/pull/92),感谢 @Teerapat-Vatpitak)。- **2026-05-09** 🛡️ **API 路径加固 + MCP server 稳定性**:API run/session 路由现在会先校验路径 ID 再查询,拒绝带换行等畸形参数,并在 auth/security 回归测试中固定行为([#80](https://github.com/HKUDS/Vibe-Trading/pull/80),感谢 @SJoon99)。MCP server 在处理 `tools/call` 前会在主线程预热工具注册表,避免 lazy tool discovery 的首次调用死锁([#85](https://github.com/HKUDS/Vibe-Trading/pull/85),感谢 @Teerapat-Vatpitak)。Vite 开发代理也会遵守 `VITE_API_URL`,方便连接非默认后端地址([#82](https://github.com/HKUDS/Vibe-Trading/pull/82),感谢 @voidborne-d)。@@ -651,7 +652,7 @@ Vibe-Trading 属于 **[HKUDS](https://github.com/HKUDS)** 代理生态的一部| **Portfolio Studio** | 风险透视、约束优化、换手感知优化器、调仓说明 | Planned || **Alpha Zoo** | Alpha101 / Alpha158 / Alpha191 因子库,支持筛选与 IC 测试 | Planned || **Research Delivery** | 定时研究简报推送到 Slack / Telegram / 邮件式渠道 | Planned |-| **Trust Layer** | 可复现实验卡片:工具轨迹、数据来源、假设与引用 | Planned |+| **Trust Layer** | 可复现实验卡片:工具轨迹、数据来源、假设与引用 | In Progress || **Community** | 可分享的 skills、presets 与 strategy cards | Exploring |---diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.pyindex e8a785dc6..70d2e5ba2 100644--- a/agent/backtest/engines/base.py+++ b/agent/backtest/engines/base.py@@ -34,6 +34,22 @@ from backtest.models import EquitySnapshot, Position, TradeRecordlogger = logging.getLogger(__name__)+def _run_card_data_sources(config: Dict[str, Any], loader: Any) -> List[str]:+ """Return source names for run-card evidence."""+ configured = config.get("_run_card_effective_sources")+ if isinstance(configured, list):+ return [str(source) for source in configured if str(source).strip()]+ if isinstance(configured, str) and configured.strip():+ return [configured.strip()]++ loader_name = getattr(loader, "name", None)+ if loader_name:+ return [str(loader_name)]++ source = config.get("source")+ return [str(source)] if source else []++# ─── Market detection (lightweight, for signal alignment only) ───_CRYPTO_RE = _re.compile(r"^[A-Z]+-USDT$|^[A-Z]+/USDT$", _re.I)@@ -405,6 +421,16 @@ class BaseEngine(ABC):target_pos, m, valid_codes,)+ # 9. Trust Layer run card+ from backtest.run_card import write_run_card+ write_run_card(+ run_dir,+ config,+ m,+ data_sources=_run_card_data_sources(config, loader),+ strategy_path=run_dir / "code" / "signal_engine.py",+ )+# Print scalar metrics (skip nested dicts for JSON compat)print(json.dumps({k: v for k, v in m.items() if not isinstance(v, dict)}, indent=2))return mdiff --git a/agent/backtest/engines/options_portfolio.py b/agent/backtest/engines/options_portfolio.pyindex dc928d9ec..bb1a90fd6 100644--- a/agent/backtest/engines/options_portfolio.py+++ b/agent/backtest/engines/options_portfolio.py@@ -16,7 +16,6 @@ Artifacts: equity.csv, metrics.csv, trades.csv, greeks.csv.import jsonimport sys-from datetime import datetimefrom pathlib import Pathfrom typing import Any, Dict, List, Optional@@ -290,7 +289,6 @@ def run_options_backtest(commission = config.get("commission", 0.001)options_cfg = config.get("options_config", {})risk_free_rate = options_cfg.get("risk_free_rate", 0.05)- iv_source = options_cfg.get("iv_source", "historical")contract_multiplier = options_cfg.get("contract_multiplier", 1.0)exercise_style = options_cfg.get("exercise_style", "european") # v2: "european" or "american"iv_skew = options_cfg.get("iv_skew", 0.0) # v2: smile skew param (0 = flat)@@ -554,6 +552,15 @@ def run_options_backtest(pd.DataFrame(greeks_records).to_csv(out / "greeks.csv", index=False)pd.DataFrame([metrics]).to_csv(out / "metrics.csv", index=False)+ from backtest.run_card import write_run_card+ write_run_card(+ run_dir,+ config,+ metrics,+ data_sources=[str(getattr(loader, "name", config.get("source", "")))],+ strategy_path=run_dir / "code" / "signal_engine.py",+ )+print(json.dumps(metrics, indent=2))return metricsdiff --git a/agent/backtest/run_card.py b/agent/backtest/run_card.pynew file mode 100644index 000000000..1c3ca57fc--- /dev/null+++ b/agent/backtest/run_card.py@@ -0,0 +1,200 @@+"""Trust Layer run card generator for backtest runs."""++from __future__ import annotations++import hashlib+import json+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Mapping, Sequence+++SCHEMA_VERSION = "0.1"+BACKTEST_SUMMARY_KEYS = (+ "codes",+ "start_date",+ "end_date",+ "interval",+ "engine",+ "initial_cash",+ "source",+)+++def write_run_card(+ run_dir: Path,+ config: Mapping[str, Any],+ metrics: Mapping[str, Any],+ *,+ data_sources: Sequence[str] | None = None,+ strategy_path: Path | None = None,+ warnings: Sequence[str] | None = None,+) -> dict[str, Any]:+ """Write JSON and Markdown run cards for a backtest run.++ Args:+ run_dir: Directory where run_card.json and run_card.md are written.+ config: Full backtest configuration. Only a summary and hash are stored.+ metrics: Backtest metrics. Scalar values are stored; ``validation`` is+ stored separately when present.+ data_sources: Data sources used by the run.+ strategy_path: Optional strategy source file to hash for reproducibility.+ warnings: Optional warnings to include in the card.++ Returns:+ The run card payload written to ``run_card.json``.+ """+ run_dir = Path(run_dir)+ run_dir.mkdir(parents=True, exist_ok=True)++ config_file = run_dir / "config.json"+ reproducibility: dict[str, Any] = {+ "config_hash": _file_hash(config_file) if config_file.exists() else _json_hash(config),+ }+ if strategy_path is not None:+ strategy_file = Path(strategy_path)+ if strategy_file.exists() and strategy_file.is_file():+ reproducibility["strategy_hash"] = _file_hash(strategy_file)++ card: dict[str, Any] = {+ "schema_version": SCHEMA_VERSION,+ "generated_at": _utc_now(),+ "run_dir": str(run_dir),+ "backtest": _backtest_summary(config),+ "reproducibility": reproducibility,+ "data_sources": list(data_sources or []),+ "metrics": _scalar_metrics(metrics),+ "warnings": list(warnings or []),+ "artifacts": _list_artifacts(run_dir),+ }+ if "validation" in metrics:+ card["validation"] = metrics["validation"]++ json_path = run_dir / "run_card.json"+ md_path = run_dir / "run_card.md"+ json_path.write_text(+ json.dumps(card, ensure_ascii=False, indent=2, sort_keys=True, default=str) + "\n",+ encoding="utf-8",+ )+ md_path.write_text(_render_markdown(card), encoding="utf-8")+ return card+++def _utc_now() -> str:+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+++def _json_hash(value: Mapping[str, Any]) -> str:+ payload = json.dumps(+ {key: val for key, val in value.items() if not str(key).startswith("_")},+ sort_keys=True,+ default=str,+ separators=(",", ":"),+ ensure_ascii=False,+ )+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()+++def _file_hash(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as handle:+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def _backtest_summary(config: Mapping[str, Any]) -> dict[str, Any]:+ return {key: config.get(key) for key in BACKTEST_SUMMARY_KEYS if key in config}+++def _scalar_metrics(metrics: Mapping[str, Any]) -> dict[str, Any]:+ return {+ key: value+ for key, value in metrics.items()+ if key != "validation" and _is_scalar(value)+ }+++def _is_scalar(value: Any) -> bool:+ return value is None or isinstance(value, (str, int, float, bool))+++def _list_artifacts(run_dir: Path) -> list[dict[str, Any]]:+ candidates: list[Path] = []+ for relative in (Path("config.json"), Path("code/signal_engine.py")):+ path = run_dir / relative+ if path.exists() and path.is_file():+ candidates.append(path)++ artifacts_dir = run_dir / "artifacts"+ if artifacts_dir.exists() and artifacts_dir.is_dir():+ candidates.extend(path for path in artifacts_dir.rglob("*") if path.is_file())++ artifacts = []+ for path in sorted(candidates, key=lambda item: item.relative_to(run_dir).as_posix()):+ artifacts.append(+ {+ "path": path.relative_to(run_dir).as_posix(),+ "size_bytes": path.stat().st_size,+ "sha256": _file_hash(path),+ }+ )+ return artifacts+++def _render_markdown(card: Mapping[str, Any]) -> str:+ lines = [+ "# Backtest Run Card",+ "",+ f"Generated: {card['generated_at']}",+ f"Run directory: `{card['run_dir']}`",+ "",+ "## Backtest Summary",+ ]++ backtest = card.get("backtest", {})+ if backtest:+ lines.extend(f"- {key}: {value}" for key, value in backtest.items())+ else:+ lines.append("- No backtest summary fields provided.")++ lines.extend(["", "## Reproducibility"])+ reproducibility = card.get("reproducibility", {})+ lines.append(f"- config_hash: `{reproducibility.get('config_hash', '')}`")+ if "strategy_hash" in reproducibility:+ lines.append(f"- strategy_hash: `{reproducibility['strategy_hash']}`")++ lines.extend(["", "## Data Sources"])+ data_sources = card.get("data_sources", [])+ lines.extend(f"- {source}" for source in data_sources) if data_sources else lines.append("- None recorded.")++ lines.extend(["", "## Metrics"])+ metric_values = card.get("metrics", {})+ lines.extend(f"- {key}: {value}" for key, value in metric_values.items()) if metric_values else lines.append("- No scalar metrics recorded.")++ lines.extend(["", "## Validation"])+ if "validation" in card:+ validation = card["validation"]+ if isinstance(validation, Mapping):+ lines.extend(f"- {key}: {value}" for key, value in validation.items())+ else:+ lines.append(f"- {validation}")+ else:+ lines.append("- Not present.")++ warnings = card.get("warnings", [])+ if warnings:+ lines.extend(["", "## Warnings"])+ lines.extend(f"- {warning}" for warning in warnings)++ lines.extend(["", "## Artifacts"])+ artifacts = card.get("artifacts", [])+ if artifacts:+ lines.extend(+ f"- `{artifact['path']}` ({artifact['size_bytes']} bytes, sha256 `{artifact['sha256']}`)"+ for artifact in artifacts+ )+ else:+ lines.append("- None found.")++ return "\n".join(lines) + "\n"diff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex 253af3256..ac2fd5850 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -466,6 +466,11 @@ def main(run_dir: Path) -> None:print(json.dumps({"error": "No data fetched"}))sys.exit(1)+ if source == "auto":+ config["_run_card_effective_sources"] = sorted(_group_codes_by_source(codes))+ else:+ config["_run_card_effective_sources"] = [source]+# Engineengine_type = config.get("engine", "daily")signal_engine = engine_cls()diff --git a/agent/src/core/runner.py b/agent/src/core/runner.pyindex b2b3ed23d..dd17195af 100644--- a/agent/src/core/runner.py+++ b/agent/src/core/runner.py@@ -73,6 +73,8 @@ _ARTIFACTS_SPEC = {"metrics": {"schema": "metrics_csv", "path": "artifacts/metrics.csv"},"trades": {"schema": "trade_log", "path": "artifacts/trades.csv"},"positions": {"schema": "positions_csv", "path": "artifacts/positions.csv"},+ "run_card_json": {"schema": "json", "path": "run_card.json"},+ "run_card_md": {"schema": "markdown", "path": "run_card.md"},},}diff --git a/agent/tests/test_engine_robustness.py b/agent/tests/test_engine_robustness.pyindex ea5ed66d5..91d834578 100644--- a/agent/tests/test_engine_robustness.py+++ b/agent/tests/test_engine_robustness.py@@ -9,6 +9,7 @@from __future__ import annotations+import jsonfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Dict@@ -241,6 +242,15 @@ class TestSymbolIsolation:assert metrics["benchmark_ticker"] == "000300.SH"assert metrics["benchmark_return"] == 0.00495+ run_card_path = tmp_path / "run_card.json"+ assert run_card_path.exists()+ run_card = json.loads(run_card_path.read_text(encoding="utf-8"))+ assert run_card["schema_version"] == "0.1"+ assert run_card["backtest"]["codes"] == ["000001.SZ"]+ assert run_card["data_sources"] == ["tushare"]+ assert run_card["metrics"]["benchmark_return"] == 0.00495+ assert (tmp_path / "run_card.md").exists()+def test_configured_fundamental_enrichment_failure_is_not_silent(self,monkeypatch: pytest.MonkeyPatch,diff --git a/agent/tests/test_run_card.py b/agent/tests/test_run_card.pynew file mode 100644index 000000000..486fa4b12--- /dev/null+++ b/agent/tests/test_run_card.py@@ -0,0 +1,193 @@+"""Tests for Trust Layer run card generation."""++from __future__ import annotations++import hashlib+import json+from pathlib import Path++import pandas as pd++from backtest.run_card import write_run_card+from src.core.runner import Runner+++def test_config_hash_is_deterministic_independent_of_key_order(tmp_path: Path) -> None:+ config_a = {+ "codes": ["AAPL", "MSFT"],+ "start_date": "2025-01-01",+ "end_date": "2025-03-01",+ "interval": "1D",+ "engine": "global_equity",+ "initial_cash": 100000,+ "source": "auto",+ "nested": {"b": 2, "a": 1},+ }+ config_b = {+ "nested": {"a": 1, "b": 2},+ "source": "auto",+ "initial_cash": 100000,+ "engine": "global_equity",+ "interval": "1D",+ "end_date": "2025-03-01",+ "start_date": "2025-01-01",+ "codes": ["AAPL", "MSFT"],+ }++ card_a = write_run_card(tmp_path / "a", config_a, {"sharpe": 1.2})+ card_b = write_run_card(tmp_path / "b", config_b, {"sharpe": 1.2})++ assert card_a["reproducibility"]["config_hash"] == card_b["reproducibility"]["config_hash"]+ assert "nested" not in card_a["backtest"]+++def test_strategy_hash_is_included_when_strategy_path_exists(tmp_path: Path) -> None:+ strategy_path = tmp_path / "strategy.py"+ strategy_path.write_text("def signal():\n return 1\n", encoding="utf-8")++ card = write_run_card(+ tmp_path / "run",+ {"codes": ["BTC-USDT"], "engine": "crypto"},+ {"return_pct": 0.15},+ strategy_path=strategy_path,+ )++ expected_hash = hashlib.sha256(strategy_path.read_bytes()).hexdigest()+ assert card["reproducibility"]["strategy_hash"] == expected_hash+++def test_artifact_listing_includes_expected_existing_files(tmp_path: Path) -> None:+ run_dir = tmp_path / "run"+ (run_dir / "code").mkdir(parents=True)+ (run_dir / "artifacts" / "nested").mkdir(parents=True)+ (run_dir / "config.json").write_text('{"ok": true}\n', encoding="utf-8")+ (run_dir / "code" / "signal_engine.py").write_text("SIGNAL = 1\n", encoding="utf-8")+ (run_dir / "artifacts" / "equity.csv").write_text("date,equity\n", encoding="utf-8")+ (run_dir / "artifacts" / "nested" / "trades.csv").write_text("id,pnl\n", encoding="utf-8")++ card = write_run_card(run_dir, {"codes": ["000001.SZ"]}, {"sharpe": 1.0})++ artifacts = {artifact["path"]: artifact for artifact in card["artifacts"]}+ assert card["reproducibility"]["config_hash"] == hashlib.sha256(+ (run_dir / "config.json").read_bytes()+ ).hexdigest()+ assert list(artifacts) == [+ "artifacts/equity.csv",+ "artifacts/nested/trades.csv",+ "code/signal_engine.py",+ "config.json",+ ]+ for relative_path, artifact in artifacts.items():+ path = run_dir / relative_path+ assert artifact["size_bytes"] == path.stat().st_size+ assert artifact["sha256"] == hashlib.sha256(path.read_bytes()).hexdigest()+++def test_json_and_markdown_files_are_written(tmp_path: Path) -> None:+ run_dir = tmp_path / "run"+ metrics = {+ "sharpe": 1.23,+ "max_drawdown": -0.08,+ "validation": {"n_windows": 5, "consistency_rate": 0.8},+ "curve": [1, 2, 3],+ }++ card = write_run_card(+ run_dir,+ {+ "codes": ["AAPL"],+ "start_date": "2025-01-01",+ "end_date": "2025-02-01",+ "interval": "1D",+ "engine": "global_equity",+ "initial_cash": 50000,+ "source": "yfinance",+ "secret": "not copied raw",+ },+ metrics,+ data_sources=["yfinance"],+ warnings=["sample warning"],+ )++ json_path = run_dir / "run_card.json"+ md_path = run_dir / "run_card.md"+ loaded = json.loads(json_path.read_text(encoding="utf-8"))+ markdown = md_path.read_text(encoding="utf-8")++ assert loaded == card+ assert loaded["schema_version"] == "0.1"+ assert loaded["generated_at"].endswith("Z")+ assert loaded["metrics"] == {"max_drawdown": -0.08, "sharpe": 1.23}+ assert loaded["validation"] == {"consistency_rate": 0.8, "n_windows": 5}+ assert "secret" not in json.dumps(loaded)+ assert "# Backtest Run Card" in markdown+ assert "Validation" in markdown+ assert "sample warning" in markdown+++def test_runner_artifact_spec_surfaces_run_card_paths() -> None:+ runner = Runner()++ assert runner.artifact_entries["run_card_json"]["path"] == "run_card.json"+ assert runner.artifact_entries["run_card_json"]["required"] is False+ assert runner.artifact_entries["run_card_md"]["path"] == "run_card.md"+ assert runner.artifact_entries["run_card_md"]["required"] is False+++def test_options_backtest_writes_run_card(tmp_path: Path) -> None:+ from backtest.engines.options_portfolio import run_options_backtest++ dates = pd.bdate_range("2025-01-01", periods=4)+ bars = pd.DataFrame(+ {+ "open": [100.0, 101.0, 102.0, 103.0],+ "high": [101.0, 102.0, 103.0, 104.0],+ "low": [99.0, 100.0, 101.0, 102.0],+ "close": [100.5, 101.5, 102.5, 103.5],+ "volume": [1000, 1100, 1200, 1300],+ },+ index=dates,+ )++ class FakeLoader:+ name = "yfinance"++ def fetch(self, codes, start_date, end_date):+ return {"SPY": bars.copy()}++ class SignalEngine:+ def generate(self, data_map):+ return [+ {+ "date": "2025-01-01",+ "action": "open",+ "underlying": "SPY",+ "legs": [{"type": "call", "strike": 101.0, "expiry": "2025-03-21", "qty": 1}],+ },+ {+ "date": "2025-01-03",+ "action": "close",+ "underlying": "SPY",+ "legs": [{"type": "call", "strike": 101.0, "expiry": "2025-03-21", "qty": 1}],+ },+ ]++ run_options_backtest(+ {+ "codes": ["SPY"],+ "start_date": "2025-01-01",+ "end_date": "2025-01-06",+ "source": "yfinance",+ "engine": "options",+ "initial_cash": 100_000,+ },+ FakeLoader(),+ SignalEngine(),+ tmp_path,+ )++ card = json.loads((tmp_path / "run_card.json").read_text(encoding="utf-8"))+ assert card["backtest"]["engine"] == "options"+ assert card["data_sources"] == ["yfinance"]+ assert "greeks.csv" in {Path(artifact["path"]).name for artifact in card["artifacts"]}+ assert (tmp_path / "run_card.md").exists()