"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(cli): add memory introspection commands
Teerapat-Vatpitak32a96fb5b247
diff --git a/agent/cli.py b/agent/cli.pyindex f082a729b..d2f67fa4d 100644--- a/agent/cli.py+++ b/agent/cli.py@@ -22,10 +22,12 @@ import sysimport threadingimport timeimport uuid+from datetime import datetimefrom pathlib import Pathfrom typing import Any, Dict, List, Optionalimport warnings+warnings.filterwarnings("ignore", message=".*Importing verbose from langchain.*")warnings.filterwarnings("ignore", category=DeprecationWarning, module="langchain")@@ -38,12 +40,15 @@ from rich.console import Consolefrom rich import boxfrom rich.columns import Columnsfrom rich.live import Live+from rich.markup import escape as rich_escapefrom rich.panel import Panelfrom rich.prompt import Confirm, IntPrompt, Promptfrom rich.syntax import Syntaxfrom rich.table import Tablefrom rich.text import Text+from src.memory.persistent import MEMORY_TYPES, PersistentMemory # noqa: E402+console = Console()AGENT_DIR = Path(__file__).resolve().parentRUNS_DIR = AGENT_DIR / "runs"@@ -140,9 +145,7 @@ def _print_status_bar(stats: _SessionStats) -> None:stats: Session statistics."""parts = _build_status_parts(stats)- bar = "[dim] │ [/dim]".join(- f"[bold]{parts[0]}[/bold]" if i == 0 else p for i, p in enumerate(parts)- )+ bar = "[dim] │ [/dim]".join(f"[bold]{parts[0]}[/bold]" if i == 0 else p for i, p in enumerate(parts))console.print(bar)@@ -254,6 +257,7 @@ def _read_prompt_source(# Helpers# ---------------------------------------------------------------------------+def _read_json(path: Path) -> dict:"""Safely read JSON."""if not path.exists():@@ -593,18 +597,19 @@ class _RunDashboard:# Agent execution core# ---------------------------------------------------------------------------+def _format_tool_call_args(tool: str, args: Dict[str, str]) -> str:"""Smart-format tool argument summary."""if tool == "load_skill":return f'("{args.get("name", "")}")'if tool in ("write_file", "read_file", "edit_file"):- return f' {args.get("path", args.get("file_path", ""))}'+ return f" {args.get('path', args.get('file_path', ''))}"if tool in ("bash", "background_run"):cmd = args.get("command", "")[:80]- return f' [yellow]{cmd}[/yellow]'+ return f" [yellow]{cmd}[/yellow]"if tool == "check_background":tid = args.get("task_id", "")- return f' {tid}' if tid else ""+ return f" {tid}" if tid else ""if tool in ("backtest", "compact"):return ""for v in args.values():@@ -624,7 +629,7 @@ def _format_tool_result_preview(tool: str, status: str, preview: str) -> str:if sharpe:parts.append(f"sharpe={sharpe.group(1)}")if ret:- parts.append(f"return={float(ret.group(1))*100:.1f}%")+ parts.append(f"return={float(ret.group(1)) * 100:.1f}%")return ", ".join(parts) if parts else ""if tool == "render_shadow_report":url = re.search(r'"report_url":\s*"([^"]+)"', preview)@@ -711,7 +716,9 @@ def _run_agent(console.print(f" {mark} [dim]{elapsed_s:.1f}s[/dim]{suffix}")elif event_type == "compact":tokens = data.get("tokens_before", "?")- console.print(f"\n [yellow]\u27f3 context compressed[/yellow] [dim]({tokens} tokens \u2192 summary)[/dim]\n")+ console.print(+ f"\n [yellow]\u27f3 context compressed[/yellow] [dim]({tokens} tokens \u2192 summary)[/dim]\n"+ )from src.memory.persistent import PersistentMemory@@ -738,7 +745,7 @@ def _build_benchmark_table(m: dict) -> Optional[Table]:Returns:Rich Table, or None if no benchmark data is present."""- bench_ticker = m.get("benchmark_ticker")+ bench_ticker = m.get("benchmark_ticker")bench_ret_str = m.get("benchmark_return")bench_ret_raw = m.get("_benchmark_return_raw")@@ -758,21 +765,21 @@ def _build_benchmark_table(m: dict) -> Optional[Table]:bench_ret = Nonestrategy_ret_str = m.get("total_return")- strategy_ret = float(strategy_ret_str) if strategy_ret_str else None+ strategy_ret = float(strategy_ret_str) if strategy_ret_str else Nonetable = Table(show_header=False, padding=(0, 2))table.add_column("Label", style="dim", width=20)table.add_column("Value", style="white no_wrap")- table.add_row("[dim]Benchmark[/dim]", bench_ticker)+ table.add_row("[dim]Benchmark[/dim]", bench_ticker)if bench_ret is not None:table.add_row("[dim]Benchmark Return[/dim]", f"{bench_ret * 100:+.2f}%")if strategy_ret is not None and bench_ret is not None:excess = strategy_ret - bench_ret- sign = "+" if excess >= 0 else ""- style = "green" if excess >= 0 else "red"+ sign = "+" if excess >= 0 else ""+ style = "green" if excess >= 0 else "red"table.add_row("[dim]vs Benchmark[/dim]",f"[{style}]{sign}{excess * 100:+.2f}%[/{style}]",@@ -809,12 +816,16 @@ def _print_result(result: dict, elapsed: float, *, no_rich: bool = False) -> Nonprint(f"Run dir: {run_dir}")if result.get("reason"):print(f"Reason: {result['reason']}")- metric_parts = [f"{label}={m[key]}" for key, label in (- ("total_return", "return"),- ("sharpe", "sharpe"),- ("max_drawdown", "max_dd"),- ("trade_count", "trades"),- ) if key in m]+ metric_parts = [+ f"{label}={m[key]}"+ for key, label in (+ ("total_return", "return"),+ ("sharpe", "sharpe"),+ ("max_drawdown", "max_dd"),+ ("trade_count", "trades"),+ )+ if key in m+ ]if metric_parts:print(f"Metrics: {', '.join(metric_parts)}")content = result.get("content", "").strip()@@ -868,7 +879,7 @@ def _print_result(result: dict, elapsed: float, *, no_rich: bool = False) -> Nonactions.add_column(style="dim")actions.add_row(f"vibe-trading show {rid}", "details")actions.add_row(f"vibe-trading code {rid}", "generated Python")- actions.add_row(f"vibe-trading continue {rid} \"...\"", "refine this run")+ actions.add_row(f'vibe-trading continue {rid} "..."', "refine this run")panels.append(Panel(actions, border_style="dim", title="Next", padding=(0, 1)))if _terminal_width() < 104:@@ -880,12 +891,14 @@ def _print_result(result: dict, elapsed: float, *, no_rich: bool = False) -> Non# Benchmark comparison panel.bench_table = _build_benchmark_table(m)if bench_table:- console.print(Panel(- bench_table,- border_style="cyan",- title="Benchmark Comparison",- padding=(0, 1),- ))+ console.print(+ Panel(+ bench_table,+ border_style="cyan",+ title="Benchmark Comparison",+ padding=(0, 1),+ )+ )# End benchmark comparison panel.content = result.get("content", "").strip()@@ -897,10 +910,12 @@ def _print_result(result: dict, elapsed: float, *, no_rich: bool = False) -> Non# Subcommands# ---------------------------------------------------------------------------+def cmd_run(prompt: str, max_iter: int, *, json_mode: bool = False, no_rich: bool = False) -> int:"""Single run."""if not json_mode:from src.preflight import run_preflight+results = run_preflight(console)if any(r.critical and r.status != "ready" for r in results):return EXIT_RUN_FAILED@@ -935,7 +950,7 @@ def cmd_run(prompt: str, max_iter: int, *, json_mode: bool = False, no_rich: booreturn _result_exit_code(result)_print_result(result, time.perf_counter() - start, no_rich=no_rich)if result.get("run_id"):- tip = f"--show {result['run_id']} | --continue {result['run_id']} \"...\" | --code {result['run_id']} | --pine {result['run_id']}"+ tip = f'--show {result["run_id"]} | --continue {result["run_id"]} "..." | --code {result["run_id"]} | --pine {result["run_id"]}'if no_rich:print(tip)else:@@ -946,6 +961,7 @@ def cmd_run(prompt: str, max_iter: int, *, json_mode: bool = False, no_rich: boodef _build_history_from_trace(run_dir: Path) -> List[Dict[str, str]]:"""Build conversation history from trace.jsonl."""from src.agent.trace import TraceWriter+entries = TraceWriter.read(run_dir)history: List[Dict[str, str]] = []for e in entries:@@ -1025,6 +1041,7 @@ def cmd_continue(# Interactive mode (Welcome + Slash commands + Swarm streaming)# ---------------------------------------------------------------------------+def _build_welcome_panel(term_width: Optional[int] = None) -> Panel:"""Build the welcome screen for the given terminal width."""_ensure_cli_env()@@ -1056,7 +1073,11 @@ def _build_welcome_panel(term_width: Optional[int] = None) -> Panel:]))- header_lines.append(Text(_clip_inline("Research, backtest, inspect runs, and coordinate swarm presets.", content_width), style="dim"))+ header_lines.append(+ Text(+ _clip_inline("Research, backtest, inspect runs, and coordinate swarm presets.", content_width), style="dim"+ )+ )config_lines: list[Text] = []if compact:@@ -1082,7 +1103,14 @@ def _build_welcome_panel(term_width: Optional[int] = None) -> Panel:else:gap = " " * widths["gap"]rows = [- ("Provider", str(provider), "bold cyan", "Credential", key_state, "bold green" if credential_ready else "bold yellow"),+ (+ "Provider",+ str(provider),+ "bold cyan",+ "Credential",+ key_state,+ "bold green" if credential_ready else "bold yellow",+ ),("Model", str(model), "white", "Runs", str(recent_runs), "cyan"),("Workspace", str(AGENT_DIR), "dim", "Swarms", str(recent_swarms), "cyan"),]@@ -1223,7 +1251,12 @@ def _show_settings() -> None:provider_key_env = _provider_key_env(provider)provider_base_env = _provider_base_env(provider)provider_key = os.getenv(provider_key_env or "")- provider_base_url = os.getenv(provider_base_env or "") or os.getenv("OPENAI_BASE_URL") or os.getenv("OPENAI_API_BASE") or "(not set)"+ provider_base_url = (+ os.getenv(provider_base_env or "")+ or os.getenv("OPENAI_BASE_URL")+ or os.getenv("OPENAI_API_BASE")+ or "(not set)"+ )provider_table = Table.grid(expand=True)provider_table.add_column(width=12, style="dim")@@ -1255,9 +1288,19 @@ def _show_settings() -> None:credential_table.add_row("TUSHARE_TOKEN", "***" if os.getenv("TUSHARE_TOKEN") else "(optional)")panels = [- Panel(provider_table, title=f"Provider {_state_badge(provider if provider != '(not set)' else None)}", border_style="cyan", padding=(0, 1)),+ Panel(+ provider_table,+ title=f"Provider {_state_badge(provider if provider != '(not set)' else None)}",+ border_style="cyan",+ padding=(0, 1),+ ),Panel(runtime_table, title="Runtime", border_style="dim", padding=(0, 1)),- Panel(credential_table, title=f"Credentials {_state_badge('ok' if credential_ready else None)}", border_style="green" if credential_ready else "yellow", padding=(0, 1)),+ Panel(+ credential_table,+ title=f"Credentials {_state_badge('ok' if credential_ready else None)}",+ border_style="green" if credential_ready else "yellow",+ padding=(0, 1),+ ),]if compact:for panel in panels:@@ -1364,6 +1407,7 @@ def cmd_interactive(max_iter: int) -> None:_print_welcome()from src.preflight import run_preflight+results = run_preflight(console)if any(r.critical and r.status != "ready" for r in results):return@@ -1418,6 +1462,7 @@ def cmd_interactive(max_iter: int) -> None:# Swarm live streaming (Rich Live panel)# ---------------------------------------------------------------------------+def _get_agent_style(agent_id: str) -> str:"""Assign a consistent color to each agent."""if agent_id not in _agent_color_map:@@ -1446,9 +1491,13 @@ class _SwarmDashboard:if agent_id in self.agents:return agent_idself.agents[agent_id] = {- "name": agent_id, "status": "waiting",- "tool": "\u2014", "elapsed": 0.0, "iters": 0,- "started_at": 0.0, "layer": self.current_layer,+ "name": agent_id,+ "status": "waiting",+ "tool": "\u2014",+ "elapsed": 0.0,+ "iters": 0,+ "started_at": 0.0,+ "layer": self.current_layer,"last_text": "",}self.agent_order.append(agent_id)@@ -1689,13 +1738,16 @@ def cmd_swarm_run_live(preset: str, vars_json: Optional[str] = None) -> None:console.print(f"\n[bold]\u2500\u2500 Final Report \u2500\u2500[/bold]")console.print(current.final_report[:2000])- console.print(f"\n[{status_color}]{current.status.value.upper()}[/{status_color}] Time: {mins}m {secs}s{token_str}")+ console.print(+ f"\n[{status_color}]{current.status.value.upper()}[/{status_color}] Time: {mins}m {secs}s{token_str}"+ )# ---------------------------------------------------------------------------# Legacy subcommands (used by flags and slash commands)# ---------------------------------------------------------------------------+def cmd_chat(max_iter: int) -> None:"""Interactive mode (delegates to cmd_interactive)."""cmd_interactive(max_iter)@@ -1758,6 +1810,7 @@ def cmd_show(run_id: str) -> None:lines.extend(f" {k}: {v}" for k, v in metrics.items())from src.agent.trace import TraceWriter+entries = TraceWriter.read(run_dir)answers = [e["content"] for e in entries if e.get("type") == "answer" and e.get("content")]if answers:@@ -1790,7 +1843,7 @@ def cmd_pine(run_id: str) -> None:pine_path = RUNS_DIR / run_id / "artifacts" / "strategy.pine"if not pine_path.exists():console.print(f"[red]{run_id}/artifacts/strategy.pine not found[/red]")- console.print("[dim]Ask the agent: \"export this strategy to Pine Script\"[/dim]")+ console.print('[dim]Ask the agent: "export this strategy to Pine Script"[/dim]')returncode = pine_path.read_text(encoding="utf-8")console.print(Syntax(code, "javascript", theme="monokai", line_numbers=True), width=120)@@ -1801,6 +1854,7 @@ def cmd_pine(run_id: str) -> None:def cmd_skills() -> None:"""List available skills."""from src.agent.skills import SkillsLoader+loader = SkillsLoader()table = Table(title="Skills", show_lines=False)@@ -1815,7 +1869,6 @@ def cmd_skills() -> None:def cmd_trace(run_id: str) -> None:"""Replay trace.jsonl to show full execution."""- from datetime import datetimefrom src.agent.trace import TraceWriterrun_dir = RUNS_DIR / run_id@@ -1838,7 +1891,9 @@ def cmd_trace(run_id: str) -> None:iter_tag = f"[dim]#{it}[/dim] " if it else ""if etype == "start":- console.print(f"\n[bold cyan]{ts_str}[/bold cyan] {iter_tag}[bold]START[/bold] {entry.get('prompt', '')[:120]}")+ console.print(+ f"\n[bold cyan]{ts_str}[/bold cyan] {iter_tag}[bold]START[/bold] {entry.get('prompt', '')[:120]}"+ )elif etype == "thinking":content = entry.get("content", "")console.print(f"[dim]{ts_str}[/dim] {iter_tag}[dim italic]{content[:200]}[/dim italic]")@@ -1855,7 +1910,9 @@ def cmd_trace(run_id: str) -> None:mark = "\u2713" if ok else "\u2717"color = "green" if ok else "red"preview = entry.get("preview", "")[:80]- console.print(f"[dim]{ts_str}[/dim] {iter_tag}[{color}]{mark} {tool}[/{color}] [dim]{elapsed}ms[/dim] {preview}")+ console.print(+ f"[dim]{ts_str}[/dim] {iter_tag}[{color}]{mark} {tool}[/{color}] [dim]{elapsed}ms[/dim] {preview}"+ )elif etype == "tool_skipped":console.print(f"[dim]{ts_str}[/dim] {iter_tag}[yellow]\u2298 {entry.get('tool', '')} (skipped)[/yellow]")elif etype == "answer":@@ -1874,6 +1931,7 @@ def cmd_trace(run_id: str) -> None:# Swarm subcommands# ---------------------------------------------------------------------------+def cmd_swarm_presets() -> None:"""List available swarm presets."""from src.swarm.presets import list_presets@@ -1892,9 +1950,7 @@ def cmd_swarm_presets() -> None:for p in presets:raw_vars = p.get("variables", [])- var_names = [- v["name"] if isinstance(v, dict) else str(v) for v in raw_vars- ]+ var_names = [v["name"] if isinstance(v, dict) else str(v) for v in raw_vars]vars_str = ", ".join(var_names)table.add_row(p["name"],@@ -2089,6 +2145,7 @@ def cmd_swarm_cancel(run_id: str) -> None:# Session subcommands# ---------------------------------------------------------------------------+def cmd_sessions() -> None:"""List chat sessions."""from src.session.store import SessionStore@@ -2138,11 +2195,13 @@ def cmd_session_chat(session_id: str, max_iter: int) -> None:if msg.role in ("user", "assistant") and msg.content.strip():history.append({"role": msg.role, "content": msg.content})- console.print(Panel(- f"[bold cyan]Session: {session.title or session_id}[/bold cyan]\n"- f"[dim]History: {len(messages)} messages | Type q to exit[/dim]",- border_style="cyan",- ))+ console.print(+ Panel(+ f"[bold cyan]Session: {session.title or session_id}[/bold cyan]\n"+ f"[dim]History: {len(messages)} messages | Type q to exit[/dim]",+ border_style="cyan",+ )+ )stats = _SessionStats(session_start=time.monotonic())prompt_session = _create_prompt_session(stats)@@ -2196,6 +2255,7 @@ def cmd_session_chat(session_id: str, max_iter: int) -> None:# Upload subcommand# ---------------------------------------------------------------------------+def cmd_upload(file_path: str) -> None:"""Upload a file to the server."""src = Path(file_path)@@ -2241,6 +2301,7 @@ def cmd_provider_login(provider: str) -> int:# CLI entrypoint# ---------------------------------------------------------------------------+def _build_parser() -> argparse.ArgumentParser:"""Build the CLI parser with subcommands and compatibility flags."""parser = argparse.ArgumentParser(description="Vibe-Trading CLI")@@ -2274,7 +2335,9 @@ def _build_parser() -> argparse.ArgumentParser:run_parser = subparsers.add_parser("run", help="Run a prompt")run_parser.add_argument("-p", "--prompt", dest="run_prompt", type=str, help="Prompt text")- run_parser.add_argument("-f", "--prompt-file", dest="run_prompt_file", type=Path, help="Read prompt text from a file")+ run_parser.add_argument(+ "-f", "--prompt-file", dest="run_prompt_file", type=Path, help="Read prompt text from a file"+ )run_parser.add_argument("--json", dest="run_json", action="store_true", help="Print machine-readable JSON output")run_parser.add_argument("--no-rich", dest="run_no_rich", action="store_true", help="Disable Rich formatting")run_parser.add_argument("--max-iter", dest="run_max_iter", type=int, default=50, help="Maximum agent iterations")@@ -2300,6 +2363,30 @@ def _build_parser() -> argparse.ArgumentParser:subparsers.add_parser("init", help="Interactive setup: create ~/.vibe-trading/.env")+ memory_parser = subparsers.add_parser("memory", help="Inspect persistent memory")+ memory_subparsers = memory_parser.add_subparsers(dest="memory_command")++ memory_list_parser = memory_subparsers.add_parser("list", help="List memory entries")+ memory_list_parser.add_argument(+ "--type",+ dest="memory_type",+ choices=MEMORY_TYPES,+ help="Filter by memory type",+ )++ memory_show_parser = memory_subparsers.add_parser("show", help="Show a memory entry")+ memory_show_parser.add_argument("name", help="Memory title or filename stem")++ memory_search_parser = memory_subparsers.add_parser("search", help="Recall memories for a query")+ memory_search_parser.add_argument("query", help="Search text")+ memory_search_parser.add_argument(+ "--limit", dest="memory_limit", type=int, default=5, help="Maximum matches (default: 5)"+ )++ memory_forget_parser = memory_subparsers.add_parser("forget", help="Remove a memory entry")+ memory_forget_parser.add_argument("name", help="Memory title or filename stem")+ memory_forget_parser.add_argument("-y", "--yes", action="store_true", help="Skip confirmation prompt")+return parser@@ -2322,7 +2409,9 @@ def _handle_prompt_command(return EXIT_USAGE_ERRORif not resolved_prompt:if json_mode:- _print_json_result({"status": "failed", "run_id": None, "run_dir": None, "reason": "Prompt cannot be empty"})+ _print_json_result(+ {"status": "failed", "run_id": None, "run_dir": None, "reason": "Prompt cannot be empty"}+ )else:print("Prompt cannot be empty") if no_rich else console.print("[red]Prompt cannot be empty[/red]")return EXIT_USAGE_ERROR@@ -2514,9 +2603,134 @@ def _render_env_content(config: dict[str, str]) -> str:return "\n".join(lines) + "\n"+_MEMORY_TYPE_STYLES = {+ "user": "cyan",+ "feedback": "yellow",+ "project": "green",+ "reference": "magenta",+}+assert set(_MEMORY_TYPE_STYLES) == set(MEMORY_TYPES), "_MEMORY_TYPE_STYLES drift: keys must mirror MEMORY_TYPES"+++def cmd_memory_list(memory_type: Optional[str] = None, *, memory_dir: Optional[Path] = None) -> int:+ """List persisted memory entries."""+ pm = PersistentMemory(memory_dir=memory_dir)+ entries = pm.list_entries()+ if memory_type:+ entries = [e for e in entries if e.memory_type == memory_type]++ if not entries:+ scope = f" type={memory_type}" if memory_type else ""+ console.print(f"[dim]No memory entries found{scope}.[/dim]")+ return EXIT_SUCCESS++ entries.sort(key=lambda e: -e.modified_at)+ table = Table(title="Persistent Memory", box=box.SIMPLE_HEAVY, show_lines=False)+ table.add_column("Title", style="bold")+ table.add_column("Type")+ table.add_column("Description", overflow="fold")+ table.add_column("Modified", style="dim")++ for e in entries:+ style = _MEMORY_TYPE_STYLES.get(e.memory_type, "white")+ modified = datetime.fromtimestamp(e.modified_at).strftime("%Y-%m-%d %H:%M")+ table.add_row(+ rich_escape(e.title),+ f"[{style}]{e.memory_type}[/{style}]",+ rich_escape(e.description) or "—",+ modified,+ )++ console.print(table)+ console.print(f"[dim]{len(entries)} entr{'y' if len(entries) == 1 else 'ies'}[/dim]")+ return EXIT_SUCCESS+++def cmd_memory_show(name: str, *, memory_dir: Optional[Path] = None) -> int:+ """Show full content of a single memory entry."""+ pm = PersistentMemory(memory_dir=memory_dir)+ entry = pm.find(name)+ if entry is None:+ console.print(f"[red]Memory not found:[/red] {rich_escape(name)}")+ console.print("[dim]Run `vibe-trading memory list` to see available titles.[/dim]")+ return EXIT_USAGE_ERROR++ style = _MEMORY_TYPE_STYLES.get(entry.memory_type, "white")+ header = (+ f"[bold]{rich_escape(entry.title)}[/bold]\n"+ f"[{style}]{entry.memory_type}[/{style}] • [dim]{rich_escape(entry.path.name)}[/dim]\n"+ f"[dim]{rich_escape(entry.description)}[/dim]"+ )+ console.print(Panel(header, border_style="cyan"))+ console.print(rich_escape(entry.body.rstrip()) or "[dim](empty body)[/dim]")+ return EXIT_SUCCESS+++def cmd_memory_search(query: str, max_results: int = 5, *, memory_dir: Optional[Path] = None) -> int:+ """Run keyword recall and display the top matches."""+ pm = PersistentMemory(memory_dir=memory_dir)+ results = pm.find_relevant(query, max_results=max_results)+ if not results:+ console.print(f"[dim]No matches for[/dim] [bold]{rich_escape(query)}[/bold]")+ return EXIT_SUCCESS++ table = Table(title=f"Recall: {rich_escape(query)}", box=box.SIMPLE_HEAVY, show_lines=False)+ table.add_column("Rank", style="dim", width=4)+ table.add_column("Title", style="bold")+ table.add_column("Type")+ table.add_column("Description", overflow="fold")++ for rank, e in enumerate(results, start=1):+ style = _MEMORY_TYPE_STYLES.get(e.memory_type, "white")+ table.add_row(+ str(rank),+ rich_escape(e.title),+ f"[{style}]{e.memory_type}[/{style}]",+ rich_escape(e.description) or "—",+ )++ console.print(table)+ return EXIT_SUCCESS+++def cmd_memory_forget(name: str, *, yes: bool = False, memory_dir: Optional[Path] = None) -> int:+ """Remove a memory entry by name."""+ pm = PersistentMemory(memory_dir=memory_dir)+ entry = pm.find(name)+ if entry is None:+ console.print(f"[red]Memory not found:[/red] {rich_escape(name)}")+ return EXIT_USAGE_ERROR++ if not yes:+ style = _MEMORY_TYPE_STYLES.get(entry.memory_type, "white")+ console.print(+ f"About to forget [bold]{rich_escape(entry.title)}[/bold] "+ f"([{style}]{entry.memory_type}[/{style}], {rich_escape(entry.path.name)})."+ )+ try:+ proceed = Confirm.ask("Proceed?", default=False)+ except EOFError:+ console.print("[dim]No input available; use --yes for non-interactive deletes.[/dim]")+ return EXIT_USAGE_ERROR+ if not proceed:+ console.print("[dim]Aborted.[/dim]")+ return EXIT_SUCCESS++ if pm.remove_entry(entry):+ console.print(f"[green]Forgot[/green] {rich_escape(entry.title)}")+ return EXIT_SUCCESS+ console.print(f"[red]Failed to remove[/red] {rich_escape(entry.title)}")+ return EXIT_RUN_FAILED++def cmd_init() -> int:"""Interactive setup: create agent/.env."""- console.print(Panel("[bold cyan]Vibe-Trading setup[/bold cyan]\n[dim]Configure the default LLM provider and data tokens.[/dim]", border_style="cyan"))+ console.print(+ Panel(+ "[bold cyan]Vibe-Trading setup[/bold cyan]\n[dim]Configure the default LLM provider and data tokens.[/dim]",+ border_style="cyan",+ )+ )if _INIT_ENV_PATH.exists():console.print(f"[yellow]Config already exists:[/yellow] {_INIT_ENV_PATH}")@@ -2530,7 +2744,13 @@ def cmd_init() -> int:provider_table.add_column("Default model", style="dim")provider_table.add_column("Credential", style="dim")for idx, option in enumerate(_PROVIDER_CHOICES, start=1):- credential = "OAuth" if option["provider"] == "openai-codex" else "none" if option["key_env"] is None else str(option["key_env"])+ credential = (+ "OAuth"+ if option["provider"] == "openai-codex"+ else "none"+ if option["key_env"] is None+ else str(option["key_env"])+ )provider_table.add_row(str(idx), str(option["label"]), str(option["model"]), credential)console.print(provider_table)@@ -2643,6 +2863,17 @@ def main(argv: list[str] | None = None) -> int:return _coerce_exit_code(cmd_show(args.show))if args.command == "chat":return _coerce_exit_code(cmd_interactive(args.chat_max_iter))+ if args.command == "memory":+ if args.memory_command == "list":+ return _coerce_exit_code(cmd_memory_list(args.memory_type))+ if args.memory_command == "show":+ return _coerce_exit_code(cmd_memory_show(args.name))+ if args.memory_command == "search":+ return _coerce_exit_code(cmd_memory_search(args.query, args.memory_limit))+ if args.memory_command == "forget":+ return _coerce_exit_code(cmd_memory_forget(args.name, yes=args.yes))+ console.print("[red]memory requires a subcommand.[/red] Try: vibe-trading memory list")+ return EXIT_USAGE_ERRORif args.list:return _coerce_exit_code(cmd_list())@@ -2681,7 +2912,9 @@ def main(argv: list[str] | None = None) -> int:if args.chat:return _coerce_exit_code(cmd_interactive(args.max_iter))if args.cont:- return _coerce_exit_code(cmd_continue(args.cont[0], args.cont[1], args.max_iter, json_mode=args.json, no_rich=args.no_rich))+ return _coerce_exit_code(+ cmd_continue(args.cont[0], args.cont[1], args.max_iter, json_mode=args.json, no_rich=args.no_rich)+ )# No flags and no subcommand: check for a prompt, otherwise enter interactive mode.if args.prompt or args.prompt_file or not sys.stdin.isatty():diff --git a/agent/src/memory/persistent.py b/agent/src/memory/persistent.pyindex e8d2ac5cb..d1e5d382b 100644--- a/agent/src/memory/persistent.py+++ b/agent/src/memory/persistent.py@@ -10,6 +10,7 @@ Storage layout:from __future__ import annotations+import loggingimport refrom dataclasses import dataclassfrom pathlib import Path@@ -17,11 +18,14 @@ from pathlib import Pathfrom src.agent.frontmatter import parse_frontmatter as _parse_frontmatterfrom typing import List, Optional+logger = logging.getLogger(__name__)+MEMORY_BASE = Path.home() / ".vibe-trading" / "memory"MAX_INDEX_LINES = 200MAX_ENTRY_CHARS = 8000MAX_RESULTS = 5METADATA_WEIGHT = 2.0+MEMORY_TYPES = ("user", "feedback", "project", "reference")@dataclass(frozen=True)@@ -128,6 +132,39 @@ class PersistentMemory:))return entries+ def list_entries(self) -> List[MemoryEntry]:+ """Return all persisted memory entries, filename-sorted."""+ return self._scan_entries()++ def find(self, name: str) -> Optional[MemoryEntry]:+ """Resolve a memory by exact title, then by on-disk filename stem.++ Stem fallback accepts both the full ``{type}_{slug}`` form and the+ bare ``slug`` suffix so users can paste either form from the index.+ """+ needle = name.strip()+ if not needle:+ return None+ entries = self._scan_entries()+ for entry in entries:+ if entry.title == needle:+ return entry+ for entry in entries:+ stem = entry.path.stem+ if stem == needle or stem.endswith(f"_{needle}"):+ return entry+ return None++ def remove_entry(self, entry: MemoryEntry) -> bool:+ """Delete a resolved entry without re-scanning to find it again."""+ try:+ entry.path.unlink(missing_ok=True)+ except OSError as exc:+ logger.warning("Failed to remove memory entry %s: %s", entry.path, exc)+ return False+ self._rebuild_index()+ return True+def find_relevant(self, query: str, max_results: int = MAX_RESULTS) -> List[MemoryEntry]:"""Keyword search across all memory entries.diff --git a/agent/tests/test_cli_memory.py b/agent/tests/test_cli_memory.pynew file mode 100644index 000000000..9b646c269--- /dev/null+++ b/agent/tests/test_cli_memory.py@@ -0,0 +1,238 @@+"""Tests for the `vibe-trading memory` CLI subcommands."""++from __future__ import annotations++from pathlib import Path+from unittest.mock import patch++import pytest++import cli+from src.memory.persistent import PersistentMemory+++def _seed(tmp_path: Path) -> PersistentMemory:+ """Populate a tmp memory dir with one entry per type."""+ pm = PersistentMemory(memory_dir=tmp_path)+ pm.add("user-style", "Prefer concise replies.", "user", description="user persona")+ pm.add("feedback-tests", "Never mock the database.", "feedback", description="testing rule")+ pm.add("project-q2", "Q2 focus is execution loop.", "project", description="Q2 priorities")+ pm.add("ref-runbook", "See runbook.md", "reference", description="ops runbook pointer")+ return pm+++class TestPersistentMemoryFind:+ def test_exact_title_wins(self, tmp_path: Path) -> None:+ pm = _seed(tmp_path)+ entry = pm.find("project-q2")+ assert entry is not None+ assert entry.title == "project-q2"++ def test_stem_match_full_form(self, tmp_path: Path) -> None:+ # On-disk stem `project_project-q2` matches via `stem == needle` branch.+ pm = _seed(tmp_path)+ entry = pm.find("project_project-q2")+ assert entry is not None+ assert entry.title == "project-q2"++ def test_stem_match_slug_suffix(self, tmp_path: Path) -> None:+ # Title differs from slug so the title-match loop misses; the+ # `stem.endswith(f"_{needle}")` branch is the one under test.+ pm = PersistentMemory(memory_dir=tmp_path)+ pm.add("My Custom Title", "body", "user", description="d")+ entry = pm.find("my_custom_title")+ assert entry is not None+ assert entry.title == "My Custom Title"++ def test_missing_returns_none(self, tmp_path: Path) -> None:+ pm = _seed(tmp_path)+ assert pm.find("nope") is None++ def test_blank_returns_none(self, tmp_path: Path) -> None:+ pm = _seed(tmp_path)+ assert pm.find(" ") is None+++class TestCmdMemoryList:+ def test_empty_dir_returns_success(self, tmp_path: Path) -> None:+ assert cli.cmd_memory_list(memory_dir=tmp_path) == cli.EXIT_SUCCESS++ def test_lists_all_entries(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ _seed(tmp_path)+ rc = cli.cmd_memory_list(memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_SUCCESS+ assert "user-style" in out+ assert "feedback-tests" in out+ assert "project-q2" in out+ assert "ref-runbook" in out+ assert "4 entries" in out++ def test_type_filter(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ _seed(tmp_path)+ rc = cli.cmd_memory_list("feedback", memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_SUCCESS+ assert "feedback-tests" in out+ assert "user-style" not in out+ assert "1 entry" in out++ def test_type_filter_with_no_matches(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ PersistentMemory(memory_dir=tmp_path).add("only-user", "x", "user")+ rc = cli.cmd_memory_list("feedback", memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_SUCCESS+ assert "No memory entries found type=feedback" in out+++class TestCmdMemoryShow:+ def test_shows_full_body(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ _seed(tmp_path)+ rc = cli.cmd_memory_show("user-style", memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_SUCCESS+ assert "user-style" in out+ assert "Prefer concise replies." in out++ def test_missing_returns_usage_error(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ _seed(tmp_path)+ rc = cli.cmd_memory_show("ghost", memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_USAGE_ERROR+ assert "Memory not found" in out++ def test_resolves_by_slug(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ _seed(tmp_path)+ rc = cli.cmd_memory_show("project_project-q2", memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_SUCCESS+ assert "Q2 focus" in out++ def test_empty_body_renders_placeholder(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ pm = PersistentMemory(memory_dir=tmp_path)+ pm.add("blank-mem", "", "user", description="empty body")+ rc = cli.cmd_memory_show("blank-mem", memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_SUCCESS+ assert "(empty body)" in out++ def test_rich_markup_in_title_is_escaped(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ # Title containing Rich-like syntax must not be interpreted as markup.+ pm = PersistentMemory(memory_dir=tmp_path)+ pm.add("evil[red]title", "ok", "user", description="d")+ rc = cli.cmd_memory_show("evil[red]title", memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_SUCCESS+ assert "evil[red]title" in out+++class TestCmdMemorySearch:+ def test_finds_match(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ _seed(tmp_path)+ rc = cli.cmd_memory_search("execution", memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_SUCCESS+ assert "project-q2" in out++ def test_no_match(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ _seed(tmp_path)+ rc = cli.cmd_memory_search("xyzznope", memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_SUCCESS+ assert "No matches" in out++ def test_limit_respected(self, tmp_path: Path) -> None:+ pm = PersistentMemory(memory_dir=tmp_path)+ for i in range(10):+ pm.add(f"runbook-{i}", "ops runbook content", "reference", description="runbook")+ results_2 = pm.find_relevant("runbook", max_results=2)+ results_5 = pm.find_relevant("runbook", max_results=5)+ assert len(results_2) == 2+ assert len(results_5) == 5+++class TestCmdMemoryForget:+ def test_removes_with_yes_flag(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ _seed(tmp_path)+ rc = cli.cmd_memory_forget("user-style", yes=True, memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_SUCCESS+ assert "Forgot" in out+ # File removed from disk+ remaining = {e.title for e in PersistentMemory(memory_dir=tmp_path).list_entries()}+ assert "user-style" not in remaining+ assert "feedback-tests" in remaining++ def test_missing_returns_usage_error(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ _seed(tmp_path)+ rc = cli.cmd_memory_forget("ghost", yes=True, memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_USAGE_ERROR+ assert "Memory not found" in out++ def test_confirmation_declined_keeps_entry(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ _seed(tmp_path)+ with patch.object(cli.Confirm, "ask", return_value=False):+ rc = cli.cmd_memory_forget("project-q2", yes=False, memory_dir=tmp_path)+ out = capsys.readouterr().out+ # Declining is a successful cancellation, mirroring cmd_init's overwrite prompt.+ assert rc == cli.EXIT_SUCCESS+ assert "Aborted" in out+ remaining = {e.title for e in PersistentMemory(memory_dir=tmp_path).list_entries()}+ assert "project-q2" in remaining++ def test_eof_in_non_interactive_context(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ _seed(tmp_path)+ with patch.object(cli.Confirm, "ask", side_effect=EOFError):+ rc = cli.cmd_memory_forget("project-q2", yes=False, memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_USAGE_ERROR+ assert "--yes" in out++ def test_remove_failure_returns_run_failed(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ _seed(tmp_path)+ with patch.object(PersistentMemory, "remove_entry", return_value=False):+ rc = cli.cmd_memory_forget("project-q2", yes=True, memory_dir=tmp_path)+ out = capsys.readouterr().out+ assert rc == cli.EXIT_RUN_FAILED+ assert "Failed to remove" in out+++class TestParserWiring:+ def test_memory_list_parses(self) -> None:+ parser = cli._build_parser()+ args = parser.parse_args(["memory", "list", "--type", "feedback"])+ assert args.command == "memory"+ assert args.memory_command == "list"+ assert args.memory_type == "feedback"++ def test_memory_show_parses(self) -> None:+ parser = cli._build_parser()+ args = parser.parse_args(["memory", "show", "user-style"])+ assert args.memory_command == "show"+ assert args.name == "user-style"++ def test_memory_search_parses(self) -> None:+ parser = cli._build_parser()+ args = parser.parse_args(["memory", "search", "bitcoin", "--limit", "3"])+ assert args.memory_command == "search"+ assert args.query == "bitcoin"+ assert args.memory_limit == 3++ def test_memory_forget_parses(self) -> None:+ parser = cli._build_parser()+ args = parser.parse_args(["memory", "forget", "user-style", "-y"])+ assert args.memory_command == "forget"+ assert args.name == "user-style"+ assert args.yes is True++ def test_memory_no_subcommand(self) -> None:+ parser = cli._build_parser()+ args = parser.parse_args(["memory"])+ assert args.command == "memory"+ assert args.memory_command is None++ def test_memory_invalid_type_rejected(self) -> None:+ parser = cli._build_parser()+ with pytest.raises(SystemExit):+ parser.parse_args(["memory", "list", "--type", "garbage"])