"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(cli): reject extra --swarm-run tokens and explain invalid vars JSON
Haozhe Wu7f5a6ea76617
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex 7ce4f0ee4..d1df9e086 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -62,6 +62,8 @@ EXIT_SUCCESS = 0EXIT_RUN_FAILED = 1EXIT_USAGE_ERROR = 2RICH_TAG_PATTERN = re.compile(r"\[/?[^\]]+\]")+SWARM_RUN_USAGE = """--swarm-run PRESET '{"k":"v"}'"""+SWARM_RUN_VARS_PREVIEW_CHARS = 80from cli._version import __version__ as _VERSION # noqa: E402 — single source of truth@@ -72,6 +74,47 @@ if TYPE_CHECKING:_AGENT_STYLES = ["cyan", "magenta", "green", "yellow", "blue", "bright_red", "bright_cyan", "bright_magenta"]_agent_color_map: dict[str, str] = {}++def _truncate_swarm_vars_preview(value: str) -> str:+ """Return a compact preview for a CLI JSON token."""+ if len(value) <= SWARM_RUN_VARS_PREVIEW_CHARS:+ return value+ return value[: SWARM_RUN_VARS_PREVIEW_CHARS - 3] + "..."+++def _print_swarm_vars_json_error(vars_json: str, exc: json.JSONDecodeError) -> None:+ """Print actionable JSON diagnostics for ``--swarm-run`` vars."""+ preview = rich_escape(_truncate_swarm_vars_preview(vars_json))+ console.print(+ "[red]Invalid JSON for --swarm-run VARS.[/red]\n"+ f"Offending string: {preview}\n"+ f"JSON parse error: {rich_escape(str(exc))}\n"+ f"Correct usage: {SWARM_RUN_USAGE}\n"+ "shell quoting is the usual culprit; wrap the JSON in single quotes."+ )+++def _parse_swarm_run_args(values: list[str]) -> tuple[str, Optional[str]] | None:+ """Validate ``--swarm-run`` values before starting the swarm."""+ if len(values) > 2:+ extras = ", ".join(rich_escape(repr(token)) for token in values[2:])+ console.print(+ "[red]Invalid --swarm-run arguments:[/red] "+ f"unexpected extra token(s): {extras}\n"+ f"Correct usage: {SWARM_RUN_USAGE}"+ )+ return None++ preset = values[0]+ vars_json = values[1] if len(values) > 1 else None+ if vars_json:+ try:+ json.loads(vars_json)+ except json.JSONDecodeError as exc:+ _print_swarm_vars_json_error(vars_json, exc)+ return None+ return preset, vars_json+_HAS_PROMPT_TOOLKIT = Falsetry:from prompt_toolkit import PromptSession@@ -2069,7 +2112,7 @@ class _SwarmDashboard:return table-def cmd_swarm_run_live(preset: str, vars_json: Optional[str] = None) -> None:+def cmd_swarm_run_live(preset: str, vars_json: Optional[str] = None) -> Optional[int]:"""Run a swarm preset with Rich Live dashboard."""from rich.live import Livefrom src.config import load_swarm_agent_config@@ -2082,8 +2125,8 @@ def cmd_swarm_run_live(preset: str, vars_json: Optional[str] = None) -> None:try:user_vars = json.loads(vars_json)except json.JSONDecodeError as exc:- console.print(f"[red]Invalid JSON: {exc}[/red]")- return+ _print_swarm_vars_json_error(vars_json, exc)+ return EXIT_USAGE_ERRORstore = SwarmStore(base_dir=SWARM_DIR)agent_config = load_swarm_agent_config()@@ -2400,9 +2443,9 @@ def cmd_swarm_presets() -> None:console.print(table)-def cmd_swarm_run(preset: str, vars_json: Optional[str] = None) -> None:+def cmd_swarm_run(preset: str, vars_json: Optional[str] = None) -> Optional[int]:"""Run swarm preset (legacy polling mode, use cmd_swarm_run_live for streaming)."""- cmd_swarm_run_live(preset, vars_json)+ return cmd_swarm_run_live(preset, vars_json)def cmd_swarm_inspect(preset: str) -> int:@@ -5388,8 +5431,10 @@ def main(argv: list[str] | None = None) -> int:if args.swarm_inspect:return _coerce_exit_code(cmd_swarm_inspect(args.swarm_inspect))if args.swarm_run:- preset_name = args.swarm_run[0]- vars_json = args.swarm_run[1] if len(args.swarm_run) > 1 else None+ parsed_swarm_run = _parse_swarm_run_args(args.swarm_run)+ if parsed_swarm_run is None:+ return EXIT_USAGE_ERROR+ preset_name, vars_json = parsed_swarm_runreturn _coerce_exit_code(cmd_swarm_run_live(preset_name, vars_json))if args.swarm_list:return _coerce_exit_code(cmd_swarm_list())diff --git a/agent/tests/test_cli_swarm_run_args.py b/agent/tests/test_cli_swarm_run_args.pynew file mode 100644index 000000000..11b72a132--- /dev/null+++ b/agent/tests/test_cli_swarm_run_args.py@@ -0,0 +1,64 @@+"""Regression tests for ``--swarm-run`` argument handling."""++from __future__ import annotations++from unittest.mock import patch++import pytest+++def test_swarm_run_rejects_extra_tokens(capsys: pytest.CaptureFixture[str]) -> None:+ """Extra vars tokens must fail explicitly instead of being dropped."""+ from cli._legacy import EXIT_USAGE_ERROR, main++ with patch("cli._legacy.cmd_swarm_run_live") as run:+ rc = main(["--swarm-run", "investment_committee", '{"k":"v"}', "dropped"])++ out = capsys.readouterr().out+ assert rc == EXIT_USAGE_ERROR+ assert "unexpected extra token(s)" in out+ assert "dropped" in out+ assert """--swarm-run PRESET '{"k":"v"}'""" in out+ run.assert_not_called()+++def test_swarm_run_invalid_json_reports_offending_string(+ capsys: pytest.CaptureFixture[str],+) -> None:+ """Invalid vars JSON should include the bad input and parser detail."""+ from cli._legacy import EXIT_USAGE_ERROR, main++ bad_vars = "{k:v}"+ with patch("cli._legacy.cmd_swarm_run_live") as run:+ rc = main(["--swarm-run", "investment_committee", bad_vars])++ out = capsys.readouterr().out+ assert rc == EXIT_USAGE_ERROR+ assert bad_vars in out+ assert "Expecting property name enclosed in double quotes" in out+ assert """--swarm-run PRESET '{"k":"v"}'""" in out+ assert "shell quoting" in out+ run.assert_not_called()+++def test_swarm_run_one_arg_dispatches_without_vars() -> None:+ """A preset without vars remains valid for backwards compatibility."""+ from cli._legacy import EXIT_SUCCESS, main++ with patch("cli._legacy.cmd_swarm_run_live", return_value=0) as run:+ rc = main(["--swarm-run", "investment_committee"])++ assert rc == EXIT_SUCCESS+ run.assert_called_once_with("investment_committee", None)+++def test_swarm_run_two_args_dispatches_with_vars() -> None:+ """A preset plus one JSON vars token dispatches unchanged."""+ from cli._legacy import EXIT_SUCCESS, main++ vars_json = '{"ticker":"AAPL"}'+ with patch("cli._legacy.cmd_swarm_run_live", return_value=0) as run:+ rc = main(["--swarm-run", "investment_committee", vars_json])++ assert rc == EXIT_SUCCESS+ run.assert_called_once_with("investment_committee", vars_json)