Skip to content

"Vibe-Trading: Your Personal Trading Agent"

docs: harden IRR-AGL migration and regression coverage

Mirandac906d2fe9306
diff --git a/AGENT_CONTRIBUTOR_GUIDE.md b/AGENT_CONTRIBUTOR_GUIDE.md
index 2266ba431..46214e5ab 100644
--- a/AGENT_CONTRIBUTOR_GUIDE.md
+++ b/AGENT_CONTRIBUTOR_GUIDE.md
@@ -21,6 +21,28 @@ Do not copy local `.env` files, token caches, broker exports, run artifacts,
private notebooks, generated reports, or local agent memory into this repository
unless they are explicitly sanitized fixtures.
+## IRR-AGL Contributor Boundaries
+
+IRR-AGL work must be additive and reviewable:
+
+- Prefer wrappers, adapters, audit extensions, and read-only surfaces.
+- Do not rewrite `AgentLoop`, `ToolRegistry`, loader registry, backtest engines,
+ MCP schemas, or live-safety gates for governance integration.
+- Preserve `BaseTool.execute(**kwargs) -> str`,
+ `ToolRegistry.execute(name, params) -> str`, and
+ `DataLoaderProtocol.fetch(codes, start_date, end_date, interval="1D", fields=None)`.
+- Keep `VIBE_TRADING_RELIABILITY_MODE=off` and
+ `VIBE_TRADING_GOVERNANCE_MODE=off` backward compatible.
+- New schemas need `schema_version`; new JSON hashes must be canonical.
+- Structured `warnings` and `hard_failures` should use stable codes, not only
+ free text.
+- Artifacts, traces, cards, and logs must pass secret redaction.
+- `R4_TRADE_WRITE` and `R5_SHELL` deny decisions must shadow-deny outside
+ `off`; do not let observe/warn execute high-risk denied tools.
+- Governance cannot approve live mandates and cannot replace
+ `LiveOrderGuardTool`.
+- DSR/PBO are experimental metrics only, not production pass gates.
+
## Safe Local Checks
These commands are normally safe for local validation:
diff --git a/README.md b/README.md
index e8a0dcfec..c7be98a09 100644
--- a/README.md
+++ b/README.md
@@ -204,6 +204,8 @@
Vibe-Trading is an open-source research workspace for turning finance questions into runnable analysis. It connects natural-language prompts to market-data loaders, strategy generation, backtest engines, reports, exports, and persistent research memory.
+The IRR-AGL reliability layer adds optional governance, PIT audit, quant scorecard, Research Card, schema migration, and threat-model documentation without changing the quickstart or legacy run artifacts. See [`docs/reliability-governance-rfc.md`](docs/reliability-governance-rfc.md), [`docs/migration-guide.md`](docs/migration-guide.md), and [`docs/threat-model.md`](docs/threat-model.md).
+
It is designed for research, simulation, and backtesting — and, when you choose, autonomous trading through a broker you authorize yourself (e.g. Robinhood Agentic Trading). It holds no funds and never trades outside the limits you set, and you can halt it instantly.
---
diff --git a/README_zh.md b/README_zh.md
index 8e7194c27..d410123e8 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -204,6 +204,8 @@
Vibe-Trading 是一个开源研究工作台,用于把金融问题转化为可运行的分析。它将自然语言提示连接到市场数据加载器、策略生成、回测引擎、报告、导出和持久研究记忆。
+IRR-AGL 可靠性层以可选、附加的方式提供 governance、PIT audit、quant scorecard、Research Card、schema migration 和 threat model 文档,不改变 quickstart 或旧 run artifacts。参见 [`docs/reliability-governance-rfc.md`](docs/reliability-governance-rfc.md)、[`docs/migration-guide.md`](docs/migration-guide.md) 和 [`docs/threat-model.md`](docs/threat-model.md)。
+
它面向研究、模拟和回测——并且在你选择时,可通过你自己授权的券商(如 Robinhood Agentic Trading)进行自主交易。它不托管任何资金,绝不超出你设定的限额交易,且你可随时一键停止。
---
diff --git a/agent/src/governance/discovery.py b/agent/src/governance/discovery.py
index 203ce0ac1..09df21b7e 100644
--- a/agent/src/governance/discovery.py
+++ b/agent/src/governance/discovery.py
@@ -106,6 +106,16 @@ class ManifestCache:
side_effects=["unknown"],
)
+ def register(self, tool: "BaseTool") -> ToolManifest:
+ """Register a manifest for a tool added after cache construction."""
+
+ manifest = discover_tool_manifest(tool, surface=self.surface)
+ if manifest.risk_level == RiskLevel.UNCLASSIFIED:
+ fallback_risk = RiskLevel.R0_READ if manifest.readonly else RiskLevel.R1_WRITE_LOCAL
+ manifest = manifest.model_copy(update={"risk_level": fallback_risk})
+ self._manifests[manifest.name] = manifest
+ return manifest
+
def discover_tool_manifest(tool: "BaseTool", *, surface: ToolSurface = ToolSurface.CLI) -> ToolManifest:
"""Derive a governance manifest from an existing BaseTool object."""
diff --git a/agent/src/governance/runtime.py b/agent/src/governance/runtime.py
index 0d91f7a8b..8a0c658e9 100644
--- a/agent/src/governance/runtime.py
+++ b/agent/src/governance/runtime.py
@@ -41,6 +41,15 @@ class GovernedToolRegistry:
def get(self, name: str) -> Any:
return self.inner.get(name)
+ def register(self, tool: Any) -> None:
+ """Delegate dynamic tool registration while keeping manifests in sync."""
+
+ register = getattr(self.inner, "register", None)
+ if not callable(register):
+ raise AttributeError("wrapped registry does not support register")
+ register(tool)
+ self.manifest_cache.register(tool)
+
def get_definitions(self) -> list[dict[str, Any]]:
return self.inner.get_definitions()
diff --git a/agent/tests/fixtures/schema_migration/data_audit_v1_0.json b/agent/tests/fixtures/schema_migration/data_audit_v1_0.json
new file mode 100644
index 000000000..28182c45d
--- /dev/null
+++ b/agent/tests/fixtures/schema_migration/data_audit_v1_0.json
@@ -0,0 +1,84 @@
+{
+ "audit_id": "audit_schema_fixture_v1",
+ "schema_version": "1.0.0",
+ "dataset_contract": {
+ "dataset_id": "ohlcv_daily_fixture",
+ "asset_class": "us_equity",
+ "frequency": "1D",
+ "calendar": "XNYS",
+ "fields": [
+ "open",
+ "high",
+ "low",
+ "close",
+ "volume"
+ ],
+ "timezone": "America/New_York",
+ "corporate_action_policy": "adjusted",
+ "survivorship_policy": "historical_membership"
+ },
+ "access_contract": {
+ "source": "local:fixture",
+ "selected_source": "local:fixture",
+ "request_params_hash": "1111111111111111111111111111111111111111111111111111111111111111",
+ "fallback_chain": [
+ "local:fixture"
+ ],
+ "cache_key": "fixture:ohlcv:AAPL,MSFT:2020-2024",
+ "fetched_at": "2026-01-01T00:00:00Z",
+ "source_timestamp": "2025-01-02T00:00:00Z",
+ "explicit_local": true,
+ "source_priority_rank": 1,
+ "fallback_chain_id": "fixture-local-only",
+ "circuit_breaker_state": "CLOSED",
+ "loader_latency_ms": 1.2
+ },
+ "row_count": 10000,
+ "symbol_count": 2,
+ "field_coverage": {
+ "open": 1.0,
+ "high": 1.0,
+ "low": 1.0,
+ "close": 1.0,
+ "volume": 1.0
+ },
+ "content_sample_hash": "2222222222222222222222222222222222222222222222222222222222222222",
+ "per_symbol_hashes": {
+ "AAPL": "3333333333333333333333333333333333333333333333333333333333333333",
+ "MSFT": "4444444444444444444444444444444444444444444444444444444444444444"
+ },
+ "pit_violations": [],
+ "quality_warnings": [
+ {
+ "code": "DATA_VALIDATOR_SAMPLED",
+ "severity": "info",
+ "message": "large DataFrame sampled for audit validation",
+ "metadata": {
+ "sampled_rows": 10000
+ }
+ }
+ ],
+ "market_rule_warnings": [],
+ "source_circuit_states": {
+ "local:fixture": "CLOSED"
+ },
+ "circuit_breaker_events": [
+ {
+ "source": "local:fixture",
+ "state": "CLOSED",
+ "consecutive_failures": 0,
+ "opened_at": null,
+ "last_error_class": null,
+ "next_probe_after": null
+ }
+ ],
+ "all_sources_open": false,
+ "artifact_refs": [
+ {
+ "artifact_id": "art_data_audit_fixture_v1",
+ "artifact_type": "data_audit",
+ "sha256": "5555555555555555555555555555555555555555555555555555555555555555",
+ "uri": "artifact://fixture/data_audit_v1"
+ }
+ ]
+}
diff --git a/agent/tests/fixtures/schema_migration/protocol_v1_0.json b/agent/tests/fixtures/schema_migration/protocol_v1_0.json
new file mode 100644
index 000000000..a23ea0d2e
--- /dev/null
+++ b/agent/tests/fixtures/schema_migration/protocol_v1_0.json
@@ -0,0 +1,115 @@
+{
+ "protocol_id": "rp_schema_fixture_v1",
+ "protocol_hash": "694d6dbcae0b2e02d66046cd231f1396f0eb8fc0f6eaa0feb2b5a531dda60711",
+ "schema_version": "1.0.0",
+ "status": "registered",
+ "goal_id": "goal_schema_fixture",
+ "session_id": "session_schema_fixture",
+ "hypothesis_id": "hyp_schema_fixture",
+ "hypothesis": "A simple momentum factor has positive out-of-sample IC after costs.",
+ "universe": {
+ "asset_class": "us_equity",
+ "universe_name": "sp500_historical_fixture",
+ "symbols": [
+ "AAPL",
+ "MSFT"
+ ],
+ "historical_membership_source": "fixture:sp500_historical_membership",
+ "point_in_time": true,
+ "filters": [
+ {
+ "field": "market_cap",
+ "op": "gte",
+ "value_json": "1000000000"
+ }
+ ]
+ },
+ "data_requirements": [
+ {
+ "dataset_id": "ohlcv_daily_fixture",
+ "asset_class": "us_equity",
+ "frequency": "1D",
+ "calendar": "XNYS",
+ "fields": [
+ "open",
+ "high",
+ "low",
+ "close",
+ "volume"
+ ],
+ "timezone": "America/New_York",
+ "corporate_action_policy": "adjusted",
+ "survivorship_policy": "historical_membership"
+ }
+ ],
+ "split_policy": {
+ "method": "walk_forward",
+ "train_start": "2020-01-01",
+ "train_end": "2022-12-31",
+ "validation_start": "2023-01-01",
+ "validation_end": "2023-12-31",
+ "test_start": "2024-01-01",
+ "test_end": "2024-12-31",
+ "fold_count": 4,
+ "min_effective_folds": 3
+ },
+ "benchmark_policy": {
+ "primary": "SPY",
+ "comparators": [
+ "RSP"
+ ],
+ "source": "fixture",
+ "pit_membership_required": true,
+ "rebalance_frequency": "daily"
+ },
+ "cost_model": {
+ "commission_bps": 1.0,
+ "slippage_bps": 5.0,
+ "spread_bps": 2.0,
+ "tax_bps": 0.0,
+ "min_fee": 0.0,
+ "borrow_fee_bps": null,
+ "stress_bps": [
+ 0,
+ 5,
+ 10,
+ 25,
+ 50,
+ 100
+ ]
+ },
+ "execution_assumptions": {
+ "signal_time_field": "signal_time",
+ "decision_delay": "1D",
+ "order_type": "market_on_open",
+ "fill_price": "next_open",
+ "allow_partial_fill": true,
+ "liquidity_cap_adv_pct": 0.05
+ },
+ "evaluation_plan": {
+ "metrics": [
+ "ic",
+ "rank_ic",
+ "turnover",
+ "net_return"
+ ],
+ "oos_required": true,
+ "ic_horizons": [
+ 1,
+ 5,
+ 20
+ ],
+ "regime_label_artifact_ref": "artifact://fixture/regimes",
+ "min_walk_forward_folds": 3,
+ "neutralization": "industry_size",
+ "random_control_required": true,
+ "regime_tests_required": true,
+ "crowding_tests_required": true
+ },
+ "created_at": "2026-01-01T00:00:00Z",
+ "registered_at": "2026-01-01T00:01:00Z",
+ "created_by": "schema_migration_fixture",
+ "metadata": {
+ "purpose": "schema migration fixture"
+ }
+}
diff --git a/agent/tests/fixtures/schema_migration/research_card_v1_0.json b/agent/tests/fixtures/schema_migration/research_card_v1_0.json
new file mode 100644
index 000000000..5f813afd1
--- /dev/null
+++ b/agent/tests/fixtures/schema_migration/research_card_v1_0.json
@@ -0,0 +1,236 @@
+{
+ "card_id": "rc_schema_fixture_v1",
+ "schema_version": "1.0.0",
+ "title": "Schema migration fixture research card",
+ "protocol_ref": "694d6dbcae0b2e02d66046cd231f1396f0eb8fc0f6eaa0feb2b5a531dda60711",
+ "hypothesis": "A simple momentum factor has positive out-of-sample IC after costs.",
+ "universe": {
+ "asset_class": "us_equity",
+ "universe_name": "sp500_historical_fixture",
+ "point_in_time": true
+ },
+ "data_sources": [
+ {
+ "audit_id": "audit_schema_fixture_v1",
+ "source": "local:fixture",
+ "selected_source": "local:fixture",
+ "fallback_chain": [
+ "local:fixture"
+ ],
+ "runtime_source": "local:fixture",
+ "row_count": 10000,
+ "symbol_count": 2,
+ "field_coverage": {
+ "open": 1.0,
+ "high": 1.0,
+ "low": 1.0,
+ "close": 1.0,
+ "volume": 1.0
+ },
+ "all_sources_open": false
+ }
+ ],
+ "data_audit_refs": [
+ "audit_schema_fixture_v1"
+ ],
+ "policy_decision_refs": [],
+ "tool_trace_refs": [
+ "trace://fixture/tool-trace-1"
+ ],
+ "backtest_refs": [
+ "backtest://fixture/run-1"
+ ],
+ "alpha_bench_refs": [
+ "alpha://fixture/strict-1"
+ ],
+ "scorecard": {
+ "scorecard_id": "sc_schema_fixture_v1",
+ "schema_version": "1.0.0",
+ "protocol_ref": "694d6dbcae0b2e02d66046cd231f1396f0eb8fc0f6eaa0feb2b5a531dda60711",
+ "data_audit_refs": [
+ "audit_schema_fixture_v1"
+ ],
+ "backtest_refs": [
+ "backtest://fixture/run-1"
+ ],
+ "alpha_bench_refs": [
+ "alpha://fixture/strict-1"
+ ],
+ "score": 0.896154,
+ "score_breakdown": {
+ "benchmark": 1.0,
+ "capacity": 0.8,
+ "cost_model": 1.0,
+ "cost_sensitivity": 0.75,
+ "crowding_risk": 0.6,
+ "execution_realism": 1.0,
+ "ic_stability": 0.8,
+ "oos_split": 1.0,
+ "pit_clean": 1.0,
+ "random_control": 1.0,
+ "regime_stability": 0.7,
+ "trial_count": 1.0,
+ "universe_pit": 1.0
+ },
+ "conclusion_cap": "research_candidate",
+ "crowding": {
+ "crowding_tier": "industry_known",
+ "crowding_risk": "medium",
+ "crowding_proxy": "public momentum family",
+ "stress_periods_tested": [
+ "2020-03",
+ "2022-01"
+ ]
+ },
+ "regime_ic": {
+ "regime_ic": {
+ "bull_market": 0.041,
+ "bear_market": 0.012,
+ "sideways": 0.022,
+ "full_sample": 0.031
+ },
+ "regime_frequency": {
+ "bull_market": 0.42,
+ "bear_market": 0.23,
+ "sideways": 0.35
+ },
+ "regime_stability_score": 0.7
+ },
+ "walk_forward": {
+ "fold_count": 4,
+ "effective_fold_count": 4,
+ "oos_ic_mean": 0.024,
+ "is_ic_mean": 0.036,
+ "oos_is_ic_ratio": 0.666667,
+ "negative_oos_fold_ratio": 0.0,
+ "oos_sharpe": 0.9,
+ "passed": true,
+ "failure_reasons": []
+ },
+ "ic_horizons": [
+ {
+ "horizon": 1,
+ "ic_mean": 0.031,
+ "rank_ic_mean": 0.028
+ },
+ {
+ "horizon": 5,
+ "ic_mean": 0.027,
+ "rank_ic_mean": 0.024
+ },
+ {
+ "horizon": 20,
+ "ic_mean": 0.018,
+ "rank_ic_mean": 0.016
+ }
+ ],
+ "cost_sensitivity": {
+ "bps_grid": [
+ 0,
+ 5,
+ 10,
+ 25,
+ 50,
+ 100
+ ],
+ "net_return_by_bps": {
+ "0": 0.18,
+ "5": 0.15,
+ "10": 0.12,
+ "25": 0.05,
+ "50": -0.02,
+ "100": -0.15
+ }
+ },
+ "capacity": {
+ "adv_participation_grid": [
+ 0.05,
+ 0.1,
+ 0.2
+ ],
+ "passed_max_participation": 0.1
+ },
+ "execution_realism": {
+ "signal_time": true,
+ "decision_time": true,
+ "order_time": true,
+ "fill_time": true,
+ "price_time": true
+ },
+ "neutralized_ic": {
+ "ic_raw": 0.031,
+ "ic_industry_neutral": 0.027,
+ "ic_size_neutral": 0.025,
+ "ic_double_neutral": 0.022
+ },
+ "random_control": {
+ "source": "bench_runner_strict",
+ "random_control": true,
+ "random_ic_mean": 0.001,
+ "alpha_t_full": 2.1,
+ "alpha_t_train": 1.9,
+ "alpha_t_test": 1.3
+ },
+ "warnings": [
+ {
+ "code": "QUANT_NEUTRALIZED_IC_STYLE_EXPOSURE",
+ "severity": "warning",
+ "message": "neutralized IC is lower than raw IC; style exposure should be monitored",
+ "metadata": {
+ "largest_drop": "size"
+ }
+ }
+ ],
+ "hard_failures": [],
+ "experimental_metrics": {
+ "dsr": 0.42,
+ "pbo": 0.18
+ }
+ },
+ "key_metrics": {
+ "ic_mean": 0.031,
+ "turnover": 0.22
+ },
+ "benchmark": {
+ "primary": "SPY",
+ "excess_return": 0.04
+ },
+ "cost_model": {
+ "commission_bps": 1.0,
+ "slippage_bps": 5.0,
+ "stress_bps": [
+ 0,
+ 5,
+ 10,
+ 25,
+ 50,
+ 100
+ ]
+ },
+ "execution_assumptions": {
+ "signal_time_field": "signal_time",
+ "decision_delay": "1D",
+ "order_type": "market_on_open",
+ "fill_price": "next_open"
+ },
+ "oos_results": {
+ "walk_forward_folds": 4,
+ "oos_ic_mean": 0.024
+ },
+ "warnings": [
+ {
+ "code": "QUANT_NEUTRALIZED_IC_STYLE_EXPOSURE",
+ "severity": "warning",
+ "message": "neutralized IC is lower than raw IC; style exposure should be monitored",
+ "metadata": {
+ "largest_drop": "size"
+ }
+ }
+ ],
+ "hard_failures": [],
+ "reproducibility": {
+ "artifact_graph_root": "artifact://fixture/research-card-v1",
+ "trial_count": 3
+ },
+ "conclusion_level": "research_candidate"
+}
diff --git a/agent/tests/fixtures/schema_migration/scorecard_v1_0.json b/agent/tests/fixtures/schema_migration/scorecard_v1_0.json
new file mode 100644
index 000000000..f8a571940
--- /dev/null
+++ b/agent/tests/fixtures/schema_migration/scorecard_v1_0.json
@@ -0,0 +1,144 @@
+{
+ "scorecard_id": "sc_schema_fixture_v1",
+ "schema_version": "1.0.0",
+ "protocol_ref": "694d6dbcae0b2e02d66046cd231f1396f0eb8fc0f6eaa0feb2b5a531dda60711",
+ "data_audit_refs": [
+ "audit_schema_fixture_v1"
+ ],
+ "backtest_refs": [
+ "backtest://fixture/run-1"
+ ],
+ "alpha_bench_refs": [
+ "alpha://fixture/strict-1"
+ ],
+ "score": 0.896154,
+ "score_breakdown": {
+ "benchmark": 1.0,
+ "capacity": 0.8,
+ "cost_model": 1.0,
+ "cost_sensitivity": 0.75,
+ "crowding_risk": 0.6,
+ "execution_realism": 1.0,
+ "ic_stability": 0.8,
+ "oos_split": 1.0,
+ "pit_clean": 1.0,
+ "random_control": 1.0,
+ "regime_stability": 0.7,
+ "trial_count": 1.0,
+ "universe_pit": 1.0
+ },
+ "conclusion_cap": "research_candidate",
+ "crowding": {
+ "crowding_tier": "industry_known",
+ "crowding_risk": "medium",
+ "crowding_proxy": "public momentum family",
+ "stress_periods_tested": [
+ "2020-03",
+ "2022-01"
+ ]
+ },
+ "regime_ic": {
+ "regime_ic": {
+ "bull_market": 0.041,
+ "bear_market": 0.012,
+ "sideways": 0.022,
+ "full_sample": 0.031
+ },
+ "regime_frequency": {
+ "bull_market": 0.42,
+ "bear_market": 0.23,
+ "sideways": 0.35
+ },
+ "regime_stability_score": 0.7
+ },
+ "walk_forward": {
+ "fold_count": 4,
+ "effective_fold_count": 4,
+ "oos_ic_mean": 0.024,
+ "is_ic_mean": 0.036,
+ "oos_is_ic_ratio": 0.666667,
+ "negative_oos_fold_ratio": 0.0,
+ "oos_sharpe": 0.9,
+ "passed": true,
+ "failure_reasons": []
+ },
+ "ic_horizons": [
+ {
+ "horizon": 1,
+ "ic_mean": 0.031,
+ "rank_ic_mean": 0.028
+ },
+ {
+ "horizon": 5,
+ "ic_mean": 0.027,
+ "rank_ic_mean": 0.024
+ },
+ {
+ "horizon": 20,
+ "ic_mean": 0.018,
+ "rank_ic_mean": 0.016
+ }
+ ],
+ "cost_sensitivity": {
+ "bps_grid": [
+ 0,
+ 5,
+ 10,
+ 25,
+ 50,
+ 100
+ ],
+ "net_return_by_bps": {
+ "0": 0.18,
+ "5": 0.15,
+ "10": 0.12,
+ "25": 0.05,
+ "50": -0.02,
+ "100": -0.15
+ }
+ },
+ "capacity": {
+ "adv_participation_grid": [
+ 0.05,
+ 0.1,
+ 0.2
+ ],
+ "passed_max_participation": 0.1
+ },
+ "execution_realism": {
+ "signal_time": true,
+ "decision_time": true,
+ "order_time": true,
+ "fill_time": true,
+ "price_time": true
+ },
+ "neutralized_ic": {
+ "ic_raw": 0.031,
+ "ic_industry_neutral": 0.027,
+ "ic_size_neutral": 0.025,
+ "ic_double_neutral": 0.022
+ },
+ "random_control": {
+ "source": "bench_runner_strict",
+ "random_control": true,
+ "random_ic_mean": 0.001,
+ "alpha_t_full": 2.1,
+ "alpha_t_train": 1.9,
+ "alpha_t_test": 1.3
+ },
+ "warnings": [
+ {
+ "code": "QUANT_NEUTRALIZED_IC_STYLE_EXPOSURE",
+ "severity": "warning",
+ "message": "neutralized IC is lower than raw IC; style exposure should be monitored",
+ "metadata": {
+ "largest_drop": "size"
+ }
+ }
+ ],
+ "hard_failures": [],
+ "experimental_metrics": {
+ "dsr": 0.42,
+ "pbo": 0.18
+ }
+}
diff --git a/agent/tests/governance/test_governed_registry.py b/agent/tests/governance/test_governed_registry.py
index 08a7641ff..21e4b3dc7 100644
--- a/agent/tests/governance/test_governed_registry.py
+++ b/agent/tests/governance/test_governed_registry.py
@@ -28,6 +28,17 @@ class _CountingTool(BaseTool):
return json.dumps({"status": "ok", "calls": self.calls})
+class _ReadTool(BaseTool):
+ name = "new_read"
+ description = "new read"
+ parameters = {"type": "object", "properties": {}}
+ repeatable = True
+ is_readonly = True
+
+ def execute(self, **kwargs):
+ return json.dumps({"status": "ok"})
+
+
def _registry(tool: _CountingTool | None = None) -> tuple[ToolRegistry, _CountingTool]:
tool = tool or _CountingTool()
inner = ToolRegistry()
@@ -145,3 +156,18 @@ def test_mode_off_delegates_directly() -> None:
assert result["calls"] == 1
assert tool.calls == 1
+
+
+def test_register_delegates_to_inner_registry_and_updates_manifest_cache() -> None:
+ inner = ToolRegistry()
+ governed = GovernedToolRegistry(
+ inner,
+ manifest_cache=ManifestCache({}, surface=ToolSurface.MCP_STDIO),
+ context=RuntimeContext(surface=ToolSurface.MCP_STDIO, mode="enforce"),
+ )
+
+ governed.register(_ReadTool())
+
+ assert "new_read" in governed.tool_names
+ assert governed.manifest_cache.get("new_read").risk_level == RiskLevel.R0_READ
+ assert json.loads(governed.execute("new_read", {})) == {"status": "ok"}
diff --git a/agent/tests/reliability/test_performance_baseline.py b/agent/tests/reliability/test_performance_baseline.py
new file mode 100644
index 000000000..8e83d2078
--- /dev/null
+++ b/agent/tests/reliability/test_performance_baseline.py
@@ -0,0 +1,175 @@
+from __future__ import annotations
+
+import json
+import platform
+import time
+from pathlib import Path
+
+from src.agent.tools import BaseTool, ToolRegistry
+from src.governance.decisions import RuntimeContext
+from src.governance.discovery import ManifestCache
+from src.governance.manifest import RiskLevel, ToolManifest, ToolSurface
+from src.governance.runtime import GovernedToolRegistry
+from src.reliability.artifacts.store import ArtifactStore
+from src.reliability.data.contracts import DataAuditReport
+from src.research_protocol.hashing import compute_protocol_hash
+from src.research_protocol.ledger import TrialLedger
+from src.research_protocol.model import ResearchProtocol
+
+
+FIXTURE_DIR = Path(__file__).resolve().parents[1] / "fixtures" / "schema_migration"
+
+
+def _p95(samples: list[float]) -> float:
+ ordered = sorted(samples)
+ return ordered[int((len(ordered) - 1) * 0.95)]
+
+
+def _p99(samples: list[float]) -> float:
+ ordered = sorted(samples)
+ return ordered[int((len(ordered) - 1) * 0.99)]
+
+
+def _threshold_ms(linux_target_ms: float, windows_target_ms: float) -> float:
+ return windows_target_ms if platform.system() == "Windows" else linux_target_ms
+
+
+def _measure_ms(fn, *, iterations: int = 40) -> list[float]:
+ samples: list[float] = []
+ fn()
+ for _ in range(iterations):
+ start = time.perf_counter()
+ fn()
+ samples.append((time.perf_counter() - start) * 1000)
+ return samples
+
+
+def test_data_audit_10k_row_metadata_p95_baseline() -> None:
+ payload = {
+ "audit_id": "audit_perf_10k",
+ "schema_version": "1.0.0",
+ "access_contract": {
+ "source": "local:perf",
+ "selected_source": "local:perf",
+ "request_params_hash": "0" * 64,
+ "fallback_chain": ["local:perf"],
+ "fetched_at": "2026-01-01T00:00:00Z",
+ "explicit_local": True,
+ },
+ "row_count": 10_000,
+ "symbol_count": 1,
+ "field_coverage": {
+ "open": 1.0,
+ "high": 1.0,
+ "low": 1.0,
+ "close": 1.0,
+ "volume": 1.0,
+ },
+ }
+
+ samples = _measure_ms(lambda: DataAuditReport.model_validate(payload), iterations=80)
+
+ assert _p95(samples) <= _threshold_ms(50.0, 150.0)
+
+
+def test_policy_engine_evaluate_p95_baseline() -> None:
+ from src.governance.policy_engine import PolicyEngine
+
+ engine = PolicyEngine()
+ context = RuntimeContext(surface=ToolSurface.REMOTE_API, mode="enforce")
+ manifest = ToolManifest(
+ name="bash",
+ surface=ToolSurface.REMOTE_API,
+ readonly=False,
+ repeatable=False,
+ risk_level=RiskLevel.R5_SHELL,
+ requires_auth=False,
+ requires_consent=True,
+ allowed_modes=["research"],
+ secret_access="none",
+ timeout_seconds=30,
+ side_effects=["process_execution"],
+ )
+
+ samples = _measure_ms(
+ lambda: engine.evaluate(name="bash", params={"api_key": "redact-me"}, manifest=manifest, context=context),
+ iterations=80,
+ )
+
+ assert _p95(samples) <= _threshold_ms(10.0, 40.0)
+
+
+def test_protocol_hash_p95_baseline() -> None:
+ protocol = ResearchProtocol.model_validate(json.loads((FIXTURE_DIR / "protocol_v1_0.json").read_text("utf-8")))
+
+ samples = _measure_ms(lambda: compute_protocol_hash(protocol), iterations=80)
+
+ assert _p95(samples) <= _threshold_ms(5.0, 20.0)
+
+
+def test_trial_ledger_append_p95_baseline(tmp_path: Path) -> None:
+ ledger = TrialLedger(path=tmp_path / "ledger.sqlite", write_retry_count=2, write_retry_delay_ms=1)
+
+ samples = _measure_ms(
+ lambda: ledger.append(
+ protocol_hash="p" * 64,
+ event_type="trial_started",
+ payload={"slice": "phase8"},
+ artifact_refs=[],
+ ),
+ iterations=20,
+ )
+
+ assert _p95(samples) <= _threshold_ms(50.0, 250.0)
+ assert ledger.verify().valid is True
+
+
+def test_artifact_store_write_1mb_p95_baseline(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")
+ store = ArtifactStore(root=tmp_path / "artifacts")
+ payload = b"x" * (1024 * 1024)
+
+ samples = _measure_ms(
+ lambda: store.write_bytes(payload, artifact_type="tool_trace", generated_by="perf_baseline"),
+ iterations=12,
+ )
+
+ assert _p95(samples) <= _threshold_ms(500.0, 1500.0)
+
+
+class _NoopTool(BaseTool):
+ name = "noop_read"
+ description = "noop read"
+ parameters = {"type": "object", "properties": {}}
+ repeatable = True
+ is_readonly = True
+
+ def execute(self, **kwargs):
+ return "ok"
+
+
+def test_governance_wrapper_overhead_p99_baseline() -> None:
+ inner = ToolRegistry()
+ inner.register(_NoopTool())
+ manifest = ToolManifest(
+ name="noop_read",
+ surface=ToolSurface.MCP_STDIO,
+ readonly=True,
+ repeatable=True,
+ risk_level=RiskLevel.R0_READ,
+ requires_auth=False,
+ requires_consent=False,
+ allowed_modes=["research"],
+ secret_access="none",
+ timeout_seconds=30,
+ side_effects=[],
+ )
+ governed = GovernedToolRegistry(
+ inner,
+ manifest_cache=ManifestCache({"noop_read": manifest}, surface=ToolSurface.MCP_STDIO),
+ context=RuntimeContext(surface=ToolSurface.MCP_STDIO, mode="observe"),
+ )
+
+ samples = _measure_ms(lambda: governed.execute("noop_read", {}), iterations=100)
+
+ assert _p99(samples) <= _threshold_ms(15.0, 75.0)
diff --git a/agent/tests/reliability/test_schema_migration.py b/agent/tests/reliability/test_schema_migration.py
new file mode 100644
index 000000000..d960c4554
--- /dev/null
+++ b/agent/tests/reliability/test_schema_migration.py
@@ -0,0 +1,72 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from src.reliability.artifacts.hashing import sha256_json
+from src.reliability.data.contracts import DataAuditReport
+from src.reliability.quant.scorecard import BacktestReliabilityScorecard, SCORECARD_DIMENSION_KEYS
+from src.research_card.model import ResearchCard
+from src.research_protocol.hashing import compute_protocol_hash
+from src.research_protocol.model import ResearchProtocol
+
+
+FIXTURE_DIR = Path(__file__).resolve().parents[1] / "fixtures" / "schema_migration"
+
+
+def _load_fixture(name: str) -> dict:
+ with (FIXTURE_DIR / name).open("r", encoding="utf-8") as handle:
+ return json.load(handle)
+
+
+def test_protocol_v1_0_fixture_validates_and_hash_is_stable() -> None:
+ protocol = ResearchProtocol.model_validate(_load_fixture("protocol_v1_0.json"))
+
+ assert protocol.schema_version == "1.0.0"
+ assert protocol.status == "registered"
+ assert protocol.evaluation_plan.ic_horizons == [1, 5, 20]
+ assert compute_protocol_hash(protocol) == protocol.protocol_hash
+
+
+def test_data_audit_v1_0_fixture_keeps_source_provenance() -> None:
+ audit = DataAuditReport.model_validate(_load_fixture("data_audit_v1_0.json"))
+
+ assert audit.schema_version == "1.0.0"
+ assert audit.access_contract.explicit_local is True
+ assert audit.access_contract.source == "local:fixture"
+ assert audit.access_contract.fallback_chain == ["local:fixture"]
+ assert audit.all_sources_open is False
+ assert "secret" not in json.dumps(audit.model_dump(mode="json"), ensure_ascii=False).lower()
+
+
+def test_scorecard_v1_0_fixture_uses_standard_dimension_whitelist() -> None:
+ scorecard = BacktestReliabilityScorecard.model_validate(_load_fixture("scorecard_v1_0.json"))
+
+ assert scorecard.schema_version == "1.0.0"
+ assert set(scorecard.score_breakdown) == set(SCORECARD_DIMENSION_KEYS)
+ assert "dsr" not in scorecard.score_breakdown
+ assert "pbo" not in scorecard.score_breakdown
+ assert {"dsr", "pbo"} <= set(scorecard.experimental_metrics)
+ assert not {item.code for item in scorecard.hard_failures} & {"DSR", "PBO", "QUANT_DSR_GATE", "QUANT_PBO_GATE"}
+
+
+def test_research_card_v1_0_fixture_validates_optional_scorecard_refs() -> None:
+ card = ResearchCard.model_validate(_load_fixture("research_card_v1_0.json"))
+
+ assert card.schema_version == "1.0.0"
+ assert card.scorecard is not None
+ assert card.scorecard.scorecard_id == "sc_schema_fixture_v1"
+ assert card.data_audit_refs == ["audit_schema_fixture_v1"]
+ assert card.backtest_refs == ["backtest://fixture/run-1"]
+ assert card.conclusion_level == "research_candidate"
+
+
+def test_schema_migration_fixtures_are_canonical_hashable_json() -> None:
+ for fixture_name in (
+ "research_card_v1_0.json",
+ "protocol_v1_0.json",
+ "data_audit_v1_0.json",
+ "scorecard_v1_0.json",
+ ):
+ digest = sha256_json(_load_fixture(fixture_name))
+ assert len(digest) == 64
diff --git a/agent/tests/security/test_irr_agl_regressions.py b/agent/tests/security/test_irr_agl_regressions.py
new file mode 100644
index 000000000..f455dc138
--- /dev/null
+++ b/agent/tests/security/test_irr_agl_regressions.py
@@ -0,0 +1,269 @@
+from __future__ import annotations
+
+import ast
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+from src.agent.tools import BaseTool, ToolRegistry
+from src.core.runner import _copy_runtime_env
+from src.governance.decisions import RuntimeContext
+from src.governance.discovery import ManifestCache
+from src.governance.errors import PolicyDenied
+from src.governance.manifest import RiskLevel, ToolManifest, ToolSurface
+from src.governance.policy_engine import PolicyEngine, PolicyRule
+from src.governance.runtime import GovernedToolRegistry
+from src.reliability.artifacts.store import resolve_under_root
+from src.reliability.data.contracts import DataAuditReport
+from src.reliability.errors import ArtifactPathError
+from src.research_card.builder import ResearchCardGraph, build_research_card
+
+
+def _manifest(
+ *,
+ name: str,
+ surface: ToolSurface,
+ risk: RiskLevel,
+ readonly: bool = False,
+ live_classification: str | None = None,
+) -> ToolManifest:
+ return ToolManifest(
+ name=name,
+ surface=surface,
+ readonly=readonly,
+ repeatable=True,
+ risk_level=risk,
+ requires_auth=False,
+ requires_consent=risk == RiskLevel.R4_TRADE_WRITE,
+ allowed_modes=["research", "paper", "advisory", "live"],
+ secret_access="none",
+ timeout_seconds=30,
+ side_effects=["test"],
+ live_classification=live_classification,
+ )
+
+
+def _context(surface: ToolSurface, mode: str = "enforce") -> RuntimeContext:
+ return RuntimeContext(surface=surface, mode=mode)
+
+
[email protected]("surface", [ToolSurface.REMOTE_API, ToolSurface.CHANNEL_BOT])
+def test_remote_and_channel_surfaces_deny_r5_shell(surface: ToolSurface) -> None:
+ decision = PolicyEngine().evaluate(
+ name="bash",
+ params={},
+ manifest=_manifest(name="bash", surface=surface, risk=RiskLevel.R5_SHELL),
+ context=_context(surface),
+ )
+
+ assert decision.action == "deny"
+ assert decision.rule_id == "P20"
+
+
+def test_scheduler_denies_live_write_and_shell() -> None:
+ engine = PolicyEngine()
+
+ for name, risk in (("place_order", RiskLevel.R4_TRADE_WRITE), ("bash", RiskLevel.R5_SHELL)):
+ decision = engine.evaluate(
+ name=name,
+ params={},
+ manifest=_manifest(name=name, surface=ToolSurface.SCHEDULER, risk=risk),
+ context=_context(ToolSurface.SCHEDULER),
+ )
+ assert decision.action == "deny"
+ assert decision.rule_id == "P30"
+
+
+def test_unknown_live_connector_fails_closed() -> None:
+ decision = PolicyEngine().evaluate(
+ name="broker_new_order_tool",
+ params={},
+ manifest=_manifest(
+ name="broker_new_order_tool",
+ surface=ToolSurface.LIVE_CONNECTOR,
+ risk=RiskLevel.R4_TRADE_WRITE,
+ live_classification="UNKNOWN",
+ ),
+ context=_context(ToolSurface.LIVE_CONNECTOR),
+ )
+
+ assert decision.action == "deny"
+ assert decision.rule_id == "P10"
+
+
+class _CountingTool(BaseTool):
+ name = "counting"
+ description = "counting"
+ parameters = {"type": "object", "properties": {}}
+ repeatable = True
+ is_readonly = False
+
+ def __init__(self) -> None:
+ self.calls = 0
+
+ def execute(self, **kwargs):
+ self.calls += 1
+ return json.dumps({"calls": self.calls})
+
+
+ ("risk", "surface", "mode"),
+ [
+ (RiskLevel.R4_TRADE_WRITE, ToolSurface.CLI, "observe"),
+ (RiskLevel.R5_SHELL, ToolSurface.REMOTE_API, "warn"),
+ ],
+)
+def test_r4_r5_policy_denies_are_shadow_denied_without_execution(
+ risk: RiskLevel,
+ surface: ToolSurface,
+ mode: str,
+) -> None:
+ tool = _CountingTool()
+ inner = ToolRegistry()
+ inner.register(tool)
+ manifest = _manifest(name="counting", surface=surface, risk=risk)
+ governed = GovernedToolRegistry(
+ inner,
+ manifest_cache=ManifestCache({"counting": manifest}, surface=surface),
+ context=RuntimeContext(surface=surface, mode=mode),
+ )
+
+ with pytest.raises(PolicyDenied) as raised:
+ governed.execute("counting", {})
+
+ assert raised.value.shadow is True
+ assert raised.value.trace_status == "skipped"
+ assert tool.calls == 0
+
+
+def test_explicit_local_market_data_fallback_to_network_is_denied() -> None:
+ decision = PolicyEngine().evaluate(
+ name="get_market_data",
+ params={"explicit_local": True, "fallback_to_network": True},
+ manifest=_manifest(
+ name="get_market_data",
+ surface=ToolSurface.CLI,
+ risk=RiskLevel.R2_NETWORK,
+ readonly=True,
+ ),
+ context=_context(ToolSurface.CLI, mode="observe"),
+ )
+
+ assert decision.action == "deny"
+ assert decision.rule_id == "P50"
+
+
+def test_all_sources_open_becomes_visible_research_card_warning() -> None:
+ audit = DataAuditReport.model_validate(
+ {
+ "audit_id": "audit_all_open",
+ "schema_version": "1.0.0",
+ "access_contract": {
+ "source": "auto",
+ "selected_source": "none",
+ "request_params_hash": "0" * 64,
+ "fallback_chain": ["eastmoney", "sina"],
+ "fetched_at": "2026-01-01T00:00:00Z",
+ "explicit_local": False,
+ },
+ "row_count": 0,
+ "symbol_count": 0,
+ "field_coverage": {},
+ "all_sources_open": True,
+ }
+ )
+
+ card = build_research_card(
+ ResearchCardGraph(
+ card_id="card_all_open",
+ title="all sources open regression",
+ data_audits=[audit],
+ has_oos=False,
+ has_cost_model=False,
+ has_benchmark=False,
+ )
+ )
+
+ warning = next(item for item in card.warnings if item.code == "DATA_ALL_SOURCES_OPEN")
+ assert warning.severity == "hard_failure"
+ assert card.conclusion_level != "paper_trade_candidate"
+
+
+def test_artifact_path_containment_rejects_escape_and_symlink(tmp_path: Path) -> None:
+ root = tmp_path / "root"
+ outside = tmp_path / "outside"
+ root.mkdir()
+ outside.mkdir()
+
+ with pytest.raises(ArtifactPathError):
+ resolve_under_root(root, "../outside/payload.json")
+
+ link = root / "link"
+ try:
+ os.symlink(outside, link, target_is_directory=True)
+ except (OSError, NotImplementedError):
+ return
+
+ with pytest.raises(ArtifactPathError):
+ resolve_under_root(root, "link/payload.json")
+
+
+def test_generated_backtest_subprocess_env_allowlist_excludes_live_and_llm_secrets(monkeypatch) -> None:
+ monkeypatch.setenv("OPENAI_API_KEY", "llm-secret")
+ monkeypatch.setenv("API_AUTH_KEY", "api-secret")
+ monkeypatch.setenv("BROKER_ACCESS_TOKEN", "broker-secret")
+ monkeypatch.setenv("TUSHARE_TOKEN", "market-data-token")
+
+ copied = _copy_runtime_env()
+
+ assert copied.get("TUSHARE_TOKEN") == "market-data-token"
+ assert "OPENAI_API_KEY" not in copied
+ assert "API_AUTH_KEY" not in copied
+ assert "BROKER_ACCESS_TOKEN" not in copied
+ assert "llm-secret" not in json.dumps(copied, ensure_ascii=False)
+ assert "broker-secret" not in json.dumps(copied, ensure_ascii=False)
+
+
+def test_agent_tool_surface_cannot_import_or_reference_commit_mandate() -> None:
+ offenders: list[str] = []
+ tools_root = Path(__file__).resolve().parents[2] / "src" / "tools"
+ for path in tools_root.rglob("*.py"):
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom) and node.names:
+ names = {alias.name for alias in node.names}
+ if "commit_mandate" in names:
+ offenders.append(f"{path.name} imports commit_mandate")
+ elif isinstance(node, ast.Name) and node.id == "commit_mandate":
+ offenders.append(f"{path.name} references commit_mandate")
+ elif isinstance(node, ast.Attribute) and node.attr == "commit_mandate":
+ offenders.append(f"{path.name} references .commit_mandate")
+
+ assert offenders == []
+
+
+def test_policy_engine_exception_high_risk_fails_safe() -> None:
+ def raises(**kwargs):
+ raise RuntimeError("boom")
+
+ decision = PolicyEngine(
+ rules=[
+ PolicyRule(
+ priority=1,
+ rule_id="raising",
+ description="raise",
+ action="allow",
+ predicate=raises,
+ )
+ ]
+ ).evaluate(
+ name="bash",
+ params={},
+ manifest=_manifest(name="bash", surface=ToolSurface.REMOTE_API, risk=RiskLevel.R5_SHELL),
+ context=_context(ToolSurface.REMOTE_API),
+ )
+
+ assert decision.action == "deny"
+ assert decision.rule_id == "policy_exception"