"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(cli): hypothesis registry — list / show / invalidate
Haozhe Wudda06ae3512f
diff --git a/agent/cli.py b/agent/cli.pyindex b78457db6..624073a02 100644--- a/agent/cli.py+++ b/agent/cli.py@@ -2652,6 +2652,10 @@ def _build_parser() -> argparse.ArgumentParser:from src.factors.cli_handlers import add_subparser as _add_alpha_subparser_add_alpha_subparser(subparsers)+ # Hypothesis Registry subcommands+ from src.hypotheses.cli_handlers import add_subparser as _add_hypothesis_subparser+ _add_hypothesis_subparser(subparsers)+return parser@@ -3140,6 +3144,9 @@ def main(argv: list[str] | None = None) -> int:if args.command == "alpha":from src.factors.cli_handlers import dispatch as _alpha_dispatchreturn _coerce_exit_code(_alpha_dispatch(args))+ if args.command == "hypothesis":+ from src.hypotheses.cli_handlers import dispatch as _hyp_dispatch+ return _coerce_exit_code(_hyp_dispatch(args))if args.command == "memory":if args.memory_command == "list":return _coerce_exit_code(cmd_memory_list(args.memory_type))diff --git a/agent/src/hypotheses/cli_handlers.py b/agent/src/hypotheses/cli_handlers.pynew file mode 100644index 000000000..d8fbd6968--- /dev/null+++ b/agent/src/hypotheses/cli_handlers.py@@ -0,0 +1,323 @@+"""CLI handlers for ``vibe-trading hypothesis {list,show,invalidate}``.++All logic lives here; ``agent/cli.py`` only wires this in via :func:`add_subparser`+and :func:`dispatch`. Handlers print to stdout (Rich when available, plain+``print`` fallback) and return an int exit code. Errors are reported as a+one-line stderr message; tracebacks are suppressed unless ``--verbose`` is set+on the namespace.++Storage path resolution defers to :func:`default_hypotheses_path`, so callers+(and tests) can override via the ``VIBE_TRADING_HYPOTHESES_PATH`` env var or by+passing ``--path``.+"""++from __future__ import annotations++import argparse+import json+import sys+import traceback+from pathlib import Path+from typing import Any, Callable++try:+ from rich.console import Console+ from rich.panel import Panel+ from rich.table import Table++ _console: Console | None = Console()+except Exception: # pragma: no cover — rich is a project dep, fallback only+ _console = None+ Table = None # type: ignore[assignment]+ Panel = None # type: ignore[assignment]++from src.hypotheses.registry import (+ HYPOTHESIS_STATUSES,+ Hypothesis,+ HypothesisRegistry,+)+++_STATUS_STYLES = {+ "exploring": "cyan",+ "testing": "yellow",+ "validated": "green",+ "rejected": "red",+ "monitoring": "magenta",+}+++def _print(msg: str) -> None:+ if _console is not None:+ _console.print(msg)+ else:+ print(msg)+++def _err(msg: str) -> None:+ print(msg, file=sys.stderr)+++def _registry(args: argparse.Namespace) -> HypothesisRegistry:+ override = getattr(args, "path", None)+ if override:+ return HypothesisRegistry(path=Path(override).expanduser())+ return HypothesisRegistry()+++def _hypothesis_payload(hyp: Hypothesis) -> dict[str, Any]:+ return hyp.to_dict()+++def _emit_table(rows: list[Hypothesis]) -> None:+ if Table is None:+ for hyp in rows:+ print(+ f"{hyp.hypothesis_id}\t{hyp.status}\t{hyp.title}\t{hyp.updated_at}"+ )+ return+ table = Table(title=f"Hypotheses ({len(rows)})", show_lines=False)+ table.add_column("ID", style="bold", overflow="fold")+ table.add_column("Status")+ table.add_column("Title", overflow="fold")+ table.add_column("Universe", overflow="fold")+ table.add_column("Run cards", justify="right")+ table.add_column("Updated", overflow="fold")+ for hyp in rows:+ status_style = _STATUS_STYLES.get(hyp.status, "white")+ table.add_row(+ hyp.hypothesis_id,+ f"[{status_style}]{hyp.status}[/{status_style}]",+ hyp.title,+ hyp.universe or "-",+ str(len(hyp.run_cards)),+ hyp.updated_at,+ )+ # Use a wide non-TTY console so piped/captured output keeps each row on+ # one line; interactive TTYs continue to honor the live terminal width+ # via the module-level _console.+ if sys.stdout.isatty() and _console is not None:+ _console.print(table)+ else:+ Console(width=200, force_terminal=False).print(table)+++def _emit_detail(hyp: Hypothesis) -> None:+ if _console is None or Panel is None:+ print(json.dumps(hyp.to_dict(), ensure_ascii=False, indent=2))+ return+ status_style = _STATUS_STYLES.get(hyp.status, "white")+ body_lines = [+ f"[bold]ID:[/bold] {hyp.hypothesis_id}",+ f"[bold]Status:[/bold] [{status_style}]{hyp.status}[/{status_style}]",+ f"[bold]Universe:[/bold] {hyp.universe or '-'}",+ f"[bold]Data sources:[/bold] {', '.join(hyp.data_sources) or '-'}",+ f"[bold]Skills:[/bold] {', '.join(hyp.skills) or '-'}",+ f"[bold]Created:[/bold] {hyp.created_at}",+ f"[bold]Updated:[/bold] {hyp.updated_at}",+ "",+ "[bold]Thesis[/bold]",+ hyp.thesis or "-",+ ]+ if hyp.signal_definition:+ body_lines.extend(["", "[bold]Signal[/bold]", hyp.signal_definition])+ if hyp.invalidation_notes:+ body_lines.extend(+ ["", "[bold red]Invalidation notes[/bold red]", hyp.invalidation_notes]+ )+ if hyp.run_cards:+ body_lines.append("")+ body_lines.append(f"[bold]Linked run cards ({len(hyp.run_cards)})[/bold]")+ for idx, link in enumerate(hyp.run_cards, 1):+ run_card_path = link.get("run_card_path") or "-"+ run_dir = link.get("backtest_run_dir") or "-"+ note = link.get("notes") or ""+ linked_at = link.get("linked_at") or "-"+ body_lines.append(+ f" {idx}. run_card={run_card_path} run_dir={run_dir} linked={linked_at}"+ )+ if note:+ body_lines.append(f" note: {note}")+ _console.print(Panel("\n".join(body_lines), title=hyp.title, expand=False))+++def _cmd_list(args: argparse.Namespace) -> int:+ registry = _registry(args)+ status_filter: str | None = getattr(args, "status", None)+ limit: int = max(0, int(getattr(args, "limit", 50) or 0))+ rows = registry.list()+ if status_filter:+ rows = [hyp for hyp in rows if hyp.status == status_filter]+ rows.sort(key=lambda h: h.updated_at, reverse=True)+ if limit:+ rows = rows[:limit]++ if getattr(args, "json", False):+ print(+ json.dumps(+ [_hypothesis_payload(hyp) for hyp in rows],+ ensure_ascii=False,+ indent=2,+ )+ )+ return 0++ if not rows:+ suffix = f" status={status_filter}" if status_filter else ""+ _print(f"No hypotheses found{suffix}.")+ return 0+ _emit_table(rows)+ return 0+++def _cmd_show(args: argparse.Namespace) -> int:+ registry = _registry(args)+ hypothesis_id = args.hypothesis_id+ for hyp in registry.list():+ if hyp.hypothesis_id == hypothesis_id:+ if getattr(args, "json", False):+ print(json.dumps(hyp.to_dict(), ensure_ascii=False, indent=2))+ else:+ _emit_detail(hyp)+ return 0+ _err(f"hypothesis not found: {hypothesis_id}")+ return 1+++def _cmd_invalidate(args: argparse.Namespace) -> int:+ registry = _registry(args)+ note = (getattr(args, "note", "") or "").strip()+ try:+ hyp = registry.update(+ args.hypothesis_id,+ status="rejected",+ invalidation_notes=note if note else None,+ )+ except KeyError:+ _err(f"hypothesis not found: {args.hypothesis_id}")+ return 1+ except ValueError as exc:+ _err(f"invalid update: {exc}")+ return 2++ if getattr(args, "json", False):+ print(json.dumps(hyp.to_dict(), ensure_ascii=False, indent=2))+ else:+ _print(+ f"[red]rejected[/red] {hyp.hypothesis_id} — {hyp.title}"+ + (f"\n note: {note}" if note else "")+ )+ return 0+++_DISPATCH: dict[str, Callable[[argparse.Namespace], int]] = {+ "list": _cmd_list,+ "show": _cmd_show,+ "invalidate": _cmd_invalidate,+}+++_HYP_PARSER: argparse.ArgumentParser | None = None+++def add_subparser(subparsers: Any) -> argparse.ArgumentParser:+ """Register ``hypothesis`` and its three sub-sub-commands on the parent+ subparsers.++ Args:+ subparsers: The object returned by ``ArgumentParser.add_subparsers(...)``.++ Returns:+ The ``hypothesis`` parser (mostly for test introspection).+ """+ global _HYP_PARSER++ hyp_parser = subparsers.add_parser(+ "hypothesis",+ help="Hypothesis Registry: list / show / invalidate",+ )+ hyp_parser.add_argument(+ "--verbose", action="store_true", help="Show full traceback on errors"+ )+ hyp_parser.add_argument(+ "--path",+ default=None,+ help=(+ "Override registry JSON path (also respects "+ "VIBE_TRADING_HYPOTHESES_PATH env var)"+ ),+ )+ hyp_sub = hyp_parser.add_subparsers(dest="hypothesis_command")++ p_list = hyp_sub.add_parser("list", help="List hypotheses")+ p_list.add_argument(+ "--status",+ choices=HYPOTHESIS_STATUSES,+ default=None,+ help="Filter by lifecycle status",+ )+ p_list.add_argument(+ "--limit",+ type=int,+ default=50,+ help="Maximum rows to print (default: 50; pass 0 for no cap)",+ )+ p_list.add_argument(+ "--json",+ action="store_true",+ help="Emit JSON array instead of a table",+ )++ p_show = hyp_sub.add_parser("show", help="Show hypothesis detail")+ p_show.add_argument("hypothesis_id", help="Hypothesis id, e.g. hyp_abcd1234ef56")+ p_show.add_argument(+ "--json",+ action="store_true",+ help="Emit JSON object instead of a panel",+ )++ p_invalidate = hyp_sub.add_parser(+ "invalidate", help="Mark a hypothesis as rejected with optional notes"+ )+ p_invalidate.add_argument(+ "hypothesis_id", help="Hypothesis id to invalidate"+ )+ p_invalidate.add_argument(+ "--note",+ default="",+ help="Invalidation note recorded on the hypothesis",+ )+ p_invalidate.add_argument(+ "--json",+ action="store_true",+ help="Emit JSON object of the updated hypothesis",+ )++ _HYP_PARSER = hyp_parser+ return hyp_parser+++def dispatch(args: argparse.Namespace) -> int:+ """Dispatch ``hypothesis <sub>`` to the matching handler.++ Returns the exit code; ``cli.py`` propagates it via ``_coerce_exit_code``.+ """+ sub = getattr(args, "hypothesis_command", None)+ if sub is None:+ if _HYP_PARSER is not None:+ _HYP_PARSER.print_help()+ else:+ _err("hypothesis requires a subcommand. Try: vibe-trading hypothesis list")+ return 1+ handler = _DISPATCH.get(sub)+ if handler is None:+ _err(f"unknown hypothesis subcommand: {sub}")+ return 1+ try:+ return int(handler(args))+ except Exception as exc: # noqa: BLE001 — surface as one-line stderr+ if getattr(args, "verbose", False):+ traceback.print_exc()+ else:+ _err(f"hypothesis {sub} failed: {exc}")+ return 1diff --git a/agent/tests/test_cli_hypothesis.py b/agent/tests/test_cli_hypothesis.pynew file mode 100644index 000000000..f30c0d93b--- /dev/null+++ b/agent/tests/test_cli_hypothesis.py@@ -0,0 +1,313 @@+"""Tests for the ``vibe-trading hypothesis`` CLI subcommands."""++from __future__ import annotations++import argparse+import json+from pathlib import Path++import pytest++from src.hypotheses import HypothesisRegistry+from src.hypotheses.cli_handlers import (+ add_subparser,+ dispatch,+)+++def _make_registry(tmp_path: Path) -> tuple[HypothesisRegistry, Path]:+ storage = tmp_path / "hypotheses.json"+ return HypothesisRegistry(path=storage), storage+++def _seed(reg: HypothesisRegistry) -> list[str]:+ """Seed three hypotheses spanning multiple statuses; return their ids."""+ a = reg.create(+ title="Mean-reversion on CSI300",+ thesis="Short-horizon dispersion → reversion edge.",+ universe="csi300",+ data_sources=["tushare"],+ skills=["factor-research"],+ )+ b = reg.create(+ title="Earnings drift on US large caps",+ thesis="Post-earnings drift in SPY components.",+ status="testing",+ universe="sp500",+ )+ c = reg.create(+ title="BTC funding skew",+ thesis="Perp funding extremes mean-revert.",+ status="validated",+ universe="btc-usdt",+ )+ return [a.hypothesis_id, b.hypothesis_id, c.hypothesis_id]+++def _build_args(**kwargs: object) -> argparse.Namespace:+ """Build a Namespace pre-populated with sane defaults that ``_registry``+ and handlers expect to read."""+ defaults: dict[str, object] = {+ "path": None,+ "verbose": False,+ "json": False,+ "status": None,+ "limit": 50,+ "note": "",+ }+ defaults.update(kwargs)+ return argparse.Namespace(**defaults)+++class TestParserWiring:+ def test_subparser_registers_three_commands(self) -> None:+ parser = argparse.ArgumentParser()+ sub = parser.add_subparsers(dest="command")+ hyp_parser = add_subparser(sub)+ # Parse each subcommand to confirm wiring.+ for sub_cmd in ("list", "show", "invalidate"):+ assert hyp_parser is not None+ args = parser.parse_args(["hypothesis", "list", "--status", "rejected"])+ assert args.hypothesis_command == "list"+ assert args.status == "rejected"+ args = parser.parse_args(["hypothesis", "show", "hyp_xyz"])+ assert args.hypothesis_command == "show"+ assert args.hypothesis_id == "hyp_xyz"+ args = parser.parse_args(+ ["hypothesis", "invalidate", "hyp_xyz", "--note", "data leak"]+ )+ assert args.hypothesis_command == "invalidate"+ assert args.note == "data leak"++ def test_dispatch_without_subcommand_returns_one(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ args = _build_args(path=str(tmp_path / "h.json"), hypothesis_command=None)+ assert dispatch(args) == 1+++class TestList:+ def test_empty_registry(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ args = _build_args(+ path=str(tmp_path / "h.json"), hypothesis_command="list"+ )+ rc = dispatch(args)+ out = capsys.readouterr().out+ assert rc == 0+ assert "No hypotheses found" in out++ def test_lists_all(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ reg, storage = _make_registry(tmp_path)+ _seed(reg)+ args = _build_args(path=str(storage), hypothesis_command="list")+ rc = dispatch(args)+ out = capsys.readouterr().out+ assert rc == 0+ assert "Mean-reversion on CSI300" in out+ assert "Earnings drift on US large caps" in out+ assert "BTC funding skew" in out++ def test_status_filter(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ reg, storage = _make_registry(tmp_path)+ _seed(reg)+ args = _build_args(+ path=str(storage), hypothesis_command="list", status="validated"+ )+ rc = dispatch(args)+ out = capsys.readouterr().out+ assert rc == 0+ assert "BTC funding skew" in out+ assert "Earnings drift" not in out+ assert "Mean-reversion" not in out++ def test_status_filter_with_no_matches(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ reg, storage = _make_registry(tmp_path)+ _seed(reg)+ args = _build_args(+ path=str(storage), hypothesis_command="list", status="rejected"+ )+ rc = dispatch(args)+ out = capsys.readouterr().out+ assert rc == 0+ assert "No hypotheses found status=rejected" in out++ def test_limit(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ reg, storage = _make_registry(tmp_path)+ _seed(reg)+ args = _build_args(path=str(storage), hypothesis_command="list", limit=1)+ rc = dispatch(args)+ out = capsys.readouterr().out+ assert rc == 0+ # Exactly one of the three seeded titles is shown; which one wins+ # depends on updated_at order, which can tie at second resolution.+ seeded_titles = (+ "Mean-reversion on CSI300",+ "Earnings drift on US large caps",+ "BTC funding skew",+ )+ shown = [t for t in seeded_titles if t in out]+ assert len(shown) == 1, f"expected exactly one row, got {shown}"+ assert "Hypotheses (1)" in out++ def test_json_output(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ reg, storage = _make_registry(tmp_path)+ _seed(reg)+ args = _build_args(+ path=str(storage), hypothesis_command="list", json=True+ )+ rc = dispatch(args)+ out = capsys.readouterr().out+ assert rc == 0+ payload = json.loads(out)+ assert isinstance(payload, list)+ assert len(payload) == 3+ titles = {item["title"] for item in payload}+ assert "Mean-reversion on CSI300" in titles+++class TestShow:+ def test_shows_existing(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ reg, storage = _make_registry(tmp_path)+ ids = _seed(reg)+ args = _build_args(+ path=str(storage),+ hypothesis_command="show",+ hypothesis_id=ids[0],+ )+ rc = dispatch(args)+ out = capsys.readouterr().out+ assert rc == 0+ assert ids[0] in out+ assert "Mean-reversion on CSI300" in out+ assert "Short-horizon dispersion" in out++ def test_missing_returns_one(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ reg, storage = _make_registry(tmp_path)+ _seed(reg)+ args = _build_args(+ path=str(storage),+ hypothesis_command="show",+ hypothesis_id="hyp_does_not_exist",+ )+ rc = dispatch(args)+ captured = capsys.readouterr()+ assert rc == 1+ assert "hypothesis not found" in captured.err++ def test_json_output(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ reg, storage = _make_registry(tmp_path)+ ids = _seed(reg)+ args = _build_args(+ path=str(storage),+ hypothesis_command="show",+ hypothesis_id=ids[1],+ json=True,+ )+ rc = dispatch(args)+ out = capsys.readouterr().out+ assert rc == 0+ payload = json.loads(out)+ assert payload["hypothesis_id"] == ids[1]+ assert payload["status"] == "testing"+++class TestInvalidate:+ def test_invalidates_with_note(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ reg, storage = _make_registry(tmp_path)+ ids = _seed(reg)+ args = _build_args(+ path=str(storage),+ hypothesis_command="invalidate",+ hypothesis_id=ids[0],+ note="Data leakage in feature set.",+ )+ rc = dispatch(args)+ out = capsys.readouterr().out+ assert rc == 0+ assert ids[0] in out++ # Reload and verify persisted state.+ reg2 = HypothesisRegistry(path=storage)+ hyp = next(h for h in reg2.list() if h.hypothesis_id == ids[0])+ assert hyp.status == "rejected"+ assert hyp.invalidation_notes == "Data leakage in feature set."++ def test_invalidates_without_note_leaves_existing_note(+ self, tmp_path: Path+ ) -> None:+ reg, storage = _make_registry(tmp_path)+ hyp = reg.create(+ title="Old idea",+ thesis="Stale thesis.",+ invalidation_notes="Original note.",+ )+ args = _build_args(+ path=str(storage),+ hypothesis_command="invalidate",+ hypothesis_id=hyp.hypothesis_id,+ note="",+ )+ rc = dispatch(args)+ assert rc == 0+ reg2 = HypothesisRegistry(path=storage)+ loaded = next(+ h for h in reg2.list() if h.hypothesis_id == hyp.hypothesis_id+ )+ assert loaded.status == "rejected"+ assert loaded.invalidation_notes == "Original note."++ def test_missing_returns_one(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ reg, storage = _make_registry(tmp_path)+ _seed(reg)+ args = _build_args(+ path=str(storage),+ hypothesis_command="invalidate",+ hypothesis_id="hyp_missing",+ note="",+ )+ rc = dispatch(args)+ captured = capsys.readouterr()+ assert rc == 1+ assert "hypothesis not found" in captured.err++ def test_json_output(+ self, tmp_path: Path, capsys: pytest.CaptureFixture[str]+ ) -> None:+ reg, storage = _make_registry(tmp_path)+ ids = _seed(reg)+ args = _build_args(+ path=str(storage),+ hypothesis_command="invalidate",+ hypothesis_id=ids[2],+ note="Funding skew anomaly disappeared.",+ json=True,+ )+ rc = dispatch(args)+ out = capsys.readouterr().out+ assert rc == 0+ payload = json.loads(out)+ assert payload["hypothesis_id"] == ids[2]+ assert payload["status"] == "rejected"+ assert payload["invalidation_notes"] == (+ "Funding skew anomaly disappeared."+ )