"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(run-card): surface trust layer card in web UI
Haozhe Wudb21715cf9a8
diff --git a/agent/api_server.py b/agent/api_server.pyindex 334bf3dfd..61990622c 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -110,6 +110,7 @@ class RunResponse(BaseModel):metrics: Optional[BacktestMetrics] = Field(None, description="Backtest metrics")artifacts: List[Artifact] = Field(default_factory=list, description="Run artifacts")+ run_card: Optional[Dict[str, Any]] = Field(None, description="Trust Layer run card payload")equity_curve: Optional[List[Dict[str, Any]]] = Field(None, description="Equity preview")trade_log: Optional[List[Dict[str, Any]]] = Field(None, description="Trade preview")@@ -830,6 +831,13 @@ def _build_response_from_run_dir(run_dir: Path, elapsed: float, *, include_analyif metrics_csv_path.exists():response.artifacts_metrics_csv = _load_csv_to_dict(metrics_csv_path)+ run_card_path = run_dir / "run_card.json"+ if run_card_path.exists():+ try:+ response.run_card = json.loads(run_card_path.read_text(encoding="utf-8"))+ except (json.JSONDecodeError, OSError):+ pass+trades_path = run_dir / "artifacts" / "trades.csv"if trades_path.exists():response.artifacts_trades_csv = _load_csv_to_dict(trades_path)diff --git a/agent/tests/test_run_card.py b/agent/tests/test_run_card.pyindex 486fa4b12..2a8c9bcc7 100644--- a/agent/tests/test_run_card.py+++ b/agent/tests/test_run_card.py@@ -125,6 +125,30 @@ def test_json_and_markdown_files_are_written(tmp_path: Path) -> None:assert "sample warning" in markdown+def test_api_run_response_includes_run_card(tmp_path: Path) -> None:+ import api_server++ run_dir = tmp_path / "run_001"+ run_dir.mkdir()+ (run_dir / "state.json").write_text('{"status": "success"}\n', encoding="utf-8")+ run_card = {+ "schema_version": "0.1",+ "generated_at": "2026-05-15T00:00:00Z",+ "run_dir": str(run_dir),+ "backtest": {"codes": ["AAPL"], "source": "yfinance"},+ "reproducibility": {"config_hash": "abc123", "strategy_hash": "def456"},+ "data_sources": ["yfinance"],+ "metrics": {"sharpe": 1.2},+ "warnings": ["sample warning"],+ "artifacts": [{"path": "artifacts/metrics.csv", "size_bytes": 42, "sha256": "feed"}],+ }+ (run_dir / "run_card.json").write_text(json.dumps(run_card), encoding="utf-8")++ response = api_server._build_response_from_run_dir(run_dir, elapsed=0.0)++ assert response.run_card == run_card++def test_runner_artifact_spec_surfaces_run_card_paths() -> None:runner = Runner()diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex c968750b0..d92673615 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -279,6 +279,7 @@ export interface RunData {metrics?: BacktestMetrics;artifacts?: ArtifactInfo[];+ run_card?: RunCard;validation?: ValidationData;price_series?: Record<string, PriceBar[]>;@@ -289,6 +290,26 @@ export interface RunData {run_logs?: Array<{ source?: string; line_number?: number; message?: string }>;}+export interface RunCard {+ schema_version?: string;+ generated_at?: string;+ run_dir?: string;+ backtest?: Record<string, unknown>;+ reproducibility?: Record<string, unknown>;+ data_sources?: string[];+ metrics?: Record<string, unknown>;+ validation?: unknown;+ warnings?: string[];+ artifacts?: RunCardArtifact[];+ [key: string]: unknown;+}++export interface RunCardArtifact {+ path: string;+ size_bytes: number;+ sha256: string;+}+export interface BacktestMetrics {final_value: number;total_return: number;diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsxindex 1cc6ba115..efacb8503 100644--- a/frontend/src/pages/RunDetail.tsx+++ b/frontend/src/pages/RunDetail.tsx@@ -1,9 +1,23 @@import { useEffect, useState } from "react";-import { useParams, Link, useNavigate } from "react-router-dom";-import { CheckCircle2, XCircle, BarChart3, List, Code2, ArrowLeft, Download, ShieldCheck } from "lucide-react";+import type { ReactNode } from "react";+import { useParams, useNavigate } from "react-router-dom";+import {+ AlertTriangle,+ ArrowLeft,+ BarChart3,+ CheckCircle2,+ Code2,+ Database,+ Download,+ FileCheck2,+ Fingerprint,+ List,+ ShieldCheck,+ XCircle,+} from "lucide-react";import { cn } from "@/lib/utils";import { useI18n } from "@/lib/i18n";-import { api, type RunData, type BacktestMetrics } from "@/lib/api";+import { api, type BacktestMetrics, type RunCard, type RunData } from "@/lib/api";import ReactMarkdown from "react-markdown";import rehypeHighlight from "rehype-highlight";import { CandlestickChart } from "@/components/charts/CandlestickChart";@@ -15,7 +29,7 @@ import { ErrorBoundary } from "@/components/common/ErrorBoundary";const rehypePlugins = [rehypeHighlight];-type Tab = "chart" | "trades" | "code" | "validation";+type Tab = "chart" | "trades" | "runCard" | "code" | "validation";function downloadCsv(filename: string, csvContent: string) {const blob = new Blob(["\uFEFF" + csvContent], { type: "text/csv;charset=utf-8;" });@@ -59,10 +73,12 @@ export function RunDetail() {const [loading, setLoading] = useState(true);const hasValidation = !!run?.validation;+ const hasRunCard = !!run?.run_card;const TABS: { id: Tab; label: string; icon: typeof BarChart3; hidden?: boolean }[] = [{ id: "chart", label: t.chart, icon: BarChart3 },{ id: "trades", label: t.trades, icon: List },{ id: "validation", label: t.validation, icon: ShieldCheck, hidden: !hasValidation },+ { id: "runCard", label: "Run Card", icon: FileCheck2, hidden: !hasRunCard },{ id: "code", label: t.code, icon: Code2 },];@@ -148,6 +164,7 @@ export function RunDetail() {{tab === "chart" && <ChartTab run={run} />}{tab === "trades" && <TradesTab run={run} />}{tab === "validation" && run.validation && <ValidationPanel data={run.validation} />}+ {tab === "runCard" && run.run_card && <RunCardTab card={run.run_card} />}{tab === "code" && <CodeTab code={code} />}</ErrorBoundary></div>@@ -155,6 +172,147 @@ export function RunDetail() {);}+function RunCardTab({ card }: { card: RunCard }) {+ const backtest = card.backtest || {};+ const reproducibility = card.reproducibility || {};+ const metrics = card.metrics || {};+ const artifacts = card.artifacts || [];+ const warnings = card.warnings || [];+ const dataSources = card.data_sources || [];++ return (+ <div className="p-4 space-y-4">+ <div className="grid gap-3 md:grid-cols-4">+ <RunCardStat label="Schema" value={card.schema_version || "unknown"} />+ <RunCardStat label="Generated" value={formatRunCardValue(card.generated_at)} />+ <RunCardStat label="Data sources" value={dataSources.length ? dataSources.join(", ") : "None recorded"} />+ <RunCardStat label="Warnings" value={String(warnings.length)} tone={warnings.length ? "warning" : "normal"} />+ </div>++ {warnings.length > 0 && (+ <section className="rounded-md border border-amber-500/25 bg-amber-500/5 p-3">+ <div className="mb-2 flex items-center gap-2 text-sm font-medium text-amber-700 dark:text-amber-300">+ <AlertTriangle className="h-4 w-4" />+ Warnings+ </div>+ <ul className="space-y-1 text-xs text-muted-foreground">+ {warnings.map((warning, index) => <li key={index}>{warning}</li>)}+ </ul>+ </section>+ )}++ <div className="grid gap-4 xl:grid-cols-2">+ <RunCardPanel title="Backtest Summary" icon={Database}>+ <KeyValueTable data={backtest} empty="No backtest summary recorded." />+ </RunCardPanel>+ <RunCardPanel title="Reproducibility" icon={Fingerprint}>+ <KeyValueTable data={reproducibility} empty="No reproducibility hashes recorded." monospaceValues />+ </RunCardPanel>+ </div>++ <div className="grid gap-4 xl:grid-cols-2">+ <RunCardPanel title="Metrics" icon={BarChart3}>+ <KeyValueTable data={metrics} empty="No scalar metrics recorded." />+ </RunCardPanel>+ <RunCardPanel title="Validation" icon={ShieldCheck}>+ {card.validation ? (+ <pre className="max-h-80 overflow-auto rounded-md bg-muted/40 p-3 text-xs leading-relaxed">+ {JSON.stringify(card.validation, null, 2)}+ </pre>+ ) : (+ <p className="text-sm text-muted-foreground">No validation payload recorded.</p>+ )}+ </RunCardPanel>+ </div>++ <RunCardPanel title="Artifact Checksums" icon={FileCheck2}>+ {artifacts.length > 0 ? (+ <div className="overflow-x-auto">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b text-left text-muted-foreground">+ <th className="py-2 pr-4">Path</th>+ <th className="py-2 pr-4">Size</th>+ <th className="py-2">SHA-256</th>+ </tr>+ </thead>+ <tbody>+ {artifacts.map((artifact) => (+ <tr key={`${artifact.path}-${artifact.sha256}`} className="border-b last:border-0">+ <td className="py-2 pr-4 font-mono text-xs">{artifact.path}</td>+ <td className="py-2 pr-4 tabular-nums text-muted-foreground">{formatBytes(artifact.size_bytes)}</td>+ <td className="py-2 font-mono text-xs text-muted-foreground">{shortHash(artifact.sha256)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ ) : (+ <p className="text-sm text-muted-foreground">No artifact checksums recorded.</p>+ )}+ </RunCardPanel>+ </div>+ );+}++function RunCardStat({ label, value, tone = "normal" }: { label: string; value: string; tone?: "normal" | "warning" }) {+ return (+ <div className="rounded-md border bg-card p-3">+ <div className="text-xs text-muted-foreground">{label}</div>+ <div className={cn("mt-1 truncate text-sm font-medium", tone === "warning" ? "text-amber-700 dark:text-amber-300" : "")}>{value}</div>+ </div>+ );+}++function RunCardPanel({ title, icon: Icon, children }: { title: string; icon: typeof FileCheck2; children: ReactNode }) {+ return (+ <section className="rounded-md border bg-card p-4">+ <div className="mb-3 flex items-center gap-2 text-sm font-medium">+ <Icon className="h-4 w-4 text-muted-foreground" />+ {title}+ </div>+ {children}+ </section>+ );+}++function KeyValueTable({ data, empty, monospaceValues = false }: { data: Record<string, unknown>; empty: string; monospaceValues?: boolean }) {+ const entries = Object.entries(data).filter(([, value]) => value !== undefined && value !== null && value !== "");+ if (entries.length === 0) {+ return <p className="text-sm text-muted-foreground">{empty}</p>;+ }+ return (+ <table className="w-full table-fixed text-sm">+ <tbody>+ {entries.map(([key, value]) => (+ <tr key={key} className="border-b last:border-0">+ <td className="w-36 py-2 pr-4 align-top text-muted-foreground">{key}</td>+ <td className={cn("py-2 align-top", monospaceValues ? "break-all font-mono text-xs" : "break-words text-right tabular-nums")}>{formatRunCardValue(value)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ );+}++function formatRunCardValue(value: unknown): string {+ if (Array.isArray(value)) return value.join(", ");+ if (typeof value === "number") return Number.isInteger(value) ? String(value) : value.toFixed(4);+ if (typeof value === "object" && value !== null) return JSON.stringify(value);+ return String(value ?? "");+}++function formatBytes(value: number): string {+ if (!Number.isFinite(value)) return "-";+ if (value < 1024) return `${value} B`;+ if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`;+ return `${(value / (1024 * 1024)).toFixed(1)} MB`;+}++function shortHash(value: string): string {+ return value.length > 16 ? `${value.slice(0, 12)}...${value.slice(-6)}` : value;+}+function ChartTab({ run }: { run: RunData }) {const entries = run.price_series ? Object.entries(run.price_series) : [];const hasEquity = run.equity_curve && run.equity_curve.length > 0;@@ -238,4 +396,3 @@ function CodeTab({ code }: { code: Record<string, string> }) {</div>);}-