"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: add research protocol registry and trial ledger
Mirandaab782c91899f
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex 40b4d70e0..71bf5ee92 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -4437,6 +4437,10 @@ def _build_parser() -> argparse.ArgumentParser:from src.hypotheses.cli_handlers import add_subparser as _add_hypothesis_subparser_add_hypothesis_subparser(subparsers)+ # Research Protocol + Trial Ledger subcommands+ from src.research_protocol.cli_handlers import add_subparser as _add_research_subparser+ _add_research_subparser(subparsers)+return parser@@ -5238,6 +5242,9 @@ def main(argv: list[str] | None = None) -> int:if args.command == "hypothesis":from src.hypotheses.cli_handlers import dispatch as _hyp_dispatchreturn _coerce_exit_code(_hyp_dispatch(args))+ if args.command == "research":+ from src.research_protocol.cli_handlers import dispatch as _research_dispatch+ return _coerce_exit_code(_research_dispatch(args))if args.command == "connector":return _coerce_exit_code(_dispatch_connector(args))if args.command == "memory":diff --git a/agent/src/research_protocol/__init__.py b/agent/src/research_protocol/__init__.pynew file mode 100644index 000000000..505d32568--- /dev/null+++ b/agent/src/research_protocol/__init__.py@@ -0,0 +1,39 @@+"""Research protocol registry and trial ledger."""++from src.research_protocol.acceptance import AcceptanceError, AcceptedResult, validate_accepted_result+from src.research_protocol.hashing import compute_protocol_hash+from src.research_protocol.ledger import TrialLedger+from src.research_protocol.model import (+ BenchmarkSpec,+ CostModelSpec,+ DataSetContract,+ EvaluationPlan,+ ExecutionAssumptions,+ FilterSpec,+ ResearchProtocol,+ SplitSpec,+ UniverseSpec,+)+from src.research_protocol.registry import ProtocolImmutableError, ProtocolRegistry+from src.research_protocol.trial import TrialEvent, TrialEventType++__all__ = [+ "AcceptanceError",+ "AcceptedResult",+ "BenchmarkSpec",+ "CostModelSpec",+ "DataSetContract",+ "EvaluationPlan",+ "ExecutionAssumptions",+ "FilterSpec",+ "ProtocolImmutableError",+ "ProtocolRegistry",+ "ResearchProtocol",+ "SplitSpec",+ "TrialEvent",+ "TrialEventType",+ "TrialLedger",+ "UniverseSpec",+ "compute_protocol_hash",+ "validate_accepted_result",+]diff --git a/agent/src/research_protocol/acceptance.py b/agent/src/research_protocol/acceptance.pynew file mode 100644index 000000000..3af4e2d73--- /dev/null+++ b/agent/src/research_protocol/acceptance.py@@ -0,0 +1,51 @@+"""Accepted-result gates for registered research experiments."""++from __future__ import annotations++from pydantic import BaseModel, Field++from src.research_protocol.registry import ProtocolRegistry+++class AcceptanceError(ValueError):+ """Raised when a result cannot be accepted under IRR-AGL gates."""+++class AcceptedResult(BaseModel):+ """Minimum evidence required before accepting a research result."""++ protocol_hash: str | None = None+ trial_count: int | None = None+ data_audit_ids: list[str] = Field(default_factory=list)+ policy_decision_ids: list[str] = Field(default_factory=list)+ backtest_artifact_refs: list[str] = Field(default_factory=list)+ alpha_artifact_refs: list[str] = Field(default_factory=list)+ best_trial: bool = False+ selection_policy: str | None = None+ abandoned_count: int = 0+ rejected_count: int = 0+++def validate_accepted_result(result: AcceptedResult, *, registry: ProtocolRegistry | None = None) -> AcceptedResult:+ """Validate accepted-result gates and return the original result."""++ if not result.protocol_hash:+ raise AcceptanceError("accepted result requires a registered protocol_hash")+ if registry is not None and not registry.is_registered(result.protocol_hash):+ raise AcceptanceError("accepted result requires a registered protocol")+ if result.trial_count is None:+ raise AcceptanceError("accepted result requires trial_count")+ if result.trial_count <= 0:+ raise AcceptanceError("trial_count must be positive")+ if not result.data_audit_ids:+ raise AcceptanceError("accepted result requires at least one data_audit_id")+ if not result.policy_decision_ids:+ raise AcceptanceError("accepted result requires at least one policy_decision_id")+ if not (result.backtest_artifact_refs or result.alpha_artifact_refs):+ raise AcceptanceError("accepted result requires backtest or alpha artifacts")+ if result.best_trial:+ if not result.selection_policy:+ raise AcceptanceError("best trial display requires a selection policy")+ if result.abandoned_count <= 0 and result.rejected_count <= 0:+ raise AcceptanceError("best trial display requires abandoned/rejected count")+ return resultdiff --git a/agent/src/research_protocol/cli_handlers.py b/agent/src/research_protocol/cli_handlers.pynew file mode 100644index 000000000..c916356bd--- /dev/null+++ b/agent/src/research_protocol/cli_handlers.py@@ -0,0 +1,137 @@+"""CLI handlers for research protocol and ledger commands."""++from __future__ import annotations++import argparse+import json+import sys+import traceback+from pathlib import Path+from typing import Any, Callable++from src.research_protocol.extractor import draft_protocol_from_hypothesis+from src.research_protocol.ledger import TrialLedger+from src.research_protocol.registry import ProtocolRegistry+from src.research_protocol.trial import TrialEventType+++_RESEARCH_PARSER: argparse.ArgumentParser | None = None+++def _err(message: str) -> None:+ print(message, file=sys.stderr)+++def _registry(args: argparse.Namespace) -> ProtocolRegistry:+ root = Path(args.root).expanduser() if getattr(args, "root", None) else None+ artifact_root = Path(args.artifact_root).expanduser() if getattr(args, "artifact_root", None) else None+ return ProtocolRegistry(root=root, artifact_root=artifact_root)+++def _cmd_protocol_draft(args: argparse.Namespace) -> int:+ hypothesis = " ".join(args.hypothesis).strip()+ if not hypothesis:+ _err("research protocol draft requires a hypothesis")+ return 1+ protocol = draft_protocol_from_hypothesis(+ hypothesis,+ protocol_id=args.protocol_id,+ created_by="cli",+ )+ saved = _registry(args).save_draft(protocol)+ payload = saved.model_dump(mode="json")+ if args.json:+ print(json.dumps(payload, ensure_ascii=False, indent=2))+ else:+ print(f"draft {saved.protocol_id} {saved.protocol_hash}")+ return 0+++def _cmd_protocol_register(args: argparse.Namespace) -> int:+ registry = _registry(args)+ protocol = registry.register(args.protocol_id, created_by="cli")+ TrialLedger(Path(args.ledger_path).expanduser() if args.ledger_path else None).append(+ protocol_hash=protocol.protocol_hash,+ event_type=TrialEventType.PROTOCOL_REGISTERED,+ payload={"protocol_id": protocol.protocol_id},+ )+ payload = protocol.model_dump(mode="json")+ if args.json:+ print(json.dumps(payload, ensure_ascii=False, indent=2))+ else:+ print(f"registered {protocol.protocol_id} {protocol.protocol_hash}")+ return 0+++def _cmd_ledger_verify(args: argparse.Namespace) -> int:+ result = TrialLedger(Path(args.ledger_path).expanduser() if args.ledger_path else None).verify()+ payload = result.model_dump(mode="json")+ if args.json:+ print(json.dumps(payload, ensure_ascii=False, indent=2))+ elif result.valid:+ print(f"ledger ok ({result.event_count} events)")+ else:+ print("ledger invalid")+ for error in result.errors:+ print(f" - {error}")+ return 0 if result.valid else 1+++_DISPATCH: dict[tuple[str, str], Callable[[argparse.Namespace], int]] = {+ ("protocol", "draft"): _cmd_protocol_draft,+ ("protocol", "register"): _cmd_protocol_register,+ ("ledger", "verify"): _cmd_ledger_verify,+}+++def add_subparser(subparsers: Any) -> argparse.ArgumentParser:+ """Register ``research`` CLI commands."""++ global _RESEARCH_PARSER+ parser = subparsers.add_parser("research", help="Research protocol and ledger commands")+ parser.add_argument("--verbose", action="store_true", help="Show full traceback on errors")+ parser.add_argument("--root", default=None, help="Override protocol registry directory")+ parser.add_argument("--artifact-root", default=None, help="Override artifact store root")+ parser.add_argument("--ledger-path", default=None, help="Override trial ledger SQLite path")+ research_sub = parser.add_subparsers(dest="research_command")++ protocol = research_sub.add_parser("protocol", help="Draft/register research protocols")+ protocol_sub = protocol.add_subparsers(dest="protocol_command")+ draft = protocol_sub.add_parser("draft", help="Create a draft protocol from a hypothesis")+ draft.add_argument("hypothesis", nargs="+", help="Hypothesis text")+ draft.add_argument("--protocol-id", default="proto_draft", help="Protocol id to write")+ draft.add_argument("--json", action="store_true", help="Emit JSON")++ register = protocol_sub.add_parser("register", help="Register an existing draft protocol")+ register.add_argument("protocol_id", help="Protocol id to register")+ register.add_argument("--json", action="store_true", help="Emit JSON")++ ledger = research_sub.add_parser("ledger", help="Trial ledger commands")+ ledger_sub = ledger.add_subparsers(dest="ledger_command")+ verify = ledger_sub.add_parser("verify", help="Verify the trial ledger hash chain")+ verify.add_argument("--json", action="store_true", help="Emit JSON")++ _RESEARCH_PARSER = parser+ return parser+++def dispatch(args: argparse.Namespace) -> int:+ """Dispatch ``research`` subcommands."""++ command = getattr(args, "research_command", None)+ subcommand = getattr(args, f"{command}_command", None) if command else None+ handler = _DISPATCH.get((command, subcommand))+ if handler is None:+ if _RESEARCH_PARSER is not None:+ _RESEARCH_PARSER.print_help()+ else:+ _err("research requires a subcommand")+ return 1+ try:+ return int(handler(args))+ except Exception as exc: # noqa: BLE001+ if getattr(args, "verbose", False):+ traceback.print_exc()+ else:+ _err(f"research {command} {subcommand} failed: {exc}")+ return 1diff --git a/agent/src/research_protocol/extractor.py b/agent/src/research_protocol/extractor.pynew file mode 100644index 000000000..3fa427780--- /dev/null+++ b/agent/src/research_protocol/extractor.py@@ -0,0 +1,39 @@+"""Draft protocol extraction helpers."""++from __future__ import annotations++from datetime import datetime, timezone++from src.reliability.data.contracts import DataSetContract+from src.research_protocol.model import EvaluationPlan, ResearchProtocol, SplitSpec, UniverseSpec+++def draft_protocol_from_hypothesis(+ hypothesis: str,+ *,+ protocol_id: str = "proto_draft",+ created_by: str = "cli",+) -> ResearchProtocol:+ """Create a conservative draft protocol for CLI/manual refinement."""++ return ResearchProtocol(+ protocol_id=protocol_id,+ schema_version="1.0.0",+ status="draft",+ hypothesis=hypothesis,+ universe=UniverseSpec(asset_class="other", universe_name="unspecified"),+ data_requirements=[+ DataSetContract(+ dataset_id="unspecified",+ asset_class="other",+ frequency="1D",+ calendar="unspecified",+ fields=[],+ timezone="UTC",+ )+ ],+ split_policy=SplitSpec(method="holdout"),+ evaluation_plan=EvaluationPlan(metrics=["return", "sharpe"]),+ created_at=datetime.now(timezone.utc),+ created_by=created_by,+ )diff --git a/agent/src/research_protocol/hashing.py b/agent/src/research_protocol/hashing.pynew file mode 100644index 000000000..bdeb80b9f--- /dev/null+++ b/agent/src/research_protocol/hashing.py@@ -0,0 +1,34 @@+"""Canonical protocol hashing."""++from __future__ import annotations++from typing import Any++from src.reliability.artifacts.hashing import sha256_json+from src.research_protocol.model import ResearchProtocol+++HASH_EXCLUDED_FIELDS = {+ "protocol_id",+ "protocol_hash",+ "registered_at",+ "created_at",+ "status",+ "created_by",+ "metadata",+}+++def protocol_hash_payload(protocol: ResearchProtocol) -> dict[str, Any]:+ """Return the canonical JSON payload used for protocol hashing."""++ payload = protocol.model_dump(mode="json")+ for field in HASH_EXCLUDED_FIELDS:+ payload.pop(field, None)+ return payload+++def compute_protocol_hash(protocol: ResearchProtocol) -> str:+ """Return a cross-machine stable hash for research-design fields."""++ return sha256_json(protocol_hash_payload(protocol))diff --git a/agent/src/research_protocol/ledger.py b/agent/src/research_protocol/ledger.pynew file mode 100644index 000000000..326a87676--- /dev/null+++ b/agent/src/research_protocol/ledger.py@@ -0,0 +1,260 @@+"""SQLite WAL trial ledger with a linear hash chain."""++from __future__ import annotations++import json+import os+import random+import sqlite3+import time+from datetime import datetime, timezone+from pathlib import Path+from typing import Any+from uuid import uuid4++from src.reliability.artifacts.hashing import sha256_json+from src.research_protocol.trial import LedgerVerificationResult, TrialEvent, TrialEventType+++WRITE_RETRY_COUNT = 5+WRITE_RETRY_DELAY_MS = 100+_LEDGER_ENV = "VIBE_TRADING_RESEARCH_LEDGER_PATH"+++def default_ledger_path() -> Path:+ override = os.getenv(_LEDGER_ENV, "").strip()+ if override:+ return Path(override).expanduser()+ return Path.home() / ".vibe-trading" / "research-ledger" / "ledger.sqlite"+++class TrialLedger:+ """Append-only trial ledger using BEGIN IMMEDIATE and hash chaining."""++ def __init__(+ self,+ path: Path | None = None,+ *,+ write_retry_count: int = WRITE_RETRY_COUNT,+ write_retry_delay_ms: int = WRITE_RETRY_DELAY_MS,+ ) -> None:+ self.path = Path(path) if path is not None else default_ledger_path()+ self.write_retry_count = int(write_retry_count)+ self.write_retry_delay_ms = int(write_retry_delay_ms)+ self.path.parent.mkdir(parents=True, exist_ok=True)+ self._init_db()++ def append(+ self,+ *,+ protocol_hash: str,+ event_type: TrialEventType | str,+ payload: dict[str, Any] | None = None,+ artifact_refs: list[str] | None = None,+ ) -> TrialEvent:+ """Append one event, assigning sequence and previous hash inside the transaction."""++ last_error: Exception | None = None+ for attempt in range(max(1, self.write_retry_count)):+ conn = self._connect(timeout=0.1)+ try:+ conn.execute("BEGIN IMMEDIATE")+ sequence, previous = self._next_sequence(conn)+ created_at = datetime.now(timezone.utc)+ event_id = f"te_{uuid4().hex}"+ event_type_value = TrialEventType(event_type).value+ payload_dict = dict(payload or {})+ refs = list(artifact_refs or [])+ event_hash = _event_hash(+ event_id=event_id,+ event_type=event_type_value,+ schema_version="1.0.0",+ protocol_hash=protocol_hash,+ sequence_number=sequence,+ previous_event_hash=previous,+ created_at=created_at.isoformat(),+ payload=payload_dict,+ artifact_refs=refs,+ )+ conn.execute(+ """+ INSERT INTO trial_events (+ event_id, event_type, schema_version, protocol_hash,+ sequence_number, previous_event_hash, event_hash,+ created_at, payload_json, artifact_refs_json+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ event_id,+ event_type_value,+ "1.0.0",+ protocol_hash,+ sequence,+ previous,+ event_hash,+ created_at.isoformat(),+ _json_dump(payload_dict),+ _json_dump(refs),+ ),+ )+ conn.commit()+ return TrialEvent(+ event_id=event_id,+ event_type=TrialEventType(event_type_value),+ schema_version="1.0.0",+ protocol_hash=protocol_hash,+ sequence_number=sequence,+ previous_event_hash=previous,+ event_hash=event_hash,+ created_at=created_at,+ payload=payload_dict,+ artifact_refs=refs,+ )+ except sqlite3.OperationalError as exc:+ conn.rollback()+ last_error = exc+ if "locked" not in str(exc).lower() or attempt >= self.write_retry_count - 1:+ raise+ delay = (self.write_retry_delay_ms / 1000.0) * (2**attempt)+ delay += random.uniform(0, self.write_retry_delay_ms / 1000.0)+ time.sleep(delay)+ except Exception:+ conn.rollback()+ raise+ finally:+ conn.close()+ if last_error is not None:+ raise last_error+ raise RuntimeError("failed to append trial event")++ def verify(self) -> LedgerVerificationResult:+ """Verify sequence, previous hash, event hash, protocol hash, and schema version."""++ errors: list[str] = []+ previous_hash: str | None = None+ expected_sequence = 1+ with self._connect() as conn:+ rows = conn.execute(+ """+ SELECT event_id, event_type, schema_version, protocol_hash,+ sequence_number, previous_event_hash, event_hash,+ created_at, payload_json, artifact_refs_json+ FROM trial_events+ ORDER BY sequence_number ASC+ """+ ).fetchall()+ for row in rows:+ sequence = int(row["sequence_number"])+ if sequence != expected_sequence:+ errors.append(f"sequence gap at {row['event_id']}: expected {expected_sequence}, got {sequence}")+ if row["previous_event_hash"] != previous_hash:+ errors.append(f"previous hash mismatch at sequence {sequence}")+ if row["schema_version"] != "1.0.0":+ errors.append(f"schema_version mismatch at sequence {sequence}")+ if not str(row["protocol_hash"] or "").strip():+ errors.append(f"protocol hash missing at sequence {sequence}")+ try:+ TrialEventType(row["event_type"])+ except ValueError:+ errors.append(f"unknown event_type at sequence {sequence}: {row['event_type']}")+ payload = _json_load(row["payload_json"], {})+ refs = _json_load(row["artifact_refs_json"], [])+ expected_hash = _event_hash(+ event_id=row["event_id"],+ event_type=row["event_type"],+ schema_version=row["schema_version"],+ protocol_hash=row["protocol_hash"],+ sequence_number=sequence,+ previous_event_hash=row["previous_event_hash"],+ created_at=row["created_at"],+ payload=payload,+ artifact_refs=refs,+ )+ if expected_hash != row["event_hash"]:+ errors.append(f"event_hash mismatch at sequence {sequence}")+ previous_hash = row["event_hash"]+ expected_sequence += 1+ return LedgerVerificationResult(valid=not errors, event_count=len(rows), errors=errors)++ def _init_db(self) -> None:+ for attempt in range(max(1, self.write_retry_count)):+ try:+ with self._connect(timeout=0.1) as conn:+ conn.execute("PRAGMA journal_mode=WAL")+ conn.execute("PRAGMA synchronous=NORMAL")+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS trial_events (+ event_id TEXT PRIMARY KEY,+ event_type TEXT NOT NULL,+ schema_version TEXT NOT NULL,+ protocol_hash TEXT NOT NULL,+ sequence_number INTEGER NOT NULL UNIQUE,+ previous_event_hash TEXT,+ event_hash TEXT NOT NULL,+ created_at TEXT NOT NULL,+ payload_json TEXT NOT NULL,+ artifact_refs_json TEXT NOT NULL+ )+ """+ )+ conn.execute("CREATE INDEX IF NOT EXISTS idx_trial_events_protocol ON trial_events(protocol_hash)")+ return+ except sqlite3.OperationalError as exc:+ if "locked" not in str(exc).lower() or attempt >= self.write_retry_count - 1:+ raise+ delay = (self.write_retry_delay_ms / 1000.0) * (2**attempt)+ delay += random.uniform(0, self.write_retry_delay_ms / 1000.0)+ time.sleep(delay)++ def _connect(self, *, timeout: float = 30.0) -> sqlite3.Connection:+ conn = sqlite3.connect(str(self.path), timeout=timeout, check_same_thread=False)+ conn.row_factory = sqlite3.Row+ conn.execute("PRAGMA busy_timeout=30000")+ return conn++ @staticmethod+ def _next_sequence(conn: sqlite3.Connection) -> tuple[int, str | None]:+ row = conn.execute(+ "SELECT sequence_number, event_hash FROM trial_events ORDER BY sequence_number DESC LIMIT 1"+ ).fetchone()+ if row is None:+ return 1, None+ return int(row["sequence_number"]) + 1, str(row["event_hash"])+++def _event_hash(+ *,+ event_id: str,+ event_type: str,+ schema_version: str,+ protocol_hash: str,+ sequence_number: int,+ previous_event_hash: str | None,+ created_at: str,+ payload: dict[str, Any],+ artifact_refs: list[str],+) -> str:+ return sha256_json(+ {+ "event_id": event_id,+ "event_type": event_type,+ "schema_version": schema_version,+ "protocol_hash": protocol_hash,+ "sequence_number": sequence_number,+ "previous_event_hash": previous_event_hash,+ "created_at": created_at,+ "payload": payload,+ "artifact_refs": artifact_refs,+ }+ )+++def _json_dump(value: Any) -> str:+ return json.dumps(value, ensure_ascii=False, sort_keys=True, allow_nan=False, separators=(",", ":"))+++def _json_load(value: str, default: Any) -> Any:+ if not value:+ return default+ return json.loads(value)diff --git a/agent/src/research_protocol/model.py b/agent/src/research_protocol/model.pynew file mode 100644index 000000000..8bedc668f--- /dev/null+++ b/agent/src/research_protocol/model.py@@ -0,0 +1,175 @@+"""Strongly typed research protocol models."""++from __future__ import annotations++import json+import math+from datetime import date, datetime, timezone+from typing import Any, Literal++from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator++from src.reliability.data.contracts import DataSetContract+++ProtocolStatus = Literal["draft", "registered", "retired"]+AssetClass = Literal["ashare", "us_equity", "hk_equity", "crypto", "futures", "macro", "other"]+++class FilterSpec(BaseModel):+ """A canonical universe filter."""++ model_config = ConfigDict(allow_inf_nan=False)++ field: str+ op: Literal["eq", "neq", "in", "not_in", "gt", "gte", "lt", "lte", "between"]+ value_json: str++ @field_validator("value_json")+ @classmethod+ def _value_json_is_canonical_json(cls, value: str) -> str:+ try:+ json.loads(value)+ except json.JSONDecodeError as exc:+ raise ValueError("value_json must be valid JSON") from exc+ return value+++class UniverseSpec(BaseModel):+ """Point-in-time research universe definition."""++ model_config = ConfigDict(allow_inf_nan=False, arbitrary_types_allowed=False)++ asset_class: AssetClass+ universe_name: str | None = None+ symbols: list[str] | None = None+ historical_membership_source: str | None = None+ point_in_time: bool = False+ filters: list[FilterSpec] = Field(default_factory=list)+++class SplitSpec(BaseModel):+ """Train/validation/test split policy."""++ model_config = ConfigDict(allow_inf_nan=False)++ method: Literal["holdout", "walk_forward", "rolling", "expanding"]+ train_start: date | None = None+ train_end: date | None = None+ validation_start: date | None = None+ validation_end: date | None = None+ test_start: date | None = None+ test_end: date | None = None+ fold_count: int | None = None+ min_effective_folds: int | None = None+++class BenchmarkSpec(BaseModel):+ """Benchmark policy for alpha/tradability claims."""++ model_config = ConfigDict(allow_inf_nan=False)++ primary: str+ comparators: list[str] = Field(default_factory=list)+ source: str | None = None+ pit_membership_required: bool = True+ rebalance_frequency: str | None = None+++class CostModelSpec(BaseModel):+ """Transaction cost and stress assumptions."""++ model_config = ConfigDict(allow_inf_nan=False)++ commission_bps: float | None = None+ slippage_bps: float | None = None+ spread_bps: float | None = None+ tax_bps: float | None = None+ min_fee: float | None = None+ borrow_fee_bps: float | None = None+ stress_bps: list[float] = Field(default_factory=lambda: [0, 5, 10, 25, 50, 100])+++class ExecutionAssumptions(BaseModel):+ """Execution timing and fill assumptions."""++ model_config = ConfigDict(allow_inf_nan=False)++ signal_time_field: str | None = None+ decision_delay: str | None = None+ order_type: str | None = None+ fill_price: str | None = None+ allow_partial_fill: bool = True+ liquidity_cap_adv_pct: float | None = None+++class EvaluationPlan(BaseModel):+ """Metrics and anti-overfit validation plan."""++ model_config = ConfigDict(allow_inf_nan=False)++ metrics: list[str]+ oos_required: bool = True+ ic_horizons: list[int] = Field(default_factory=lambda: [1, 5, 20])+ regime_label_artifact_ref: str | None = None+ min_walk_forward_folds: int | None = None+ neutralization: Literal["none", "industry", "size", "industry_size"] = "none"+ random_control_required: bool = True+ regime_tests_required: bool = False+ crowding_tests_required: bool = False+++class ResearchProtocol(BaseModel):+ """A typed research experiment design."""++ model_config = ConfigDict(allow_inf_nan=False, arbitrary_types_allowed=False)++ protocol_id: str+ protocol_hash: str = ""+ schema_version: str+ status: ProtocolStatus = "draft"+ goal_id: str | None = None+ session_id: str | None = None+ hypothesis_id: str | None = None+ hypothesis: str+ universe: UniverseSpec+ data_requirements: list[DataSetContract]+ split_policy: SplitSpec+ benchmark_policy: BenchmarkSpec | None = None+ cost_model: CostModelSpec | None = None+ execution_assumptions: ExecutionAssumptions | None = None+ evaluation_plan: EvaluationPlan+ created_at: datetime+ registered_at: datetime | None = None+ created_by: str+ metadata: dict[str, Any] = Field(default_factory=dict)++ @model_validator(mode="before")+ @classmethod+ def _reject_non_json_values(cls, value: Any) -> Any:+ _reject_pandas_or_nonfinite(value, path="$")+ return value++ @field_validator("created_at", "registered_at")+ @classmethod+ def _datetime_must_be_aware(cls, value: datetime | None) -> datetime | None:+ if value is None:+ return None+ if value.tzinfo is None or value.utcoffset() is None:+ raise ValueError("datetime fields must be timezone-aware")+ return value.astimezone(timezone.utc)+++def _reject_pandas_or_nonfinite(value: Any, *, path: str) -> None:+ module = type(value).__module__+ name = type(value).__name__+ if module.startswith("pandas.") and name in {"DataFrame", "Series"}:+ raise ValueError(f"{path}: pandas objects are not allowed in ResearchProtocol")+ if isinstance(value, float) and not math.isfinite(value):+ raise ValueError(f"{path}: floats must be finite")+ if isinstance(value, dict):+ for key, item in value.items():+ _reject_pandas_or_nonfinite(item, path=f"{path}.{key}")+ elif isinstance(value, (list, tuple, set)):+ for index, item in enumerate(value):+ _reject_pandas_or_nonfinite(item, path=f"{path}[{index}]")diff --git a/agent/src/research_protocol/registry.py b/agent/src/research_protocol/registry.pynew file mode 100644index 000000000..a82989ed0--- /dev/null+++ b/agent/src/research_protocol/registry.py@@ -0,0 +1,109 @@+"""Filesystem protocol registry with artifact-backed registration."""++from __future__ import annotations++import json+from datetime import datetime, timezone+from pathlib import Path++from src.reliability.artifacts.model import ArtifactRef+from src.reliability.artifacts.store import ArtifactStore+from src.research_protocol.hashing import compute_protocol_hash+from src.research_protocol.model import ResearchProtocol+++class ProtocolImmutableError(ValueError):+ """Raised when a registered protocol is mutated in place."""+++class ProtocolRegistry:+ """Store draft/registered protocols without replacing GoalStore or Hypotheses."""++ def __init__(self, root: Path | None = None, *, artifact_root: Path | None = None) -> None:+ self.root = Path(root) if root is not None else Path.home() / ".vibe-trading" / "research-protocols"+ self.root.mkdir(parents=True, exist_ok=True)+ self.artifact_store = ArtifactStore(root=artifact_root) if artifact_root is not None else ArtifactStore()++ def save_draft(self, protocol: ResearchProtocol) -> ResearchProtocol:+ """Persist a draft protocol; registered protocols are immutable."""++ existing = self.get(protocol.protocol_id)+ if existing is not None and existing.status == "registered":+ raise ProtocolImmutableError(f"registered protocol is immutable: {protocol.protocol_id}")+ if protocol.status == "registered":+ raise ProtocolImmutableError("use register() to create registered protocols")+ draft = protocol.model_copy(update={"status": "draft", "protocol_hash": compute_protocol_hash(protocol)})+ self._write_protocol(draft)+ return draft++ def register(self, protocol_id: str, *, created_by: str | None = None) -> ResearchProtocol:+ """Register a draft protocol and write a research_protocol artifact."""++ current = self.get(protocol_id)+ if current is None:+ raise KeyError(f"protocol not found: {protocol_id}")+ if current.status == "registered":+ return current+ digest = compute_protocol_hash(current)+ registered = current.model_copy(+ update={+ "status": "registered",+ "protocol_hash": digest,+ "registered_at": datetime.now(timezone.utc),+ "created_by": created_by or current.created_by,+ }+ )+ self._write_protocol(registered)+ record = self.artifact_store.write_json(+ registered.model_dump(mode="json"),+ artifact_type="research_protocol",+ generated_by="ProtocolRegistry",+ metadata={+ "protocol_id": registered.protocol_id,+ "protocol_hash": registered.protocol_hash,+ "goal_id": registered.goal_id,+ "hypothesis_id": registered.hypothesis_id,+ },+ )+ if record is not None:+ self._write_artifact_ref(registered.protocol_hash, record.to_ref())+ return registered++ def get(self, protocol_id: str) -> ResearchProtocol | None:+ path = self._protocol_path(protocol_id)+ if not path.exists():+ return None+ return ResearchProtocol.model_validate_json(path.read_text(encoding="utf-8"))++ def is_registered(self, protocol_hash: str) -> bool:+ for path in self.root.glob("*.json"):+ protocol = ResearchProtocol.model_validate_json(path.read_text(encoding="utf-8"))+ if protocol.status == "registered" and protocol.protocol_hash == protocol_hash:+ return True+ return False++ def artifact_refs_for(self, protocol_hash: str) -> list[ArtifactRef]:+ path = self.root / f"{protocol_hash}.artifact_refs.json"+ if not path.exists():+ return []+ raw = json.loads(path.read_text(encoding="utf-8"))+ return [ArtifactRef.model_validate(item) for item in raw]++ def _protocol_path(self, protocol_id: str) -> Path:+ safe = "".join(ch for ch in protocol_id if ch.isalnum() or ch in {"_", "-"})+ if not safe:+ raise ValueError("protocol_id must contain a safe filename character")+ return self.root / f"{safe}.json"++ def _write_protocol(self, protocol: ResearchProtocol) -> None:+ path = self._protocol_path(protocol.protocol_id)+ path.write_text(protocol.model_dump_json(indent=2), encoding="utf-8")++ def _write_artifact_ref(self, protocol_hash: str, ref: ArtifactRef) -> None:+ path = self.root / f"{protocol_hash}.artifact_refs.json"+ refs = self.artifact_refs_for(protocol_hash)+ refs.append(ref)+ path.write_text(+ json.dumps([item.model_dump(mode="json") for item in refs], ensure_ascii=False, indent=2),+ encoding="utf-8",+ )diff --git a/agent/src/research_protocol/trial.py b/agent/src/research_protocol/trial.pynew file mode 100644index 000000000..0eb679032--- /dev/null+++ b/agent/src/research_protocol/trial.py@@ -0,0 +1,56 @@+"""Trial ledger event models."""++from __future__ import annotations++from datetime import datetime, timezone+from enum import Enum+from typing import Any+from uuid import uuid4++from pydantic import BaseModel, Field, field_validator+++TRIAL_EVENT_SCHEMA_VERSION = "1.0.0"+++class TrialEventType(str, Enum):+ PROTOCOL_REGISTERED = "protocol_registered"+ TRIAL_STARTED = "trial_started"+ DATA_LOADED = "data_loaded"+ TOOL_CALLED = "tool_called"+ POLICY_DECISION_RECORDED = "policy_decision_recorded"+ BACKTEST_COMPLETED = "backtest_completed"+ ALPHA_BENCH_COMPLETED = "alpha_bench_completed"+ SCORECARD_GENERATED = "scorecard_generated"+ RESEARCH_CARD_GENERATED = "research_card_generated"+ TRIAL_ACCEPTED = "trial_accepted"+ TRIAL_REJECTED = "trial_rejected"+ TRIAL_ABANDONED = "trial_abandoned"+++class TrialEvent(BaseModel):+ """One immutable event in the trial hash chain."""++ event_id: str = Field(default_factory=lambda: f"te_{uuid4().hex}")+ event_type: TrialEventType+ schema_version: str = TRIAL_EVENT_SCHEMA_VERSION+ protocol_hash: str+ sequence_number: int+ previous_event_hash: str | None = None+ event_hash: str+ created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))+ payload: dict[str, Any] = Field(default_factory=dict)+ artifact_refs: list[str] = Field(default_factory=list)++ @field_validator("created_at")+ @classmethod+ def _created_at_must_be_aware(cls, value: datetime) -> datetime:+ if value.tzinfo is None or value.utcoffset() is None:+ raise ValueError("created_at must be timezone-aware")+ return value.astimezone(timezone.utc)+++class LedgerVerificationResult(BaseModel):+ valid: bool+ event_count: int+ errors: list[str] = Field(default_factory=list)diff --git a/agent/tests/research_protocol/__init__.py b/agent/tests/research_protocol/__init__.pynew file mode 100644index 000000000..8d3127b05--- /dev/null+++ b/agent/tests/research_protocol/__init__.py@@ -0,0 +1 @@+"""Research protocol tests."""diff --git a/agent/tests/research_protocol/test_accepted_result_gates.py b/agent/tests/research_protocol/test_accepted_result_gates.pynew file mode 100644index 000000000..79f3734bc--- /dev/null+++ b/agent/tests/research_protocol/test_accepted_result_gates.py@@ -0,0 +1,65 @@+from __future__ import annotations++from pathlib import Path++import pytest++from src.research_protocol.acceptance import (+ AcceptanceError,+ AcceptedResult,+ validate_accepted_result,+)+from src.research_protocol.registry import ProtocolRegistry++from .test_protocol_models import make_protocol+++def _registered_hash(tmp_path: Path) -> str:+ registry = ProtocolRegistry(root=tmp_path / "protocols", artifact_root=tmp_path / "artifacts")+ draft = registry.save_draft(make_protocol())+ return registry.register(draft.protocol_id, created_by="tester").protocol_hash+++def _accepted(protocol_hash: str, **updates) -> AcceptedResult:+ payload = {+ "protocol_hash": protocol_hash,+ "trial_count": 3,+ "data_audit_ids": ["audit_1"],+ "policy_decision_ids": ["pd_1"],+ "backtest_artifact_refs": ["art_backtest_1"],+ "alpha_artifact_refs": [],+ "best_trial": False,+ "selection_policy": None,+ "abandoned_count": 0,+ "rejected_count": 0,+ }+ payload.update(updates)+ return AcceptedResult(**payload)+++def test_accepted_result_requires_registered_protocol(tmp_path: Path) -> None:+ registry = ProtocolRegistry(root=tmp_path / "protocols", artifact_root=tmp_path / "artifacts")++ with pytest.raises(AcceptanceError, match="registered protocol"):+ validate_accepted_result(_accepted("missing_hash"), registry=registry)+++def test_accepted_result_requires_trial_count(tmp_path: Path) -> None:+ protocol_hash = _registered_hash(tmp_path)++ with pytest.raises(AcceptanceError, match="trial_count"):+ validate_accepted_result(_accepted(protocol_hash, trial_count=None))+++def test_best_trial_requires_selection_policy(tmp_path: Path) -> None:+ protocol_hash = _registered_hash(tmp_path)++ with pytest.raises(AcceptanceError, match="selection policy"):+ validate_accepted_result(+ _accepted(protocol_hash, best_trial=True, selection_policy=None, abandoned_count=1, rejected_count=1)+ )++ with pytest.raises(AcceptanceError, match="abandoned/rejected"):+ validate_accepted_result(+ _accepted(protocol_hash, best_trial=True, selection_policy="highest OOS IC")+ )diff --git a/agent/tests/research_protocol/test_protocol_hash.py b/agent/tests/research_protocol/test_protocol_hash.pynew file mode 100644index 000000000..222544b7c--- /dev/null+++ b/agent/tests/research_protocol/test_protocol_hash.py@@ -0,0 +1,51 @@+from __future__ import annotations++import math++import pytest+from pydantic import ValidationError++from src.research_protocol.hashing import compute_protocol_hash+from src.research_protocol.model import UniverseSpec++from .test_protocol_models import make_protocol+++GOLDEN_PROTOCOL_HASH = "c78e4d2f6be110a879541467a317fc837b0c365ad9040957143a468a7fec7109"+++def test_protocol_hash_stable_for_fixture() -> None:+ assert compute_protocol_hash(make_protocol()) == GOLDEN_PROTOCOL_HASH+++def test_protocol_hash_changes_when_universe_changes() -> None:+ original = compute_protocol_hash(make_protocol())+ changed = compute_protocol_hash(+ make_protocol(+ universe=UniverseSpec(+ asset_class="ashare",+ universe_name="zz500",+ point_in_time=True,+ )+ )+ )++ assert changed != original+++def test_protocol_hash_ignores_metadata_and_ids() -> None:+ original = compute_protocol_hash(make_protocol())+ noisy = make_protocol(+ protocol_id="proto_other",+ protocol_hash="old_hash",+ status="registered",+ created_by="someone_else",+ metadata={"note": "this should not affect research design"},+ )++ assert compute_protocol_hash(noisy) == original+++def test_protocol_hash_rejects_nan() -> None:+ with pytest.raises(ValidationError, match="finite"):+ make_protocol(cost_model={"commission_bps": math.nan})diff --git a/agent/tests/research_protocol/test_protocol_models.py b/agent/tests/research_protocol/test_protocol_models.pynew file mode 100644index 000000000..56242c3ea--- /dev/null+++ b/agent/tests/research_protocol/test_protocol_models.py@@ -0,0 +1,102 @@+from __future__ import annotations++from datetime import datetime, timezone++import pandas as pd+import pytest+from pydantic import ValidationError++from src.research_protocol.model import (+ BenchmarkSpec,+ CostModelSpec,+ DataSetContract,+ EvaluationPlan,+ ExecutionAssumptions,+ FilterSpec,+ ResearchProtocol,+ SplitSpec,+ UniverseSpec,+)+++def make_protocol(**updates) -> ResearchProtocol:+ payload = {+ "protocol_id": "proto_fixture",+ "schema_version": "1.0.0",+ "status": "draft",+ "goal_id": "goal_abc",+ "session_id": "session_abc",+ "hypothesis_id": "hyp_abc",+ "hypothesis": "CSI300 short-term reversal has positive next-day IC.",+ "universe": UniverseSpec(+ asset_class="ashare",+ universe_name="csi300",+ point_in_time=True,+ filters=[FilterSpec(field="is_st", op="eq", value_json="false")],+ ),+ "data_requirements": [+ DataSetContract(+ dataset_id="tushare:ohlcv:1D",+ asset_class="ashare",+ frequency="1D",+ calendar="SSE",+ fields=["open", "high", "low", "close", "volume"],+ timezone="Asia/Shanghai",+ survivorship_policy="historical_membership",+ )+ ],+ "split_policy": SplitSpec(+ method="walk_forward",+ train_start="2020-01-01",+ train_end="2021-12-31",+ test_start="2022-01-01",+ test_end="2023-12-31",+ fold_count=6,+ min_effective_folds=4,+ ),+ "benchmark_policy": BenchmarkSpec(primary="000300.SH", source="tushare"),+ "cost_model": CostModelSpec(commission_bps=3.0, slippage_bps=5.0, tax_bps=10.0),+ "execution_assumptions": ExecutionAssumptions(+ signal_time_field="close",+ decision_delay="1D",+ order_type="market",+ fill_price="next_open",+ ),+ "evaluation_plan": EvaluationPlan(+ metrics=["rank_ic", "icir"],+ min_walk_forward_folds=4,+ neutralization="industry_size",+ regime_tests_required=True,+ crowding_tests_required=True,+ ),+ "created_at": datetime(2026, 7, 6, 12, 0, tzinfo=timezone.utc),+ "created_by": "tester",+ }+ payload.update(updates)+ return ResearchProtocol(**payload)+++def test_protocol_json_roundtrip() -> None:+ protocol = make_protocol()++ reloaded = ResearchProtocol.model_validate_json(protocol.model_dump_json())++ assert reloaded == protocol+ assert isinstance(reloaded.universe, UniverseSpec)+ assert isinstance(reloaded.split_policy, SplitSpec)+ assert isinstance(reloaded.evaluation_plan, EvaluationPlan)+ assert reloaded.evaluation_plan.ic_horizons == [1, 5, 20]+ assert reloaded.evaluation_plan.random_control_required is True+++def test_registered_protocol_requires_timezone_aware_datetime() -> None:+ with pytest.raises(ValidationError, match="timezone-aware"):+ make_protocol(status="registered", registered_at=datetime(2026, 7, 6, 12, 0))+++def test_protocol_rejects_dataframe_or_series_fields() -> None:+ with pytest.raises(ValidationError, match="pandas"):+ make_protocol(metadata={"labels": pd.Series([1, 2, 3])})++ with pytest.raises(ValidationError, match="pandas"):+ make_protocol(metadata={"frame": pd.DataFrame({"x": [1]})})diff --git a/agent/tests/research_protocol/test_protocol_registry.py b/agent/tests/research_protocol/test_protocol_registry.pynew file mode 100644index 000000000..220546d0f--- /dev/null+++ b/agent/tests/research_protocol/test_protocol_registry.py@@ -0,0 +1,42 @@+from __future__ import annotations++from pathlib import Path++import pytest++from src.research_protocol.hashing import compute_protocol_hash+from src.research_protocol.registry import ProtocolImmutableError, ProtocolRegistry++from .test_protocol_models import make_protocol+++def test_registered_protocol_is_immutable(tmp_path: Path) -> None:+ registry = ProtocolRegistry(root=tmp_path / "protocols")+ draft = registry.save_draft(make_protocol())+ registered = registry.register(draft.protocol_id, created_by="tester")++ with pytest.raises(ProtocolImmutableError):+ registry.save_draft(registered.model_copy(update={"hypothesis": "changed"}))++ reloaded = registry.get(registered.protocol_id)+ assert reloaded is not None+ assert reloaded.hypothesis == draft.hypothesis+ assert reloaded.protocol_hash == compute_protocol_hash(draft)+ assert reloaded.status == "registered"+++def test_register_creates_artifact_ref(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("VIBE_TRADING_RELIABILITY_MODE", "observe")+ registry = ProtocolRegistry(+ root=tmp_path / "protocols",+ artifact_root=tmp_path / "artifacts",+ )+ draft = registry.save_draft(make_protocol())++ registered = registry.register(draft.protocol_id, created_by="tester")++ refs = registry.artifact_refs_for(registered.protocol_hash)+ assert registered.protocol_hash+ assert refs+ assert refs[0].artifact_type == "research_protocol"+ assert refs[0].sha256diff --git a/agent/tests/research_protocol/test_trial_ledger.py b/agent/tests/research_protocol/test_trial_ledger.pynew file mode 100644index 000000000..0939f8c97--- /dev/null+++ b/agent/tests/research_protocol/test_trial_ledger.py@@ -0,0 +1,51 @@+from __future__ import annotations++import json+import sqlite3+from pathlib import Path++from src.research_protocol.ledger import TrialLedger+from src.research_protocol.trial import TrialEventType++from .test_protocol_hash import GOLDEN_PROTOCOL_HASH+++def test_trial_ledger_append_creates_linear_hash_chain(tmp_path: Path) -> None:+ ledger = TrialLedger(tmp_path / "ledger.sqlite")++ first = ledger.append(+ protocol_hash=GOLDEN_PROTOCOL_HASH,+ event_type=TrialEventType.PROTOCOL_REGISTERED,+ payload={"protocol_id": "proto_fixture"},+ )+ second = ledger.append(+ protocol_hash=GOLDEN_PROTOCOL_HASH,+ event_type=TrialEventType.TRIAL_STARTED,+ payload={"trial_id": "trial_1"},+ )++ assert first.sequence_number == 1+ assert second.sequence_number == 2+ assert first.previous_event_hash is None+ assert second.previous_event_hash == first.event_hash+ assert ledger.verify().valid is True+ assert ledger.verify().event_count == 2+++def test_trial_ledger_verify_detects_tamper(tmp_path: Path) -> None:+ ledger = TrialLedger(tmp_path / "ledger.sqlite")+ event = ledger.append(+ protocol_hash=GOLDEN_PROTOCOL_HASH,+ event_type=TrialEventType.TRIAL_STARTED,+ payload={"trial_id": "trial_1"},+ )++ with sqlite3.connect(tmp_path / "ledger.sqlite") as conn:+ conn.execute(+ "UPDATE trial_events SET payload_json = ? WHERE event_id = ?",+ (json.dumps({"trial_id": "tampered"}, sort_keys=True), event.event_id),+ )++ result = ledger.verify()+ assert result.valid is False+ assert any("event_hash" in error for error in result.errors)diff --git a/agent/tests/research_protocol/test_trial_ledger_concurrency.py b/agent/tests/research_protocol/test_trial_ledger_concurrency.pynew file mode 100644index 000000000..be039e120--- /dev/null+++ b/agent/tests/research_protocol/test_trial_ledger_concurrency.py@@ -0,0 +1,78 @@+from __future__ import annotations++import sqlite3+import threading+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import pytest++from src.research_protocol.ledger import TrialLedger+from src.research_protocol.trial import TrialEventType++from .test_protocol_hash import GOLDEN_PROTOCOL_HASH+++def test_trial_ledger_concurrent_appends_do_not_fork(tmp_path: Path) -> None:+ path = tmp_path / "ledger.sqlite"++ def append_one(index: int):+ return TrialLedger(path).append(+ protocol_hash=GOLDEN_PROTOCOL_HASH,+ event_type=TrialEventType.TOOL_CALLED,+ payload={"index": index},+ )++ with ThreadPoolExecutor(max_workers=8) as pool:+ events = list(pool.map(append_one, range(32)))++ sequences = sorted(event.sequence_number for event in events)+ assert sequences == list(range(1, 33))+ assert TrialLedger(path).verify().valid is True+++def test_trial_ledger_concurrent_appends_do_not_lose_events_100(tmp_path: Path) -> None:+ path = tmp_path / "ledger.sqlite"++ def append_one(index: int):+ return TrialLedger(path).append(+ protocol_hash=GOLDEN_PROTOCOL_HASH,+ event_type=TrialEventType.POLICY_DECISION_RECORDED,+ payload={"policy_decision_id": f"pd_{index}"},+ )++ with ThreadPoolExecutor(max_workers=16) as pool:+ list(pool.map(append_one, range(100)))++ verification = TrialLedger(path).verify()+ assert verification.valid is True+ assert verification.event_count == 100+++def test_sqlite_locked_retries(tmp_path: Path) -> None:+ path = tmp_path / "ledger.sqlite"+ ledger = TrialLedger(path, write_retry_count=8, write_retry_delay_ms=20)+ blocker = sqlite3.connect(path, timeout=0.1, check_same_thread=False)+ blocker.execute("BEGIN IMMEDIATE")++ def release_lock() -> None:+ blocker.rollback()+ blocker.close()++ timer = threading.Timer(0.08, release_lock)+ timer.start()+ try:+ event = ledger.append(+ protocol_hash=GOLDEN_PROTOCOL_HASH,+ event_type=TrialEventType.TRIAL_STARTED,+ payload={"trial_id": "retry"},+ )+ finally:+ timer.cancel()+ try:+ blocker.close()+ except sqlite3.Error:+ pass++ assert event.sequence_number == 1+ assert ledger.verify().valid is True