"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(cli): add swarm retry command with resume option
Siminus316940f0e124
diff --git a/README.md b/README.mdindex c1a96567d..a1dfc9561 100644--- a/README.md+++ b/README.md@@ -1123,6 +1123,9 @@ vibe-trading --swarm-run crypto_trading_desk '{"asset": "ETH-USDT", "timeframe":# Global macro portfolio allocationvibe-trading --swarm-run macro_rates_fx_desk '{"focus": "Fed pivot impact on EM bonds"}'++# Resume a failed or cancelled run while keeping its completed tasks+vibe-trading --swarm-retry <run_id> --swarm-resume```### Cross-Session Memorydiff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex 7a99fc19a..73d785c00 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -1863,6 +1863,7 @@ def _print_help() -> None:("/swarm list", "List team run history"),("/swarm show <run_id>", "Show a team run"),("/swarm cancel <run_id>", "Cancel a team run"),+ ("/swarm retry <run_id> [--resume]", "Retry a team run or resume a failed one"),("/sessions", "List chat sessions"),("/settings", "Show provider, model, timeout, and credentials"),("/stop", "How to gracefully cancel a running agent"),@@ -2029,6 +2030,14 @@ def _handle_swarm_command(arg: str) -> None:cmd_swarm_cancel(sub_arg)else:console.print("[red]Usage: /swarm cancel <run_id>[/red]")+ elif sub == "retry":+ retry_parts = sub_arg.split()+ if len(retry_parts) == 1:+ cmd_swarm_retry_live(retry_parts[0])+ elif len(retry_parts) == 2 and retry_parts[1] == "--resume":+ cmd_swarm_retry_live(retry_parts[0], resume=True)+ else:+ console.print("[red]Usage: /swarm retry <run_id> [--resume][/red]")else:console.print(f"[red]Unknown swarm command: {sub}[/red]")@@ -2179,6 +2188,9 @@ class _SwarmDashboard:summary = data.get("summary", "")if summary:self.completed_summaries.append((agent["name"], summary))+ elif etype == "task_resumed":+ agent["status"] = "resumed"+ agent["tool"] = "kept"elif etype == "task_failed":agent["status"] = "failed"agent["elapsed"] = (time.monotonic() - agent["started_at"]) if agent["started_at"] else 0@@ -2247,6 +2259,9 @@ class _SwarmDashboard:elif status == "done":status_str = "[green][\u2713 done ][/green]"elapsed = agent["elapsed"]+ elif status == "resumed":+ status_str = "[green][\u2713 kept ][/green]"+ elapsed = agent["elapsed"]elif status == "failed":status_str = "[red][\u2717 failed][/red]"elapsed = agent["elapsed"]@@ -2267,7 +2282,7 @@ class _SwarmDashboard:table.add_row(styled_name, status_str, agent["tool"], time_str, iter_str, last_text)# Progress bar row- done_count = sum(1 for a in self.agents.values() if a["status"] in ("done", "failed", "cancelled"))+ done_count = sum(1 for a in self.agents.values() if a["status"] in ("done", "resumed", "failed", "cancelled"))total_count = len(self.agents) or 1pct = int(done_count / total_count * 100)bar_width = 40@@ -2293,47 +2308,11 @@ class _SwarmDashboard:return table-def cmd_swarm_run_live(preset: str, vars_json: Optional[str] = None) -> Optional[int]:- """Run a swarm preset with Rich Live dashboard."""+def _watch_swarm_run(store, runtime, run, dashboard: _SwarmDashboard) -> Optional[int]:+ """Keep the CLI alive while a swarm run streams to its dashboard."""from rich.live import Live- from src.config import load_swarm_agent_config- from src.swarm.runtime import SwarmRuntime- from src.swarm.store import SwarmStorefrom src.swarm.models import RunStatus- user_vars: Dict[str, str] = {}- if vars_json:- try:- user_vars = json.loads(vars_json)- except json.JSONDecodeError as exc:- _print_swarm_vars_json_error(vars_json, exc)- return EXIT_USAGE_ERROR-- store = SwarmStore(base_dir=SWARM_DIR)- agent_config = load_swarm_agent_config()- runtime = SwarmRuntime(store=store, agent_config=agent_config)- _agent_color_map.clear()-- console.print(f"\n[dim]Starting swarm:[/dim] [cyan]{preset}[/cyan]")- if user_vars:- console.print(f"[dim]Variables:[/dim] {json.dumps(user_vars, ensure_ascii=False)}")-- dashboard = _SwarmDashboard(preset, "")-- try:- run = runtime.start_run(- preset,- user_vars,- live_callback=dashboard.handle_event,- include_shell_tools=True,- )- except FileNotFoundError as exc:- console.print(f"[red]{exc}[/red]")- return- except ValueError as exc:- console.print(f"[red]DAG validation failed: {exc}[/red]")- return-dashboard.run_id = run.idwith Live(dashboard.build_table(), console=console, refresh_per_second=4, transient=False) as live:@@ -2359,18 +2338,15 @@ def cmd_swarm_run_live(preset: str, vars_json: Optional[str] = None) -> Optionalif current is None:return- # Print completed agent summariesfor agent_name, summary in dashboard.completed_summaries:style = _get_agent_style(agent_name)console.print(f"\n[{style}]\u2500\u2500 {agent_name} \u2500\u2500[/{style}]")- # Truncate to first meaningful chunklines = summary.strip().split("\n")preview = "\n".join(lines[:8])if len(lines) > 8:preview += "\n[dim]...[/dim]"console.print(preview)- # Final reportstatus_color = {RunStatus.completed: "green",RunStatus.failed: "red",@@ -2393,6 +2369,101 @@ def cmd_swarm_run_live(preset: str, vars_json: Optional[str] = None) -> Optionalconsole.print(f"\n[{status_color}]{current.status.value.upper()}[/{status_color}] Time: {mins}m {secs}s{token_str}")+def cmd_swarm_run_live(preset: str, vars_json: Optional[str] = None) -> Optional[int]:+ """Run a swarm preset with Rich Live dashboard."""+ from src.config import load_swarm_agent_config+ from src.swarm.runtime import SwarmRuntime+ from src.swarm.store import SwarmStore++ user_vars: Dict[str, str] = {}+ if vars_json:+ try:+ user_vars = json.loads(vars_json)+ except json.JSONDecodeError as exc:+ _print_swarm_vars_json_error(vars_json, exc)+ return EXIT_USAGE_ERROR++ store = SwarmStore(base_dir=SWARM_DIR)+ agent_config = load_swarm_agent_config()+ runtime = SwarmRuntime(store=store, agent_config=agent_config)+ _agent_color_map.clear()++ console.print(f"\n[dim]Starting swarm:[/dim] [cyan]{preset}[/cyan]")+ if user_vars:+ console.print(f"[dim]Variables:[/dim] {json.dumps(user_vars, ensure_ascii=False)}")++ dashboard = _SwarmDashboard(preset, "")++ try:+ run = runtime.start_run(+ preset,+ user_vars,+ live_callback=dashboard.handle_event,+ include_shell_tools=True,+ )+ except FileNotFoundError as exc:+ console.print(f"[red]{exc}[/red]")+ return+ except ValueError as exc:+ console.print(f"[red]DAG validation failed: {exc}[/red]")+ return++ return _watch_swarm_run(store, runtime, run, dashboard)+++def cmd_swarm_retry_live(run_id: str, resume: bool = False) -> Optional[int]:+ """Retry a prior swarm run, optionally keeping completed tasks."""+ from src.config import load_swarm_agent_config+ from src.swarm.models import RunStatus+ from src.swarm.runtime import SwarmRuntime+ from src.swarm.store import SwarmStore++ store = SwarmStore(base_dir=SWARM_DIR)+ try:+ loaded = store.load_run(run_id)+ except ValueError as exc:+ console.print(f"[red]{exc}[/red]")+ return EXIT_USAGE_ERROR+ if loaded is None:+ console.print(f"[red]Run {run_id} not found[/red]")+ return EXIT_USAGE_ERROR++ reconciled = store.reconcile_run(loaded, write=True)+ if reconciled.status == RunStatus.running:+ console.print("[red]Cannot retry a running run. Cancel or reap it first.[/red]")+ return EXIT_USAGE_ERROR+ if resume and reconciled.status not in (RunStatus.failed, RunStatus.cancelled):+ console.print(+ f"[red]Cannot resume a run in status '{reconciled.status.value}'; "+ "resume only applies to failed or cancelled runs.[/red]"+ )+ return EXIT_USAGE_ERROR++ runtime = SwarmRuntime(store=store, agent_config=load_swarm_agent_config())+ _agent_color_map.clear()+ action = "Resuming swarm" if resume else "Retrying swarm"+ console.print(f"\n[dim]{action}:[/dim] [cyan]{reconciled.preset_name}[/cyan]")+ console.print(f"[dim]Source run:[/dim] {run_id}")++ dashboard = _SwarmDashboard(reconciled.preset_name, "")+ try:+ run = runtime.start_run(+ reconciled.preset_name,+ reconciled.user_vars or {},+ live_callback=dashboard.handle_event,+ include_shell_tools=True,+ resume_from=reconciled if resume else None,+ )+ except FileNotFoundError as exc:+ console.print(f"[red]{exc}[/red]")+ return EXIT_USAGE_ERROR+ except ValueError as exc:+ console.print(f"[red]DAG validation failed: {exc}[/red]")+ return EXIT_USAGE_ERROR++ return _watch_swarm_run(store, runtime, run, dashboard)++# ---------------------------------------------------------------------------# Legacy subcommands (used by flags and slash commands)# ---------------------------------------------------------------------------@@ -5071,6 +5142,8 @@ def _build_parser() -> argparse.ArgumentParser:parser.add_argument("--swarm-list", action="store_true", help="List swarm runs")parser.add_argument("--swarm-show", metavar="RUN_ID", help="Show a swarm run")parser.add_argument("--swarm-cancel", metavar="RUN_ID", help="Cancel a swarm run")+ parser.add_argument("--swarm-retry", metavar="RUN_ID", help="Retry a prior swarm run")+ parser.add_argument("--swarm-resume", action="store_true", help="Keep completed tasks when retrying a swarm run")parser.add_argument("--sessions", action="store_true", help="List sessions")parser.add_argument("--session-chat", metavar="SESSION_ID", help="Continue a session chat")@@ -6286,6 +6359,11 @@ def main(argv: list[str] | None = None) -> int:return _coerce_exit_code(cmd_swarm_show(args.swarm_show))if args.swarm_cancel:return _coerce_exit_code(cmd_swarm_cancel(args.swarm_cancel))+ if args.swarm_retry:+ return _coerce_exit_code(cmd_swarm_retry_live(args.swarm_retry, resume=args.swarm_resume))+ if args.swarm_resume:+ console.print("[red]--swarm-resume requires --swarm-retry RUN_ID[/red]")+ return EXIT_USAGE_ERRORif args.sessions:return _coerce_exit_code(cmd_sessions())diff --git a/agent/tests/test_cli_swarm_retry.py b/agent/tests/test_cli_swarm_retry.pynew file mode 100644index 000000000..db6714ea1--- /dev/null+++ b/agent/tests/test_cli_swarm_retry.py@@ -0,0 +1,123 @@+"""Regression tests for swarm retry and resume CLI entry points."""++from __future__ import annotations++import sys+from types import ModuleType, SimpleNamespace+from unittest.mock import patch++import pytest+++def test_swarm_retry_dispatches_full_retry_by_default() -> None:+ from cli._legacy import EXIT_SUCCESS, main++ with patch("cli._legacy.cmd_swarm_retry_live", return_value=0) as retry:+ rc = main(["--swarm-retry", "run-123"])++ assert rc == EXIT_SUCCESS+ retry.assert_called_once_with("run-123", resume=False)+++def test_swarm_retry_dispatches_resume_opt_in() -> None:+ from cli._legacy import EXIT_SUCCESS, main++ with patch("cli._legacy.cmd_swarm_retry_live", return_value=0) as retry:+ rc = main(["--swarm-retry", "run-123", "--swarm-resume"])++ assert rc == EXIT_SUCCESS+ retry.assert_called_once_with("run-123", resume=True)+++def test_swarm_resume_requires_retry_id(capsys: pytest.CaptureFixture[str]) -> None:+ from cli._legacy import EXIT_USAGE_ERROR, main++ rc = main(["--swarm-resume"])++ assert rc == EXIT_USAGE_ERROR+ assert "requires --swarm-retry" in capsys.readouterr().out+++def test_swarm_retry_slash_command_accepts_resume_opt_in() -> None:+ from cli._legacy import _handle_swarm_command++ with patch("cli._legacy.cmd_swarm_retry_live") as retry:+ _handle_swarm_command("retry run-123 --resume")++ retry.assert_called_once_with("run-123", resume=True)+++def test_swarm_retry_passes_prior_run_only_for_resume(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from cli import _legacy++ captured: dict[str, object] = {}+ status = SimpleNamespace(running="running", failed="failed", cancelled="cancelled")+ prior = SimpleNamespace(+ id="run-failed",+ status=status.failed,+ preset_name="demo",+ user_vars={"ticker": "AAPL"},+ )++ class FakeStore:+ def __init__(self, *, base_dir) -> None:+ captured["base_dir"] = base_dir++ def load_run(self, run_id):+ assert run_id == "run-failed"+ return prior++ def reconcile_run(self, run, *, write):+ assert run is prior+ assert write is True+ return prior++ class FakeRuntime:+ def __init__(self, *, store, agent_config) -> None:+ captured["store"] = store+ captured["agent_config"] = agent_config++ def start_run(self, preset_name, variables, **kwargs):+ captured["preset_name"] = preset_name+ captured["variables"] = variables+ captured.update(kwargs)+ return SimpleNamespace(id="run-retry")++ swarm_package = ModuleType("src.swarm")+ swarm_package.__path__ = [] # type: ignore[attr-defined]+ models_module = ModuleType("src.swarm.models")+ models_module.RunStatus = status+ runtime_module = ModuleType("src.swarm.runtime")+ runtime_module.SwarmRuntime = FakeRuntime+ store_module = ModuleType("src.swarm.store")+ store_module.SwarmStore = FakeStore++ monkeypatch.setitem(sys.modules, "src.swarm", swarm_package)+ monkeypatch.setitem(sys.modules, "src.swarm.models", models_module)+ monkeypatch.setitem(sys.modules, "src.swarm.runtime", runtime_module)+ monkeypatch.setitem(sys.modules, "src.swarm.store", store_module)+ monkeypatch.setattr("src.config.load_swarm_agent_config", lambda: {"agents": []})+ monkeypatch.setattr(_legacy, "_watch_swarm_run", lambda *args: 0)++ assert _legacy.cmd_swarm_retry_live("run-failed", resume=True) == 0+ assert captured["preset_name"] == "demo"+ assert captured["resume_from"] is not None+ assert captured["resume_from"].id == "run-failed"+++def test_swarm_dashboard_marks_resumed_task_as_kept() -> None:+ from cli._legacy import _SwarmDashboard++ dashboard = _SwarmDashboard("demo", "run-retry")+ dashboard.handle_event(+ SimpleNamespace(+ agent_id="analyst",+ type="task_resumed",+ data={"source_run_id": "run-failed"},+ )+ )++ assert dashboard.agents["analyst"]["status"] == "resumed"+ assert dashboard.agents["analyst"]["tool"] == "kept"