"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(goal): add research goal runtime
Haozhe Wu2a18d33c232c
diff --git a/agent/api_server.py b/agent/api_server.pyindex 24d59ff0e..652d69941 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -238,6 +238,63 @@ class MessageResponse(BaseModel):metadata: Optional[Dict[str, Any]] = None+class CreateGoalRequest(BaseModel):+ """Create or replace a finance research goal."""++ objective: str = Field(..., min_length=1, max_length=5000)+ criteria: List[str] = Field(default_factory=list)+ ui_summary: str = ""+ protocol: str = "thesis_review"+ risk_tier: str = "research_general"+ token_budget: Optional[int] = Field(None, ge=1)+ turn_budget: Optional[int] = Field(None, ge=1)+ time_budget_seconds: Optional[int] = Field(None, ge=1)+++class AddGoalEvidenceRequest(BaseModel):+ """Append evidence to a finance research goal."""++ goal_id: str = Field(..., min_length=1)+ expected_goal_id: str = Field(..., min_length=1)+ text: str = Field(..., min_length=1, max_length=10000)+ criterion_id: Optional[str] = None+ claim_id: Optional[str] = None+ evidence_type: str = "evidence"+ tool_call_id: Optional[str] = None+ run_id: Optional[str] = None+ source_provider: Optional[str] = None+ source_type: Optional[str] = None+ source_uri: Optional[str] = None+ symbol_universe: List[str] = Field(default_factory=list)+ benchmark: List[str] = Field(default_factory=list)+ timeframe: Optional[str] = None+ method: Optional[str] = None+ assumptions: Dict[str, Any] = Field(default_factory=dict)+ artifact_path: Optional[str] = None+ artifact_hash: Optional[str] = None+ data_as_of: Optional[str] = None+ confidence: Optional[str] = None+ caveat: Optional[str] = None+ contradicts_claim_ids: List[str] = Field(default_factory=list)+++class GoalSnapshotResponse(BaseModel):+ """Finance research goal snapshot."""++ goal: Dict[str, Any]+ claims: List[Dict[str, Any]]+ criteria: List[Dict[str, Any]]+ evidence: List[Dict[str, Any]]+ evidence_count: int = 0+++class AddGoalEvidenceResponse(BaseModel):+ """Response after appending goal evidence."""++ evidence: Dict[str, Any]+ snapshot: GoalSnapshotResponse++# ============================================================================# FastAPI Application@@ -1320,6 +1377,7 @@ async def api_info():# ============================================================================_session_service = None+_goal_store = Nonedef _get_session_service():@@ -1353,6 +1411,26 @@ def _get_session_service():return _session_service+def _get_goal_store():+ """Return the shared finance goal store."""+ global _goal_store+ if _goal_store is None:+ from src.goal import GoalStore++ _goal_store = GoalStore()+ return _goal_store+++def _get_existing_session_or_404(session_id: str):+ svc = _get_session_service()+ if not svc:+ raise HTTPException(status_code=501, detail="Session runtime not enabled")+ session = svc.get_session(session_id)+ if not session:+ raise HTTPException(status_code=404, detail=f"Session {session_id} not found")+ return svc, session++@app.post("/sessions", response_model=SessionResponse, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_auth)])async def create_session(request: CreateSessionRequest):"""Create a chat session."""@@ -1410,6 +1488,124 @@ async def get_session(session_id: str):)+ "/sessions/{session_id}/goal",+ response_model=GoalSnapshotResponse,+ status_code=status.HTTP_201_CREATED,+ dependencies=[Depends(require_auth)],+)+async def create_session_goal(session_id: str, req: CreateGoalRequest):+ """Create or replace the current finance research goal for a session."""+ _validate_path_param(session_id, "session_id")+ svc, _session = _get_existing_session_or_404(session_id)+ from src.goal import RiskTier++ criteria = [item.strip() for item in req.criteria if item.strip()]+ if not criteria:+ criteria = ["Define research thesis", "Record at least one supporting or contradicting evidence row"]+ try:+ risk_tier = RiskTier(req.risk_tier)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=f"invalid risk_tier: {req.risk_tier}") from exc+ if risk_tier is RiskTier.LIVE_TRADING_OR_EXECUTION:+ raise HTTPException(status_code=400, detail="live trading or execution goals are not supported")++ goal_store = _get_goal_store()+ try:+ goal = goal_store.replace_goal(+ session_id=session_id,+ objective=req.objective,+ criteria=criteria,+ ui_summary=req.ui_summary,+ source="api",+ protocol=req.protocol,+ risk_tier=risk_tier,+ token_budget=req.token_budget,+ turn_budget=req.turn_budget,+ time_budget_seconds=req.time_budget_seconds,+ )+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ snapshot = goal_store.get_goal_snapshot(goal.goal_id)+ if snapshot is None:+ raise HTTPException(status_code=500, detail="Goal created but could not be reloaded")+ svc.event_bus.emit(session_id, "goal.created", {"goal": snapshot["goal"]})+ return snapshot+++ "/sessions/{session_id}/goal",+ response_model=GoalSnapshotResponse,+ dependencies=[Depends(require_auth)],+)+async def get_session_goal(session_id: str):+ """Return the current finance research goal snapshot for a session."""+ _validate_path_param(session_id, "session_id")+ _get_existing_session_or_404(session_id)+ snapshot = _get_goal_store().get_current_snapshot(session_id)+ if snapshot is None:+ raise HTTPException(status_code=404, detail="No current goal")+ return snapshot+++ "/sessions/{session_id}/goal/evidence",+ response_model=AddGoalEvidenceResponse,+ status_code=status.HTTP_201_CREATED,+ dependencies=[Depends(require_auth)],+)+async def add_session_goal_evidence(session_id: str, req: AddGoalEvidenceRequest):+ """Append traceable evidence to the current finance research goal."""+ _validate_path_param(session_id, "session_id")+ svc, _session = _get_existing_session_or_404(session_id)+ from dataclasses import asdict+ from src.goal import EvidenceInput, StaleGoalError++ goal_store = _get_goal_store()+ try:+ evidence = goal_store.append_evidence(+ session_id=session_id,+ goal_id=req.goal_id,+ expected_goal_id=req.expected_goal_id,+ evidence=EvidenceInput(+ criterion_id=req.criterion_id,+ claim_id=req.claim_id,+ evidence_type=req.evidence_type,+ text=req.text,+ tool_call_id=req.tool_call_id,+ run_id=req.run_id,+ source_provider=req.source_provider,+ source_type=req.source_type,+ source_uri=req.source_uri,+ symbol_universe=req.symbol_universe,+ benchmark=req.benchmark,+ timeframe=req.timeframe,+ method=req.method,+ assumptions=req.assumptions,+ artifact_path=req.artifact_path,+ artifact_hash=req.artifact_hash,+ data_as_of=req.data_as_of,+ confidence=req.confidence,+ caveat=req.caveat,+ contradicts_claim_ids=req.contradicts_claim_ids,+ ),+ )+ except StaleGoalError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ snapshot = goal_store.get_goal_snapshot(req.goal_id)+ if snapshot is None:+ raise HTTPException(status_code=500, detail="Goal snapshot could not be reloaded")+ svc.event_bus.emit(+ session_id,+ "goal.evidence",+ {"evidence": asdict(evidence), "goal_id": req.goal_id},+ )+ return {"evidence": asdict(evidence), "snapshot": snapshot}++@app.delete("/sessions/{session_id}", dependencies=[Depends(require_auth)])async def delete_session(session_id: str):"""Delete a session."""@@ -1420,6 +1616,7 @@ async def delete_session(session_id: str):deleted = svc.delete_session(session_id)if not deleted:raise HTTPException(status_code=404, detail=f"Session {session_id} not found")+ _get_goal_store().delete_session_goals(session_id)return {"status": "deleted", "session_id": session_id}@@ -1504,6 +1701,7 @@ async def session_events(session_id: str,request: Request,last_event_id: Optional[str] = Query(None, alias="Last-Event-ID"),+ replay: Optional[str] = Query(None),):"""SSE stream for agent events."""_validate_path_param(session_id, "session_id")@@ -1516,9 +1714,19 @@ async def session_events(header_id = request.headers.get("Last-Event-ID")event_id = header_id or last_event_id+ replay_active = (replay or "").lower() == "active"+ replay_all = False+ if replay_active and not event_id and session.last_attempt_id:+ attempt = svc.store.get_attempt(session_id, session.last_attempt_id)+ attempt_status = getattr(attempt.status, "value", attempt.status) if attempt else None+ replay_all = attempt_status == "running"async def event_generator():- async for event in svc.event_bus.subscribe(session_id, last_event_id=event_id):+ async for event in svc.event_bus.subscribe(+ session_id,+ last_event_id=event_id,+ replay_all=replay_all,+ ):if await request.is_disconnected():breakyield event.to_sse()@@ -1594,20 +1802,19 @@ async def upload_file(file: UploadFile):if not file.filename:raise HTTPException(status_code=400, detail="Missing filename")filename = Path(file.filename).name- ext = Path(file.filename).suffix.lower()+ ext = Path(filename).suffix.lower()if ext in _BLOCKED_UPLOAD_EXT or filename.lower() in _BLOCKED_UPLOAD_NAMES:raise HTTPException(status_code=400,detail="This file type is not allowed for upload.",)- UPLOADS_DIR.mkdir(parents=True, exist_ok=True)-safe_name = f"{uuid.uuid4().hex}{ext}"dest = UPLOADS_DIR / safe_nametotal_size = 0try:+ UPLOADS_DIR.mkdir(parents=True, exist_ok=True)with dest.open("wb") as handle:while True:chunk = await file.read(_UPLOAD_CHUNK_SIZE)@@ -1628,14 +1835,17 @@ async def upload_file(file: UploadFile):except OSError as exc:if dest.exists():dest.unlink()- raise HTTPException(status_code=500, detail=f"Failed to store upload: {exc}") from exc+ raise HTTPException(+ status_code=500,+ detail="Upload failed while storing the file. Please retry or choose a different file.",+ ) from excfinally:await file.close()return {"status": "ok",- "file_path": str(dest.resolve()),- "filename": file.filename,+ "file_path": f"uploads/{safe_name}",+ "filename": filename,}diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex 888eb4632..0757e3f13 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -850,6 +850,7 @@ def _run_agent(no_rich: bool = False,stream_output: bool = True,dashboard: Optional[_RunDashboard] = None,+ session_id: str = "",) -> dict:"""Build AgentLoop and execute, return result dict."""from src.tools import build_registry@@ -975,6 +976,7 @@ def _run_agent(persistent_memory=pm,include_shell_tools=True,agent_config=agent_config,+ session_id=session_id or None,warn_callback=_mcp_warn,),llm=ChatLLM(),@@ -985,7 +987,13 @@ def _run_agent(if run_dir_override:agent.memory.run_dir = run_dir_override- return _run_with_graceful_cancel(agent, prompt, history, no_rich=no_rich)+ return _run_with_graceful_cancel(+ agent,+ prompt,+ history,+ no_rich=no_rich,+ session_id=session_id,+ )def _run_with_graceful_cancel(@@ -994,6 +1002,7 @@ def _run_with_graceful_cancel(history: Optional[List[Dict]],*,no_rich: bool,+ session_id: str = "",) -> dict:"""Run an agent loop with first-Ctrl+C = graceful cancel.@@ -1020,7 +1029,7 @@ def _run_with_graceful_cancel(original = _signal.getsignal(_signal.SIGINT)except (ValueError, AttributeError):# Not on a thread that can receive signals — skip the handler swap.- return agent.run(user_message=prompt, history=history)+ return agent.run(user_message=prompt, history=history, session_id=session_id)def _on_sigint(_signum, _frame) -> None:now = time.time()@@ -1041,10 +1050,10 @@ def _run_with_graceful_cancel(_signal.signal(_signal.SIGINT, _on_sigint)except (ValueError, OSError):# signal.signal only works on the main thread of the main interpreter.- return agent.run(user_message=prompt, history=history)+ return agent.run(user_message=prompt, history=history, session_id=session_id)try:- return agent.run(user_message=prompt, history=history)+ return agent.run(user_message=prompt, history=history, session_id=session_id)finally:try:_signal.signal(_signal.SIGINT, original)diff --git a/agent/cli/commands/goal.py b/agent/cli/commands/goal.pynew file mode 100644index 000000000..833ec794f--- /dev/null+++ b/agent/cli/commands/goal.py@@ -0,0 +1,301 @@+"""``/goal`` — manage the current finance research goal from the CLI."""++from __future__ import annotations++import os+from typing import Any++from rich import box+from rich.console import Console+from rich.console import Group+from rich.panel import Panel+from rich.table import Table+from rich.text import Text++from cli.theme import get_console++_goal_store = None+++def _resolve_console() -> Console:+ """Return the shared CLI console."""+ return get_console()+++def _get_goal_store():+ """Return the shared goal store, lazily initialized."""+ global _goal_store+ if _goal_store is None:+ from src.goal import GoalStore++ _goal_store = GoalStore()+ return _goal_store+++def _default_criteria() -> list[str]:+ """Return the MVP finance protocol checklist."""+ return [+ "Define the research-only thesis and symbol universe",+ "Collect fresh market or benchmark evidence",+ "Record caveats, contradictions, and non-advice boundary",+ ]+++def _criterion_is_covered(criterion: dict, evidence: list[dict]) -> bool:+ """Return whether a criterion has completion status or attached evidence."""+ status = str(criterion.get("status") or "").lower()+ if status not in {"", "pending", "open", "unsatisfied"}:+ return True+ criterion_id = criterion.get("criterion_id")+ return any(item.get("criterion_id") == criterion_id for item in evidence)+++def _create_cli_session(ctx: Any, title: str) -> str | None:+ """Create a normal CLI session when /goal is used before the first turn."""+ try:+ from cli._legacy import SESSIONS_DIR+ from src.session.models import Session, SessionStatus+ from src.session.search import get_shared_index+ from src.session.store import SessionStore++ session = Session(+ title=(title[:60] or "Goal research"),+ status=SessionStatus.ACTIVE,+ )+ SessionStore(base_dir=SESSIONS_DIR).create_session(session)+ get_shared_index().index_session(session.session_id, session.title)+ if ctx is not None:+ setattr(ctx, "session_id", session.session_id)+ return session.session_id+ except Exception: # noqa: BLE001+ return None+++def _session_id(ctx: Any, *, title: str = "Goal research", create: bool) -> str | None:+ """Return the active CLI session id, optionally creating one."""+ existing = getattr(ctx, "session_id", None)+ if existing:+ return str(existing)+ env_session_id = os.getenv("VIBE_GOAL_SESSION_ID")+ if env_session_id:+ return env_session_id+ if not create:+ return None+ created = _create_cli_session(ctx, title)+ if created:+ return created+ return "cli-default"+++def _render_snapshot(snapshot: dict, *, title: str = "/goal") -> None:+ """Render a compact goal card."""+ console = _resolve_console()+ goal = snapshot["goal"]+ criteria = snapshot.get("criteria") or []+ evidence = snapshot.get("evidence") or []+ evidence_count = int(snapshot.get("evidence_count", len(evidence)))+ covered = sum(1 for item in criteria if _criterion_is_covered(item, evidence))+ total = len(criteria)++ meta = Table.grid(padding=(0, 2))+ meta.add_column(style="dim", no_wrap=True)+ meta.add_column(ratio=1)+ meta.add_column(style="dim", no_wrap=True)+ meta.add_column(no_wrap=True)+ meta.add_row("goal", str(goal["objective"]), "status", f"[green]{goal['status']}[/green]")+ meta.add_row("id", str(goal["goal_id"]), "progress", f"[cyan]{covered}/{total}[/cyan]")+ meta.add_row("evidence", str(evidence_count), "protocol", str(goal.get("protocol", "thesis_review")))++ criteria_table = Table(+ box=box.SIMPLE_HEAVY,+ show_lines=False,+ expand=True,+ padding=(0, 1),+ )+ criteria_table.add_column("#", style="dim", no_wrap=True, width=3)+ criteria_table.add_column("Criterion", ratio=1)+ criteria_table.add_column("Status", no_wrap=True)+ criteria_table.add_column("Evidence", no_wrap=True)+ for index, criterion in enumerate(criteria, start=1):+ criterion_id = criterion["criterion_id"]+ criterion_evidence = [item for item in evidence if item.get("criterion_id") == criterion_id]+ is_covered = _criterion_is_covered(criterion, evidence)+ status = "[green]covered[/green]" if is_covered else "[yellow]pending[/yellow]"+ evidence_label = (+ f"{len(criterion_evidence)} item{'s' if len(criterion_evidence) != 1 else ''}"+ if criterion_evidence+ else "[dim]needed[/dim]"+ )+ criteria_table.add_row(+ str(index),+ str(criterion["text"]),+ status,+ evidence_label,+ )+ if not criteria:+ criteria_table.add_row("-", "[dim](none)[/dim]", "[dim]pending[/dim]", "[dim]needed[/dim]")++ next_steps = Text()+ next_steps.append("Next ", style="dim")+ next_steps.append("/goal status", style="bold")+ if criteria:+ next_steps.append(" ")+ next_steps.append("/goal evidence <#> <note>", style="bold")++ console.print(+ Panel(+ Group(meta, criteria_table, next_steps),+ title=title,+ border_style="cyan",+ padding=(1, 2),+ )+ )+++def cmd_status(ctx: Any = None, *args: str) -> int: # noqa: ARG001+ """Show the current goal snapshot."""+ session_id = _session_id(ctx, create=False)+ if session_id is None:+ _resolve_console().print(Text("No current goal. Use /goal <objective> to start one.", style="dim"))+ return 0+ snapshot = _get_goal_store().get_current_snapshot(session_id)+ if snapshot is None:+ _resolve_console().print(Text("No current goal. Use /goal <objective> to start one.", style="dim"))+ return 0+ _render_snapshot(snapshot)+ return 0+++def cmd_start(ctx: Any = None, *args: str) -> int:+ """Start or replace the current research goal."""+ objective = " ".join(args).strip()+ if not objective:+ _resolve_console().print(Text("Usage: /goal <research objective>", style="bold red"))+ return 1++ session_id = _session_id(ctx, title=objective, create=True)+ if session_id is None:+ _resolve_console().print(Text("Could not create or resolve a session for /goal.", style="bold red"))+ return 1+ try:+ goal = _get_goal_store().replace_goal(+ session_id=session_id,+ objective=objective,+ criteria=_default_criteria(),+ source="cli",+ protocol="thesis_review",+ )+ except ValueError as exc:+ _resolve_console().print(Text(f"/goal failed: {exc}", style="bold red"))+ return 1+ snapshot = _get_goal_store().get_goal_snapshot(goal.goal_id)+ if snapshot is None:+ _resolve_console().print(Text("Goal created but could not be reloaded.", style="bold red"))+ return 1+ _render_snapshot(snapshot, title="/goal started")+ return 0+++def _resolve_criterion_id(snapshot: dict, token: str) -> str:+ """Resolve a criterion by 1-based index, exact id, or id prefix."""+ criteria = snapshot.get("criteria") or []+ if token.isdigit():+ index = int(token)+ if 1 <= index <= len(criteria):+ return str(criteria[index - 1]["criterion_id"])+ raise ValueError(f"criterion index out of range: {token}")++ matches = [+ item["criterion_id"]+ for item in criteria+ if item["criterion_id"] == token or str(item["criterion_id"]).startswith(token)+ ]+ if len(matches) == 1:+ return str(matches[0])+ if not matches:+ raise ValueError(f"unknown criterion: {token}")+ raise ValueError(f"ambiguous criterion prefix: {token}")+++def cmd_evidence(ctx: Any = None, *args: str) -> int:+ """Append a manual evidence note to the current goal."""+ if len(args) < 2:+ _resolve_console().print(Text("Usage: /goal evidence <criterion-index-or-id> <note>", style="bold red"))+ return 1++ session_id = _session_id(ctx, create=False)+ if session_id is None:+ _resolve_console().print(Text("No current goal. Use /goal <objective> first.", style="bold red"))+ return 1+ snapshot = _get_goal_store().get_current_snapshot(session_id)+ if snapshot is None:+ _resolve_console().print(Text("No current goal. Use /goal <objective> first.", style="bold red"))+ return 1++ criterion_token, *text_parts = args+ text = " ".join(text_parts).strip()+ if not text:+ _resolve_console().print(Text("Evidence note cannot be empty.", style="bold red"))+ return 1++ try:+ criterion_id = _resolve_criterion_id(snapshot, criterion_token)+ from src.goal import EvidenceInput++ _get_goal_store().append_evidence(+ session_id=session_id,+ goal_id=snapshot["goal"]["goal_id"],+ expected_goal_id=snapshot["goal"]["goal_id"],+ evidence=EvidenceInput(+ criterion_id=criterion_id,+ text=text,+ source_provider="cli",+ source_type="manual_note",+ ),+ )+ except Exception as exc: # noqa: BLE001+ _resolve_console().print(Text(f"/goal evidence failed: {exc}", style="bold red"))+ return 1++ updated = _get_goal_store().get_goal_snapshot(snapshot["goal"]["goal_id"])+ if updated is not None:+ _render_snapshot(updated, title="/goal evidence added")+ return 0+++def cmd_help() -> int:+ """Render /goal usage."""+ body = Text()+ body.append("/goal <objective>", style="bold")+ body.append(" start or replace the current research goal\n", style="dim")+ body.append("/goal status", style="bold")+ body.append(" show the current goal snapshot\n", style="dim")+ body.append("/goal evidence <criterion-index-or-id> <note>", style="bold")+ body.append(" append manual evidence\n", style="dim")+ _resolve_console().print(Panel(body, title="/goal", border_style="dim", padding=(1, 2)))+ return 0+++def run(ctx: Any = None, *args: str) -> int:+ """Dispatch /goal subcommands."""+ if not args:+ return cmd_status(ctx)++ command = args[0].lower()+ if command in {"help", "-h", "--help"}:+ return cmd_help()+ if command in {"status", "show"}:+ return cmd_status(ctx, *args[1:])+ if command == "start":+ return cmd_start(ctx, *args[1:])+ if command == "evidence":+ return cmd_evidence(ctx, *args[1:])+ return cmd_start(ctx, *args)+++__all__ = [+ "run",+ "cmd_start",+ "cmd_status",+ "cmd_evidence",+]diff --git a/agent/cli/commands/slash_router.py b/agent/cli/commands/slash_router.pyindex 8eb5515ed..af9250668 100644--- a/agent/cli/commands/slash_router.py+++ b/agent/cli/commands/slash_router.py@@ -36,6 +36,7 @@ SLASH_COMMANDS: tuple[Command, ...] = (Command("model", "Switch LLM provider and model", "cli.commands.chat"),Command("memory", "Show / manage persistent memory", "cli.commands.memory"),Command("history", "Browse and resume prior sessions", "cli.commands.session"),+ Command("goal", "Start / inspect a finance research goal", "cli.commands.goal"),Command("search", "Full-text search across all sessions", "cli.commands.session"),Command("swarm", "Multi-agent presets (committee / quant / risk)", "cli.commands.chat"),Command("skill", "List / load / unload skills", "cli.commands.show"),diff --git a/agent/cli/main.py b/agent/cli/main.pyindex fb3c94df6..797c8aa00 100644--- a/agent/cli/main.py+++ b/agent/cli/main.py@@ -604,6 +604,7 @@ def _run_one_turn(user_input: str, ctx: InteractiveContext) -> None:history=ctx.history[-_HISTORY_RETAINED_TURNS:],max_iter=ctx.max_iter,dashboard=dashboard,+ session_id=ctx.session_id or "",)dashboard.finish(result, time.perf_counter() - start)except (KeyboardInterrupt, BrokenPipeError):diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex 260bf73f0..17be5edfc 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -53,6 +53,7 @@ logger = logging.getLogger(__name__)_skills_loader = None_registry = None+_goal_store = None_include_shell_tools = True@@ -79,6 +80,62 @@ def _get_registry():return _registry+def _get_goal_store():+ """Return the shared finance goal store."""+ global _goal_store+ if _goal_store is None:+ from src.goal import GoalStore++ _goal_store = GoalStore()+ return _goal_store+++def _json_ok(**payload: Any) -> str:+ """Return a standard MCP JSON success envelope."""+ return json.dumps({"status": "ok", **payload}, ensure_ascii=False, indent=2)+++def _json_error(error: str, *, error_type: str = "error") -> str:+ """Return a standard MCP JSON error envelope."""+ return json.dumps(+ {"status": "error", "error_type": error_type, "error": error},+ ensure_ascii=False,+ indent=2,+ )+++def _default_goal_criteria() -> list[str]:+ """Return the MVP finance protocol checklist."""+ return [+ "Define the research-only thesis and symbol universe",+ "Collect fresh market or benchmark evidence",+ "Record caveats, contradictions, and non-advice boundary",+ ]+++def _clean_list(value: list[str] | None) -> list[str]:+ """Strip empty list values from MCP payloads."""+ return [item.strip() for item in (value or []) if item and item.strip()]+++def _blank_to_none(value: str | None) -> str | None:+ """Normalize blank MCP strings to None."""+ if value is None:+ return None+ value = value.strip()+ return value or None+++def _risk_tier_from_text(value: str):+ """Parse and validate goal risk tier."""+ from src.goal import RiskTier++ risk_tier = RiskTier(value)+ if risk_tier is RiskTier.LIVE_TRADING_OR_EXECUTION:+ raise ValueError("live trading or execution goals are not supported")+ return risk_tier++# ---------------------------------------------------------------------------# Skill tools# ---------------------------------------------------------------------------@@ -114,6 +171,171 @@ def load_skill(name: str) -> str:return json.dumps({"status": "ok", "skill": name, "content": content}, ensure_ascii=False)+# ---------------------------------------------------------------------------+# Goal tools+# ---------------------------------------------------------------------------+++def start_research_goal(+ session_id: str,+ objective: str,+ criteria: list[str] | None = None,+ ui_summary: str = "",+ protocol: str = "thesis_review",+ risk_tier: str = "research_general",+ token_budget: int | None = None,+ turn_budget: int | None = None,+ time_budget_seconds: int | None = None,+) -> str:+ """Create or replace the current finance research goal for a session.++ This is the MCP entry point for long-running, research-only finance tasks.+ It creates an auditable goal with checklist criteria and supersedes any+ previous current goal for the same session.++ Args:+ session_id: External conversation/session id owned by the MCP client.+ objective: Research-only objective, not a trade execution request.+ criteria: Optional checklist. Defaults to the MVP finance protocol.+ ui_summary: Optional compact label for UI surfaces.+ protocol: Research protocol name. Defaults to thesis_review.+ risk_tier: One of the supported non-execution risk tiers.+ token_budget: Optional token budget.+ turn_budget: Optional turn budget.+ time_budget_seconds: Optional wall-clock budget.+ """+ try:+ clean_criteria = _clean_list(criteria) or _default_goal_criteria()+ goal = _get_goal_store().replace_goal(+ session_id=session_id.strip(),+ objective=objective,+ criteria=clean_criteria,+ ui_summary=ui_summary,+ source="mcp",+ protocol=protocol,+ risk_tier=_risk_tier_from_text(risk_tier),+ token_budget=token_budget,+ turn_budget=turn_budget,+ time_budget_seconds=time_budget_seconds,+ )+ snapshot = _get_goal_store().get_goal_snapshot(goal.goal_id)+ return _json_ok(snapshot=snapshot)+ except ValueError as exc:+ return _json_error(str(exc), error_type="validation")+++def get_research_goal(session_id: str) -> str:+ """Return the current finance research goal snapshot for a session.++ Args:+ session_id: External conversation/session id owned by the MCP client.+ """+ try:+ snapshot = _get_goal_store().get_current_snapshot(session_id.strip())+ except ValueError as exc:+ return _json_error(str(exc), error_type="validation")+ if snapshot is None:+ return _json_error("No current goal", error_type="not_found")+ return _json_ok(snapshot=snapshot)+++def add_goal_evidence(+ session_id: str,+ goal_id: str,+ expected_goal_id: str,+ text: str,+ criterion_id: str | None = None,+ claim_id: str | None = None,+ evidence_type: str = "evidence",+ tool_call_id: str | None = None,+ run_id: str | None = None,+ source_provider: str | None = None,+ source_type: str | None = None,+ source_uri: str | None = None,+ symbol_universe: list[str] | None = None,+ benchmark: list[str] | None = None,+ timeframe: str | None = None,+ method: str | None = None,+ assumptions: dict[str, Any] | None = None,+ artifact_path: str | None = None,+ artifact_hash: str | None = None,+ data_as_of: str | None = None,+ confidence: str | None = None,+ caveat: str | None = None,+ contradicts_claim_ids: list[str] | None = None,+) -> str:+ """Append traceable evidence to a finance research goal.++ Args:+ session_id: External conversation/session id.+ goal_id: Goal being mutated.+ expected_goal_id: Goal id captured before the tool/model turn started.+ text: Evidence note or result summary.+ criterion_id: Optional criterion this evidence satisfies.+ claim_id: Optional claim this evidence supports or contradicts.+ evidence_type: Evidence category, default evidence.+ tool_call_id: Source tool call id. Presence marks evidence verified.+ run_id: Vibe-Trading run id. Presence marks evidence verified.+ source_provider: Data/provider name such as yfinance, OKX, tushare.+ source_type: Source category such as market_data, document, backtest.+ source_uri: Optional source URL/path.+ symbol_universe: Symbols covered by the evidence.+ benchmark: Benchmark symbols covered by the evidence.+ timeframe: Market timeframe.+ method: Research method used.+ assumptions: Structured assumptions.+ artifact_path: Artifact path. Presence marks evidence verified.+ artifact_hash: Optional artifact hash.+ data_as_of: ISO timestamp/date for data freshness.+ confidence: Optional confidence label.+ caveat: Optional limitation note.+ contradicts_claim_ids: Claim ids contradicted by this evidence.+ """+ try:+ from src.goal import EvidenceInput, StaleGoalError++ evidence = _get_goal_store().append_evidence(+ session_id=session_id.strip(),+ goal_id=goal_id.strip(),+ expected_goal_id=expected_goal_id.strip(),+ evidence=EvidenceInput(+ criterion_id=_blank_to_none(criterion_id),+ claim_id=_blank_to_none(claim_id),+ evidence_type=evidence_type,+ text=text,+ tool_call_id=_blank_to_none(tool_call_id),+ run_id=_blank_to_none(run_id),+ source_provider=_blank_to_none(source_provider),+ source_type=_blank_to_none(source_type),+ source_uri=_blank_to_none(source_uri),+ symbol_universe=_clean_list(symbol_universe),+ benchmark=_clean_list(benchmark),+ timeframe=_blank_to_none(timeframe),+ method=_blank_to_none(method),+ assumptions=assumptions or {},+ artifact_path=_blank_to_none(artifact_path),+ artifact_hash=_blank_to_none(artifact_hash),+ data_as_of=_blank_to_none(data_as_of),+ confidence=_blank_to_none(confidence),+ caveat=_blank_to_none(caveat),+ contradicts_claim_ids=_clean_list(contradicts_claim_ids),+ ),+ )+ snapshot = _get_goal_store().get_goal_snapshot(goal_id.strip())+ if snapshot is None:+ return _json_error("Goal snapshot could not be reloaded")+ from dataclasses import asdict++ return _json_ok(evidence=asdict(evidence), snapshot=snapshot)+ except StaleGoalError as exc:+ return _json_error(str(exc), error_type="stale_goal")+ except ValueError as exc:+ return _json_error(str(exc), error_type="validation")++# ---------------------------------------------------------------------------# Backtest tool# ---------------------------------------------------------------------------diff --git a/agent/src/goal/__init__.py b/agent/src/goal/__init__.pynew file mode 100644index 000000000..ea2b54baf--- /dev/null+++ b/agent/src/goal/__init__.py@@ -0,0 +1,30 @@+"""Finance research goal runtime primitives."""++from src.goal.models import (+ AuditRow,+ EvidenceInput,+ EvidenceRecord,+ GoalClaim,+ GoalCriterion,+ GoalRecord,+ GoalStatus,+ RiskTier,+ StaleGoalError,+)+from src.goal.policy import normalize_required_text, reject_live_execution_objective+from src.goal.store import GoalStore++__all__ = [+ "AuditRow",+ "EvidenceInput",+ "EvidenceRecord",+ "GoalClaim",+ "GoalCriterion",+ "GoalRecord",+ "GoalStatus",+ "GoalStore",+ "RiskTier",+ "StaleGoalError",+ "normalize_required_text",+ "reject_live_execution_objective",+]diff --git a/agent/src/goal/models.py b/agent/src/goal/models.pynew file mode 100644index 000000000..665aa4419--- /dev/null+++ b/agent/src/goal/models.py@@ -0,0 +1,161 @@+"""Data models for finance research goals."""++from __future__ import annotations++from dataclasses import dataclass, field+from enum import Enum+from typing import Any+++class GoalStatus(str, Enum):+ """Lifecycle states for a finance research goal."""++ ACTIVE = "active"+ PAUSED = "paused"+ WAITING_USER = "waiting_user"+ NEEDS_REFRESH = "needs_refresh"+ INSUFFICIENT_EVIDENCE = "insufficient_evidence"+ COMPLIANCE_BLOCKED = "compliance_blocked"+ BLOCKED = "blocked"+ BUDGET_LIMITED = "budget_limited"+ USAGE_LIMITED = "usage_limited"+ COMPLETE = "complete"+ CANCELLED = "cancelled"+ SUPERSEDED = "superseded"+++class RiskTier(str, Enum):+ """Risk classification for goal objectives."""++ RESEARCH_GENERAL = "research_general"+ MARKET_SPECIFIC_SHORT_TERM = "market_specific_short_term"+ PERSONALIZED_ADVICE_OR_POSITION_SIZING = "personalized_advice_or_position_sizing"+ LIVE_TRADING_OR_EXECUTION = "live_trading_or_execution"+++class StaleGoalError(ValueError):+ """Raised when a model turn tries to mutate a stale or replaced goal."""+++@dataclass(frozen=True)+class GoalRecord:+ """Persisted finance research goal record."""++ goal_id: str+ session_id: str+ status: GoalStatus+ objective: str+ ui_summary: str+ source: str+ protocol: str+ risk_tier: RiskTier+ token_budget: int | None = None+ tokens_used: int = 0+ turn_budget: int | None = None+ turns_used: int = 0+ time_budget_seconds: int | None = None+ time_used_seconds: int = 0+ budget_wrapup_sent: bool = False+ created_at: str = ""+ updated_at: str = ""+ completed_at: str | None = None+ recap: str | None = None+++@dataclass(frozen=True)+class GoalClaim:+ """A research claim tracked by the goal ledger."""++ claim_id: str+ goal_id: str+ session_id: str+ claim_type: str+ text: str+ status: str+ created_at: str = ""+ updated_at: str = ""+++@dataclass(frozen=True)+class GoalCriterion:+ """A protocol criterion that must be covered before completion."""++ criterion_id: str+ goal_id: str+ session_id: str+ text: str+ required: bool = True+ status: str = "pending"+ freshness_requirement: str | None = None+ protocol_step: str | None = None+ created_at: str = ""+ updated_at: str = ""+++@dataclass(frozen=True)+class EvidenceInput:+ """Input for appending traceable evidence to a goal."""++ text: str+ criterion_id: str | None = None+ claim_id: str | None = None+ evidence_type: str = "evidence"+ tool_call_id: str | None = None+ run_id: str | None = None+ source_provider: str | None = None+ source_type: str | None = None+ source_uri: str | None = None+ symbol_universe: list[str] = field(default_factory=list)+ benchmark: list[str] = field(default_factory=list)+ timeframe: str | None = None+ method: str | None = None+ assumptions: dict[str, Any] = field(default_factory=dict)+ artifact_path: str | None = None+ artifact_hash: str | None = None+ data_as_of: str | None = None+ confidence: str | None = None+ caveat: str | None = None+ contradicts_claim_ids: list[str] = field(default_factory=list)+++@dataclass(frozen=True)+class EvidenceRecord:+ """Persisted evidence row linked to a goal criterion or claim."""++ evidence_id: str+ goal_id: str+ session_id: str+ text: str+ criterion_id: str | None = None+ claim_id: str | None = None+ evidence_type: str = "evidence"+ tool_call_id: str | None = None+ run_id: str | None = None+ source_provider: str | None = None+ source_type: str | None = None+ source_uri: str | None = None+ symbol_universe: list[str] = field(default_factory=list)+ benchmark: list[str] = field(default_factory=list)+ timeframe: str | None = None+ method: str | None = None+ assumptions: dict[str, Any] = field(default_factory=dict)+ artifact_path: str | None = None+ artifact_hash: str | None = None+ retrieved_at: str = ""+ data_as_of: str | None = None+ freshness_status: str = "unknown"+ verification_status: str = "unverified"+ confidence: str | None = None+ caveat: str | None = None+ contradicts_claim_ids: list[str] = field(default_factory=list)+ created_at: str = ""+++@dataclass(frozen=True)+class AuditRow:+ """Completion audit row for one criterion."""++ criterion_id: str+ result: str+ evidence_ids: list[str]+ notes: str = ""diff --git a/agent/src/goal/policy.py b/agent/src/goal/policy.pynew file mode 100644index 000000000..f070018c8--- /dev/null+++ b/agent/src/goal/policy.py@@ -0,0 +1,48 @@+"""Policy helpers for finance research goals."""++from __future__ import annotations++import re++_EXECUTION_PATTERNS = (+ re.compile(r"\b(place|submit|execute|send)\b.{0,40}\b(order|trade)\b", re.I),+ re.compile(+ r"\b(buy|sell|short|long)\b.{0,40}\b(now|immediately|market order|limit order|shares?|contracts?|btc|eth|usdt)\b",+ re.I,+ ),+ re.compile(r"(下单|市价单|限价单|马上买|立即买|现在买|马上卖|立即卖|现在卖)"),+)+++def normalize_required_text(value: str, field_name: str) -> str:+ """Strip and validate a required text field.++ Args:+ value: User supplied text.+ field_name: Field name for the error message.++ Returns:+ The stripped value.++ Raises:+ ValueError: If the stripped value is empty.+ """+ text = value.strip()+ if not text:+ raise ValueError(f"{field_name} cannot be empty")+ return text+++def reject_live_execution_objective(objective: str) -> None:+ """Reject direct live-trading or order-execution goal text.++ Args:+ objective: Research goal objective.++ Raises:+ ValueError: If the objective looks like an execution request.+ """+ text = objective.strip()+ for pattern in _EXECUTION_PATTERNS:+ if pattern.search(text):+ raise ValueError("live trading or execution goals are not supported")diff --git a/agent/src/goal/store.py b/agent/src/goal/store.pynew file mode 100644index 000000000..98ab42b30--- /dev/null+++ b/agent/src/goal/store.py@@ -0,0 +1,927 @@+"""SQLite-backed store for finance research goals."""++from __future__ import annotations++import hashlib+import json+import sqlite3+import threading+import uuid+from contextlib import contextmanager+from dataclasses import asdict+from datetime import datetime+from enum import Enum+from functools import wraps+from pathlib import Path+from typing import Callable, TypeVar++from src.goal.models import (+ AuditRow,+ EvidenceInput,+ EvidenceRecord,+ GoalClaim,+ GoalCriterion,+ GoalRecord,+ GoalStatus,+ RiskTier,+ StaleGoalError,+)+from src.goal.policy import normalize_required_text, reject_live_execution_objective+from src.tools.path_utils import safe_document_path, safe_run_id++_DEFAULT_DB_PATH = Path.home() / ".vibe-trading" / "sessions.db"++_CURRENT_STATUSES = {+ GoalStatus.ACTIVE,+ GoalStatus.PAUSED,+ GoalStatus.WAITING_USER,+ GoalStatus.NEEDS_REFRESH,+ GoalStatus.INSUFFICIENT_EVIDENCE,+ GoalStatus.COMPLIANCE_BLOCKED,+ GoalStatus.BUDGET_LIMITED,+}++_COMPLETION_RESULTS = {+ "satisfied",+ "satisfied_with_caveat",+ "not_applicable_user_accepted",+}+++def _now_iso() -> str:+ return datetime.now().isoformat()+++def _id(prefix: str) -> str:+ return f"{prefix}_{uuid.uuid4().hex[:12]}"+++def _json_dumps(value: object) -> str:+ return json.dumps(value, ensure_ascii=False, sort_keys=True)+++def _json_loads(value: str | None, default: object) -> object:+ if not value:+ return default+ return json.loads(value)+++def _to_json_dict(value: object) -> dict:+ data = asdict(value)+ for key, item in list(data.items()):+ if isinstance(item, Enum):+ data[key] = item.value+ return data+++F = TypeVar("F", bound=Callable)+++def _synchronized(method: F) -> F:+ """Serialize access to the shared SQLite connection."""++ @wraps(method)+ def wrapper(self, *args, **kwargs): # type: ignore[no-untyped-def]+ with self._lock:+ return method(self, *args, **kwargs)++ return wrapper # type: ignore[return-value]+++class GoalStore:+ """SQLite-backed store for finance research goals."""++ def __init__(self, db_path: Path = _DEFAULT_DB_PATH) -> None:+ """Initialize the goal store.++ Args:+ db_path: SQLite database path.+ """+ self.db_path = Path(db_path)+ self.db_path.parent.mkdir(parents=True, exist_ok=True)+ self._conn = sqlite3.connect(str(self.db_path), check_same_thread=False)+ self._conn.row_factory = sqlite3.Row+ self._conn.execute("PRAGMA foreign_keys=ON")+ self._conn.execute("PRAGMA busy_timeout=5000")+ self._conn.execute("PRAGMA journal_mode=WAL")+ self._conn.execute("PRAGMA synchronous=NORMAL")+ self._lock = threading.RLock()+ self._init_db()++ def _init_db(self) -> None:+ """Create goal tables and indexes if they do not exist."""+ with self._lock:+ self._conn.executescript(+ """+ CREATE TABLE IF NOT EXISTS goals (+ goal_id TEXT PRIMARY KEY,+ session_id TEXT NOT NULL,+ status TEXT NOT NULL,+ objective TEXT NOT NULL,+ ui_summary TEXT NOT NULL,+ source TEXT NOT NULL,+ protocol TEXT NOT NULL,+ risk_tier TEXT NOT NULL,+ token_budget INTEGER,+ tokens_used INTEGER NOT NULL DEFAULT 0,+ turn_budget INTEGER,+ turns_used INTEGER NOT NULL DEFAULT 0,+ time_budget_seconds INTEGER,+ time_used_seconds INTEGER NOT NULL DEFAULT 0,+ budget_wrapup_sent INTEGER NOT NULL DEFAULT 0,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ completed_at TEXT,+ recap TEXT+ );++ CREATE UNIQUE INDEX IF NOT EXISTS idx_goals_one_current_per_session+ ON goals(session_id)+ WHERE status IN (+ 'active',+ 'paused',+ 'waiting_user',+ 'needs_refresh',+ 'insufficient_evidence',+ 'compliance_blocked',+ 'budget_limited'+ );++ CREATE TABLE IF NOT EXISTS goal_claims (+ claim_id TEXT PRIMARY KEY,+ goal_id TEXT NOT NULL,+ session_id TEXT NOT NULL,+ claim_type TEXT NOT NULL,+ text TEXT NOT NULL,+ status TEXT NOT NULL,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ FOREIGN KEY(goal_id) REFERENCES goals(goal_id)+ );++ CREATE INDEX IF NOT EXISTS idx_goal_claims_goal+ ON goal_claims(goal_id, status);++ CREATE TABLE IF NOT EXISTS goal_criteria (+ criterion_id TEXT PRIMARY KEY,+ goal_id TEXT NOT NULL,+ session_id TEXT NOT NULL,+ text TEXT NOT NULL,+ required INTEGER NOT NULL DEFAULT 1,+ status TEXT NOT NULL DEFAULT 'pending',+ freshness_requirement TEXT,+ protocol_step TEXT,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ FOREIGN KEY(goal_id) REFERENCES goals(goal_id)+ );++ CREATE INDEX IF NOT EXISTS idx_goal_criteria_goal+ ON goal_criteria(goal_id, status);++ CREATE TABLE IF NOT EXISTS goal_evidence (+ evidence_id TEXT PRIMARY KEY,+ goal_id TEXT NOT NULL,+ session_id TEXT NOT NULL,+ criterion_id TEXT,+ claim_id TEXT,+ evidence_type TEXT NOT NULL,+ text TEXT NOT NULL,+ tool_call_id TEXT,+ run_id TEXT,+ source_provider TEXT,+ source_type TEXT,+ source_uri TEXT,+ symbol_universe_json TEXT NOT NULL DEFAULT '[]',+ benchmark_json TEXT NOT NULL DEFAULT '[]',+ timeframe TEXT,+ method TEXT,+ assumptions_json TEXT NOT NULL DEFAULT '{}',+ artifact_path TEXT,+ artifact_hash TEXT,+ retrieved_at TEXT NOT NULL,+ data_as_of TEXT,+ freshness_status TEXT NOT NULL DEFAULT 'unknown',+ verification_status TEXT NOT NULL DEFAULT 'unverified',+ confidence TEXT,+ caveat TEXT,+ contradicts_claim_ids_json TEXT NOT NULL DEFAULT '[]',+ created_at TEXT NOT NULL,+ FOREIGN KEY(goal_id) REFERENCES goals(goal_id)+ );++ CREATE INDEX IF NOT EXISTS idx_goal_evidence_goal+ ON goal_evidence(goal_id, created_at);++ CREATE TABLE IF NOT EXISTS goal_audits (+ audit_id TEXT PRIMARY KEY,+ goal_id TEXT NOT NULL,+ session_id TEXT NOT NULL,+ audit_type TEXT NOT NULL,+ result TEXT NOT NULL,+ rows_json TEXT NOT NULL,+ created_at TEXT NOT NULL,+ FOREIGN KEY(goal_id) REFERENCES goals(goal_id)+ );+ """+ )+ if self._conn.execute("PRAGMA user_version").fetchone()[0] < 1:+ self._conn.execute("PRAGMA user_version=1")+ self._conn.commit()++ @contextmanager+ def _write_transaction(self):+ """Open an immediate write transaction for cross-connection safety."""+ self._conn.execute("BEGIN IMMEDIATE")+ try:+ yield+ except Exception:+ self._conn.rollback()+ raise+ else:+ self._conn.commit()++ @_synchronized+ def replace_goal(+ self,+ *,+ session_id: str,+ objective: str,+ criteria: list[str],+ ui_summary: str = "",+ source: str = "api",+ protocol: str = "thesis_review",+ risk_tier: RiskTier = RiskTier.RESEARCH_GENERAL,+ token_budget: int | None = None,+ turn_budget: int | None = None,+ time_budget_seconds: int | None = None,+ ) -> GoalRecord:+ """Supersede the current goal and create a new active goal.++ Args:+ session_id: Owning session id.+ objective: Research objective.+ criteria: Required criteria generated by the finance protocol.+ ui_summary: Optional compact summary.+ source: Source of goal creation.+ protocol: Finance research protocol name.+ risk_tier: Risk classification.+ token_budget: Optional token budget.+ turn_budget: Optional turn budget.+ time_budget_seconds: Optional wall-clock budget.++ Returns:+ The newly active goal.++ Raises:+ ValueError: If objective or criteria are empty.+ """+ session_id = normalize_required_text(session_id, "session_id")+ objective = normalize_required_text(objective, "goal objective")+ reject_live_execution_objective(objective)+ if risk_tier is RiskTier.LIVE_TRADING_OR_EXECUTION:+ raise ValueError("live trading or execution goals are not supported")+ cleaned_criteria = [item.strip() for item in criteria if item.strip()]+ if not cleaned_criteria:+ raise ValueError("at least one goal criterion is required")+ for criterion in cleaned_criteria:+ reject_live_execution_objective(criterion)+ budgets = {+ "token_budget": token_budget,+ "turn_budget": turn_budget,+ "time_budget_seconds": time_budget_seconds,+ }+ for name, value in budgets.items():+ if value is not None and value <= 0:+ raise ValueError(f"{name} must be positive")++ now = _now_iso()+ goal_id = _id("goal")+ summary = ui_summary.strip() or objective[:80]+ current_values = [status.value for status in _CURRENT_STATUSES]+ placeholders = ",".join("?" for _ in current_values)++ with self._write_transaction():+ self._conn.execute(+ f"""+ UPDATE goals+ SET status = ?, updated_at = ?, completed_at = COALESCE(completed_at, ?)+ WHERE session_id = ? AND status IN ({placeholders})+ """,+ [GoalStatus.SUPERSEDED.value, now, now, session_id, *current_values],+ )+ self._conn.execute(+ """+ INSERT INTO goals (+ goal_id, session_id, status, objective, ui_summary, source,+ protocol, risk_tier, token_budget, turn_budget,+ time_budget_seconds, created_at, updated_at+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ goal_id,+ session_id,+ GoalStatus.ACTIVE.value,+ objective,+ summary,+ source,+ protocol,+ risk_tier.value,+ token_budget,+ turn_budget,+ time_budget_seconds,+ now,+ now,+ ),+ )+ self._conn.execute(+ """+ INSERT INTO goal_claims (+ claim_id, goal_id, session_id, claim_type, text,+ status, created_at, updated_at+ )+ VALUES (?, ?, ?, 'thesis', ?, 'active', ?, ?)+ """,+ (_id("claim"), goal_id, session_id, objective, now, now),+ )+ for index, text in enumerate(cleaned_criteria):+ self._conn.execute(+ """+ INSERT INTO goal_criteria (+ criterion_id, goal_id, session_id, text, required,+ status, protocol_step, created_at, updated_at+ )+ VALUES (?, ?, ?, ?, 1, 'pending', ?, ?, ?)+ """,+ (+ _id("crit"),+ goal_id,+ session_id,+ text,+ f"step_{index + 1}",+ now,+ now,+ ),+ )++ goal = self.get_goal(goal_id)+ if goal is None:+ raise RuntimeError("created goal could not be reloaded")+ return goal++ @_synchronized+ def get_goal(self, goal_id: str) -> GoalRecord | None:+ """Return a goal by id."""+ row = self._conn.execute(+ "SELECT * FROM goals WHERE goal_id = ?",+ (normalize_required_text(goal_id, "goal_id"),),+ ).fetchone()+ return self._goal_from_row(row) if row else None++ @_synchronized+ def get_current_goal(self, session_id: str) -> GoalRecord | None:+ """Return the current goal for a session."""+ current_values = [status.value for status in _CURRENT_STATUSES]+ session_id = normalize_required_text(session_id, "session_id")+ placeholders = ",".join("?" for _ in current_values)+ row = self._conn.execute(+ f"""+ SELECT * FROM goals+ WHERE session_id = ? AND status IN ({placeholders})+ ORDER BY updated_at DESC+ LIMIT 1+ """,+ [session_id, *current_values],+ ).fetchone()+ return self._goal_from_row(row) if row else None++ @_synchronized+ def list_criteria(self, goal_id: str) -> list[GoalCriterion]:+ """Return criteria for a goal."""+ rows = self._conn.execute(+ """+ SELECT * FROM goal_criteria+ WHERE goal_id = ?+ ORDER BY+ CASE+ WHEN protocol_step GLOB 'step_[0-9]*' THEN CAST(substr(protocol_step, 6) AS INTEGER)+ ELSE 2147483647+ END,+ created_at,+ criterion_id+ """,+ (normalize_required_text(goal_id, "goal_id"),),+ ).fetchall()+ return [self._criterion_from_row(row) for row in rows]++ @_synchronized+ def list_claims(self, goal_id: str) -> list[GoalClaim]:+ """Return claims for a goal."""+ rows = self._conn.execute(+ """+ SELECT * FROM goal_claims+ WHERE goal_id = ?+ ORDER BY created_at, claim_id+ """,+ (normalize_required_text(goal_id, "goal_id"),),+ ).fetchall()+ return [self._claim_from_row(row) for row in rows]++ @_synchronized+ def list_evidence(self, goal_id: str, limit: int | None = None) -> list[EvidenceRecord]:+ """Return evidence rows for a goal."""+ goal_id = normalize_required_text(goal_id, "goal_id")+ if limit is not None and limit <= 0:+ raise ValueError("evidence limit must be positive")+ if limit is not None:+ rows = self._conn.execute(+ """+ SELECT * FROM (+ SELECT * FROM goal_evidence+ WHERE goal_id = ?+ ORDER BY created_at DESC, evidence_id DESC+ LIMIT ?+ )+ ORDER BY created_at, evidence_id+ """,+ (goal_id, limit),+ ).fetchall()+ return [self._evidence_from_row(row) for row in rows]+ rows = self._conn.execute(+ """+ SELECT * FROM goal_evidence+ WHERE goal_id = ?+ ORDER BY created_at, evidence_id+ """,+ (goal_id,),+ ).fetchall()+ return [self._evidence_from_row(row) for row in rows]++ @_synchronized+ def count_evidence(self, goal_id: str) -> int:+ """Return the total evidence row count for a goal."""+ row = self._conn.execute(+ "SELECT COUNT(*) FROM goal_evidence WHERE goal_id = ?",+ (normalize_required_text(goal_id, "goal_id"),),+ ).fetchone()+ return int(row[0]) if row else 0++ @_synchronized+ def delete_session_goals(self, session_id: str) -> int:+ """Delete all goal ledger rows for a session.++ Args:+ session_id: Session whose goal ledger should be removed.++ Returns:+ Number of goal rows deleted.+ """+ session_id = normalize_required_text(session_id, "session_id")+ with self._write_transaction():+ row = self._conn.execute(+ "SELECT COUNT(*) FROM goals WHERE session_id = ?",+ (session_id,),+ ).fetchone()+ count = int(row[0]) if row else 0+ for table in (+ "goal_audits",+ "goal_evidence",+ "goal_criteria",+ "goal_claims",+ "goals",+ ):+ self._conn.execute(f"DELETE FROM {table} WHERE session_id = ?", (session_id,))+ return count++ @_synchronized+ def get_current_snapshot(self, session_id: str) -> dict | None:+ """Return the current goal plus ledger rows for a session."""+ goal = self.get_current_goal(session_id)+ if goal is None:+ return None+ return self.get_goal_snapshot(goal.goal_id)++ @_synchronized+ def get_goal_snapshot(self, goal_id: str, evidence_limit: int | None = 50) -> dict | None:+ """Return a JSON-safe goal snapshot."""+ goal = self.get_goal(goal_id)+ if goal is None:+ return None+ evidence = self.list_evidence(goal.goal_id, limit=evidence_limit)+ return {+ "goal": _to_json_dict(goal),+ "claims": [_to_json_dict(item) for item in self.list_claims(goal.goal_id)],+ "criteria": [_to_json_dict(item) for item in self.list_criteria(goal.goal_id)],+ "evidence": [_to_json_dict(item) for item in evidence],+ "evidence_count": self.count_evidence(goal.goal_id),+ }++ @_synchronized+ def append_evidence(+ self,+ *,+ session_id: str,+ goal_id: str,+ expected_goal_id: str,+ evidence: EvidenceInput,+ ) -> EvidenceRecord:+ """Append traceable evidence after stale-goal validation.++ Args:+ session_id: Owning session id.+ goal_id: Goal being mutated.+ expected_goal_id: Goal id captured at the start of the agent turn.+ evidence: Evidence payload.++ Returns:+ Persisted evidence record.++ Raises:+ StaleGoalError: If the expected goal id does not match or goal is not current.+ ValueError: If evidence text is empty or references an unknown criterion.+ """+ evidence_id = _id("ev")+ with self._write_transaction():+ goal = self._require_mutable_goal(session_id, goal_id, expected_goal_id)+ session_id = goal.session_id+ goal_id = goal.goal_id+ text = evidence.text.strip()+ if not text:+ raise ValueError("evidence text cannot be empty")+ if evidence.criterion_id is not None:+ self._require_criterion(goal.goal_id, evidence.criterion_id)+ if evidence.claim_id is not None:+ self._require_claim(goal.goal_id, evidence.claim_id)++ now = _now_iso()+ freshness_status = "fresh" if evidence.data_as_of else "unknown"+ verification_status = self._verification_status(evidence)+ self._conn.execute(+ """+ INSERT INTO goal_evidence (+ evidence_id, goal_id, session_id, criterion_id, claim_id,+ evidence_type, text, tool_call_id, run_id, source_provider,+ source_type, source_uri, symbol_universe_json, benchmark_json,+ timeframe, method, assumptions_json, artifact_path,+ artifact_hash, retrieved_at, data_as_of, freshness_status,+ verification_status, confidence, caveat,+ contradicts_claim_ids_json, created_at+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ evidence_id,+ goal_id,+ session_id,+ evidence.criterion_id,+ evidence.claim_id,+ evidence.evidence_type,+ text,+ evidence.tool_call_id,+ evidence.run_id,+ evidence.source_provider,+ evidence.source_type,+ evidence.source_uri,+ _json_dumps(evidence.symbol_universe),+ _json_dumps(evidence.benchmark),+ evidence.timeframe,+ evidence.method,+ _json_dumps(evidence.assumptions),+ evidence.artifact_path,+ evidence.artifact_hash,+ now,+ evidence.data_as_of,+ freshness_status,+ verification_status,+ evidence.confidence,+ evidence.caveat,+ _json_dumps(evidence.contradicts_claim_ids),+ now,+ ),+ )++ record = self._get_evidence(evidence_id)+ if record is None:+ raise RuntimeError("created evidence could not be reloaded")+ return record++ @_synchronized+ def update_status(+ self,+ *,+ session_id: str,+ goal_id: str,+ expected_goal_id: str,+ status: GoalStatus,+ audit: list[AuditRow] | None = None,+ recap: str | None = None,+ ) -> GoalRecord:+ """Update a goal status with stale-goal and completion validation."""+ with self._write_transaction():+ goal = self._require_mutable_goal(session_id, goal_id, expected_goal_id)+ session_id = goal.session_id+ goal_id = goal.goal_id+ if status is GoalStatus.COMPLETE:+ self._validate_completion_audit(goal, audit or [])++ now = _now_iso()+ completed_at = now if status in {+ GoalStatus.COMPLETE,+ GoalStatus.BLOCKED,+ GoalStatus.CANCELLED,+ GoalStatus.SUPERSEDED,+ GoalStatus.USAGE_LIMITED,+ } else None+ self._conn.execute(+ """+ UPDATE goals+ SET status = ?, updated_at = ?, completed_at = COALESCE(?, completed_at),+ recap = COALESCE(?, recap)+ WHERE goal_id = ? AND session_id = ?+ """,+ (status.value, now, completed_at, recap, goal_id, session_id),+ )+ if audit:+ self._conn.execute(+ """+ INSERT INTO goal_audits (+ audit_id, goal_id, session_id, audit_type, result,+ rows_json, created_at+ )+ VALUES (?, ?, ?, 'completion', ?, ?, ?)+ """,+ (+ _id("audit"),+ goal_id,+ session_id,+ status.value,+ _json_dumps([row.__dict__ for row in audit]),+ now,+ ),+ )+ if audit and status is GoalStatus.COMPLETE:+ for row in audit:+ self._conn.execute(+ """+ UPDATE goal_criteria+ SET status = ?, updated_at = ?+ WHERE goal_id = ? AND session_id = ? AND criterion_id = ?+ """,+ (row.result, now, goal_id, session_id, row.criterion_id),+ )++ updated = self.get_goal(goal_id)+ if updated is None:+ raise RuntimeError("updated goal could not be reloaded")+ return updated++ @_synchronized+ def account_usage(+ self,+ *,+ session_id: str,+ goal_id: str,+ expected_goal_id: str,+ token_delta: int = 0,+ time_delta_seconds: int = 0,+ turn_delta: int = 0,+ ) -> GoalRecord:+ """Account usage and move the goal to budget_limited if needed."""+ if min(token_delta, time_delta_seconds, turn_delta) < 0:+ raise ValueError("usage deltas must be non-negative")++ with self._write_transaction():+ goal = self._require_mutable_goal(session_id, goal_id, expected_goal_id)+ session_id = goal.session_id+ goal_id = goal.goal_id+ tokens_used = goal.tokens_used + token_delta+ time_used_seconds = goal.time_used_seconds + time_delta_seconds+ turns_used = goal.turns_used + turn_delta+ crosses_budget = (+ (goal.token_budget is not None and tokens_used >= goal.token_budget)+ or (+ goal.time_budget_seconds is not None+ and time_used_seconds >= goal.time_budget_seconds+ )+ or (goal.turn_budget is not None and turns_used >= goal.turn_budget)+ )+ next_status = GoalStatus.BUDGET_LIMITED if crosses_budget else goal.status+ now = _now_iso()+ self._conn.execute(+ """+ UPDATE goals+ SET tokens_used = ?, time_used_seconds = ?, turns_used = ?,+ status = ?, updated_at = ?+ WHERE goal_id = ? AND session_id = ?+ """,+ (+ tokens_used,+ time_used_seconds,+ turns_used,+ next_status.value,+ now,+ goal_id,+ session_id,+ ),+ )++ updated = self.get_goal(goal_id)+ if updated is None:+ raise RuntimeError("usage-updated goal could not be reloaded")+ return updated++ def _require_mutable_goal(+ self,+ session_id: str,+ goal_id: str,+ expected_goal_id: str,+ ) -> GoalRecord:+ if expected_goal_id != goal_id:+ raise StaleGoalError("expected_goal_id does not match target goal")+ session_id = normalize_required_text(session_id, "session_id")+ goal_id = normalize_required_text(goal_id, "goal_id")+ goal = self.get_goal(goal_id)+ if goal is None or goal.session_id != session_id:+ raise StaleGoalError("goal is not available for this session")+ if goal.status not in _CURRENT_STATUSES:+ raise StaleGoalError(f"goal status {goal.status.value!r} is not mutable")+ current = self.get_current_goal(session_id)+ if current is None or current.goal_id != goal_id:+ raise StaleGoalError("goal is not current for this session")+ return goal++ @staticmethod+ def _verification_status(evidence: EvidenceInput) -> str:+ """Return whether evidence has a traceable local artifact/run source."""+ if evidence.artifact_path:+ try:+ artifact = safe_document_path(evidence.artifact_path)+ except ValueError:+ artifact = None+ if artifact and artifact.is_file():+ if GoalStore._artifact_hash_matches(artifact, evidence.artifact_hash):+ return "verified"+ if evidence.run_id:+ try:+ run_dir = safe_run_id(evidence.run_id)+ except ValueError:+ run_dir = None+ if run_dir and run_dir.is_dir():+ return "verified"+ return "unverified"++ @staticmethod+ def _artifact_hash_matches(path: Path, expected_hash: str | None) -> bool:+ if not expected_hash:+ return False+ try:+ digest = hashlib.sha256(path.read_bytes()).hexdigest()+ except OSError:+ return False+ return digest == expected_hash.lower().removeprefix("sha256:")++ def _require_criterion(self, goal_id: str, criterion_id: str) -> GoalCriterion:+ row = self._conn.execute(+ """+ SELECT * FROM goal_criteria+ WHERE goal_id = ? AND criterion_id = ?+ """,+ (goal_id, criterion_id),+ ).fetchone()+ if row is None:+ raise ValueError(f"unknown criterion_id: {criterion_id}")+ return self._criterion_from_row(row)++ def _require_claim(self, goal_id: str, claim_id: str) -> GoalClaim:+ row = self._conn.execute(+ """+ SELECT * FROM goal_claims+ WHERE goal_id = ? AND claim_id = ?+ """,+ (goal_id, claim_id),+ ).fetchone()+ if row is None:+ raise ValueError(f"unknown claim_id: {claim_id}")+ return self._claim_from_row(row)++ def _validate_completion_audit(+ self,+ goal: GoalRecord,+ audit: list[AuditRow],+ ) -> None:+ criteria = self.list_criteria(goal.goal_id)+ rows_by_criterion = {row.criterion_id: row for row in audit}+ for criterion in criteria:+ if not criterion.required:+ continue+ row = rows_by_criterion.get(criterion.criterion_id)+ if row is None:+ raise ValueError(f"missing audit row for criterion {criterion.criterion_id}")+ if row.result not in _COMPLETION_RESULTS:+ raise ValueError(f"criterion {criterion.criterion_id} is not satisfied")+ if row.result in {"satisfied", "satisfied_with_caveat"} and not row.evidence_ids:+ raise ValueError("complete goals require verified evidence")+ if row.result == "not_applicable_user_accepted" and not row.notes.strip():+ raise ValueError("not-applicable criteria require acceptance notes")+ for evidence_id in row.evidence_ids:+ evidence = self._get_evidence(evidence_id)+ if evidence is None or evidence.goal_id != goal.goal_id:+ raise ValueError(f"unknown evidence_id: {evidence_id}")+ if evidence.criterion_id != criterion.criterion_id:+ raise ValueError(+ f"evidence {evidence_id} does not match criterion {criterion.criterion_id}"+ )+ if evidence.verification_status != "verified":+ raise ValueError("complete goals require verified evidence")++ def _get_evidence(self, evidence_id: str) -> EvidenceRecord | None:+ row = self._conn.execute(+ "SELECT * FROM goal_evidence WHERE evidence_id = ?",+ (evidence_id,),+ ).fetchone()+ return self._evidence_from_row(row) if row else None++ @staticmethod+ def _goal_from_row(row: sqlite3.Row) -> GoalRecord:+ return GoalRecord(+ goal_id=row["goal_id"],+ session_id=row["session_id"],+ status=GoalStatus(row["status"]),+ objective=row["objective"],+ ui_summary=row["ui_summary"],+ source=row["source"],+ protocol=row["protocol"],+ risk_tier=RiskTier(row["risk_tier"]),+ token_budget=row["token_budget"],+ tokens_used=row["tokens_used"],+ turn_budget=row["turn_budget"],+ turns_used=row["turns_used"],+ time_budget_seconds=row["time_budget_seconds"],+ time_used_seconds=row["time_used_seconds"],+ budget_wrapup_sent=bool(row["budget_wrapup_sent"]),+ created_at=row["created_at"],+ updated_at=row["updated_at"],+ completed_at=row["completed_at"],+ recap=row["recap"],+ )++ @staticmethod+ def _criterion_from_row(row: sqlite3.Row) -> GoalCriterion:+ return GoalCriterion(+ criterion_id=row["criterion_id"],+ goal_id=row["goal_id"],+ session_id=row["session_id"],+ text=row["text"],+ required=bool(row["required"]),+ status=row["status"],+ freshness_requirement=row["freshness_requirement"],+ protocol_step=row["protocol_step"],+ created_at=row["created_at"],+ updated_at=row["updated_at"],+ )++ @staticmethod+ def _claim_from_row(row: sqlite3.Row) -> GoalClaim:+ return GoalClaim(+ claim_id=row["claim_id"],+ goal_id=row["goal_id"],+ session_id=row["session_id"],+ claim_type=row["claim_type"],+ text=row["text"],+ status=row["status"],+ created_at=row["created_at"],+ updated_at=row["updated_at"],+ )++ @staticmethod+ def _evidence_from_row(row: sqlite3.Row) -> EvidenceRecord:+ return EvidenceRecord(+ evidence_id=row["evidence_id"],+ goal_id=row["goal_id"],+ session_id=row["session_id"],+ criterion_id=row["criterion_id"],+ claim_id=row["claim_id"],+ evidence_type=row["evidence_type"],+ text=row["text"],+ tool_call_id=row["tool_call_id"],+ run_id=row["run_id"],+ source_provider=row["source_provider"],+ source_type=row["source_type"],+ source_uri=row["source_uri"],+ symbol_universe=list(_json_loads(row["symbol_universe_json"], [])),+ benchmark=list(_json_loads(row["benchmark_json"], [])),+ timeframe=row["timeframe"],+ method=row["method"],+ assumptions=dict(_json_loads(row["assumptions_json"], {})),+ artifact_path=row["artifact_path"],+ artifact_hash=row["artifact_hash"],+ retrieved_at=row["retrieved_at"],+ data_as_of=row["data_as_of"],+ freshness_status=row["freshness_status"],+ verification_status=row["verification_status"],+ confidence=row["confidence"],+ caveat=row["caveat"],+ contradicts_claim_ids=list(_json_loads(row["contradicts_claim_ids_json"], [])),+ created_at=row["created_at"],+ )diff --git a/agent/src/session/events.py b/agent/src/session/events.pyindex 1d6393a26..46eb93ab1 100644--- a/agent/src/session/events.py+++ b/agent/src/session/events.py@@ -146,20 +146,29 @@ class EventBus:self.publish(event)return event- def replay(self, session_id: str, last_event_id: Optional[str] = None) -> List[SSEEvent]:+ def replay(+ self,+ session_id: str,+ last_event_id: Optional[str] = None,+ *,+ replay_all: bool = False,+ ) -> List[SSEEvent]:"""Replay buffered session events for reconnect recovery.Args:session_id: Session ID.last_event_id: Last event ID received by the client.+ replay_all: Return the buffered stream from the beginning when+ ``last_event_id`` is absent. Used only for active run recovery;+ completed history is loaded through REST.Returns:List of events that should be replayed."""- if not last_event_id:- return [] # First connect: history loaded via REST, no replay neededwith self._lock:buffer = self._buffers.get(session_id, [])+ if not last_event_id:+ return list(buffer) if replay_all else [] # First connect: history loaded via REST by default.found = Falseresult: List[SSEEvent] = []for event in buffer:@@ -173,12 +182,16 @@ class EventBus:self,session_id: str,last_event_id: Optional[str] = None,+ *,+ replay_all: bool = False,) -> AsyncIterator[SSEEvent]:"""Subscribe to a session event stream asynchronously.Args:session_id: Session ID.last_event_id: Last event ID received by the client for reconnect recovery.+ replay_all: Replay all buffered events when no last event ID is+ available. This is opt-in for active run hydration.Yields:SSEEvent objects.@@ -191,7 +204,7 @@ class EventBus:self._subscribers[session_id].append(queue)try:- replay_events = self.replay(session_id, last_event_id)+ replay_events = self.replay(session_id, last_event_id, replay_all=replay_all)for event in replay_events:yield eventdiff --git a/agent/src/session/service.py b/agent/src/session/service.pyindex f84e5556d..99e4c2b24 100644--- a/agent/src/session/service.py+++ b/agent/src/session/service.py@@ -244,6 +244,8 @@ class SessionService:persistent_memory=pm,include_shell_tools=include_shell_tools,agent_config=agent_config,+ session_id=session_id,+ event_callback=event_callback,warn_callback=_mcp_collision_warn,),)diff --git a/agent/src/skills/research-goal/SKILL.md b/agent/src/skills/research-goal/SKILL.mdnew file mode 100644index 000000000..704ee1af3--- /dev/null+++ b/agent/src/skills/research-goal/SKILL.md@@ -0,0 +1,48 @@+---+name: research-goal+description: Goal-driven finance research workflow: attach a research-only objective, track criteria, and add evidence while avoiding live trading execution.+category: flow+---++# Goal-Driven Finance Research++Use this skill when a user asks for a multi-step finance research task, comparison, audit, thesis review, or "keep working until the answer is supported." The goal runtime is for research only. Never use it to place, submit, or execute trades.++## When to Attach a Goal++Start a goal when the task has any of these traits:++- It needs multiple criteria before a conclusion is credible.+- It compares strategies, assets, regimes, or evidence sources.+- It may continue across turns or require a final audit.+- The user asks for "long driven task", "goal", "审计", "对比", "研究结论", or similar.++Do not start a goal for a tiny one-shot answer unless the user explicitly asks.++## Tool Flow++1. Call `start_research_goal` with a concise research-only objective.+2. Include 3-5 acceptance criteria when the user provided enough context.+3. Before continuing an existing task, call `get_research_goal`.+4. After a market-data lookup, backtest, document read, web source, or manual reasoning step, call `add_goal_evidence`.+5. Link evidence to a criterion using `criterion_id` or `criterion_index`.++## Criteria Template++Use this shape when the user did not provide criteria:++- Define the research-only thesis and symbol universe.+- Collect fresh market, benchmark, or artifact evidence.+- Compare alternatives or a control baseline.+- Record caveats, contradictions, and the non-advice boundary.++## Evidence Rules++- Keep evidence short and concrete.+- Prefer artifact-backed evidence when a tool produced a run or file.+- Include `run_id`, `artifact_path`, `source_provider`, `source_type`, `symbol_universe`, `benchmark`, and `data_as_of` when known.+- Do not mark live trading instructions as evidence. Refuse or reframe them as research-only analysis.++## Response Style++Tell the user what the goal is tracking only when it helps. Do not flood the answer with ledger details. Lead with the research conclusion, then mention which criteria remain unresolved.diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.pyindex 682794ba0..465b2f063 100644--- a/agent/src/tools/__init__.py+++ b/agent/src/tools/__init__.py@@ -67,6 +67,8 @@ def build_registry(persistent_memory: "PersistentMemory | None" = None,include_shell_tools: bool = False,agent_config: "AgentConfig | None" = None,+ session_id: str | None = None,+ event_callback: Callable[[str, dict], None] | None = None,warn_callback: Callable[[str], None] | None = None,) -> ToolRegistry:"""Build the tool registry via auto-discovery, optionally enriched with MCP tools.@@ -89,6 +91,10 @@ def build_registry(non-empty, MCP tools are appended to the registry after localtool discovery. Pass ``None`` (default) to preserve existingbehavior with no MCP integration.+ session_id: Optional current session id injected into local tools that+ persist per-session state.+ event_callback: Optional event callback injected into local tools that+ mutate session-scoped state.warn_callback: Optional callable invoked with operator-facing warningmessages. When provided, server-name collision warnings are passedto this callback in addition to the standard logger so CLI and@@ -98,9 +104,11 @@ def build_registry(ToolRegistry containing all available local tools followed by anysuccessfully discovered MCP tools."""+ from src.tools.goal_tool import AddGoalEvidenceTool, GetResearchGoalTool, StartResearchGoalToolfrom src.tools.remember_tool import RememberToolfrom src.tools.swarm_tool import SwarmTool+ goal_tool_classes = {StartResearchGoalTool, GetResearchGoalTool, AddGoalEvidenceTool}registry = ToolRegistry()for cls in _discover_subclasses():try:@@ -112,6 +120,8 @@ def build_registry(continueif cls is RememberTool and persistent_memory is not None:registry.register(cls(memory=persistent_memory))+ elif cls in goal_tool_classes:+ registry.register(cls(default_session_id=session_id, event_callback=event_callback))elif cls is SwarmTool:registry.register(cls(include_shell_tools=include_shell_tools))else:diff --git a/agent/src/tools/goal_tool.py b/agent/src/tools/goal_tool.pynew file mode 100644index 000000000..12061fcca--- /dev/null+++ b/agent/src/tools/goal_tool.py@@ -0,0 +1,307 @@+"""Local agent tools for finance research goals."""++from __future__ import annotations++import json+from typing import Any, Callable++from src.agent.tools import BaseTool+from src.goal import EvidenceInput, GoalStore, RiskTier, StaleGoalError+++def _default_criteria() -> list[str]:+ """Return the minimal finance research goal checklist."""+ return [+ "Define the research-only thesis and symbol universe",+ "Collect fresh market or benchmark evidence",+ "Record caveats, contradictions, and non-advice boundary",+ ]+++def _json_error(error: str, *, error_type: str = "validation") -> str:+ """Return a standard JSON error envelope."""+ return json.dumps(+ {"status": "error", "error_type": error_type, "error": error},+ ensure_ascii=False,+ )+++def _coerce_string_list(value: Any) -> list[str]:+ """Coerce a JSON-schema array-or-string value to a string list."""+ if value is None:+ return []+ if isinstance(value, str):+ return [value] if value.strip() else []+ if isinstance(value, list):+ return [str(item).strip() for item in value if str(item).strip()]+ return []+++class _GoalToolBase(BaseTool):+ """Shared helpers for local goal tools."""++ repeatable = True++ def __init__(+ self,+ *,+ default_session_id: str | None = None,+ store: GoalStore | None = None,+ event_callback: Callable[[str, dict[str, Any]], None] | None = None,+ ) -> None:+ """Initialize a local goal tool.++ Args:+ default_session_id: Session id injected by the host runtime.+ store: Optional store override for tests.+ event_callback: Optional host callback for live UI updates.+ """+ self._default_session_id = default_session_id+ self._store = store or GoalStore()+ self._event_callback = event_callback++ def _session_id(self, kwargs: dict[str, Any]) -> str | None:+ value = str(kwargs.get("session_id") or self._default_session_id or "").strip()+ return value or None++ def _emit(self, event_type: str, data: dict[str, Any]) -> None:+ """Best-effort host event emission for goal mutations."""+ if self._event_callback is None:+ return+ try:+ self._event_callback(event_type, data)+ except Exception:+ return+++class StartResearchGoalTool(_GoalToolBase):+ """Start or replace the current research-only goal."""++ name = "start_research_goal"+ description = (+ "Start or replace the current finance research goal for this session. "+ "Use for long-running research tasks, multi-step market analysis, or "+ "evidence-driven conclusions. Research-only; live trading objectives are rejected."+ )+ is_readonly = False+ parameters = {+ "type": "object",+ "properties": {+ "session_id": {+ "type": "string",+ "description": "Optional session id. Omit when the host runtime injected the current session.",+ },+ "objective": {+ "type": "string",+ "description": "Research-only goal objective.",+ },+ "criteria": {+ "type": "array",+ "items": {"type": "string"},+ "description": "Optional acceptance criteria. Defaults to the finance research checklist.",+ },+ "risk_tier": {+ "type": "string",+ "enum": [+ "research_general",+ "market_specific_short_term",+ "personalized_advice_or_position_sizing",+ ],+ "description": "Research risk tier. Live trading/execution is not supported.",+ },+ "token_budget": {"type": "integer", "description": "Optional positive token budget."},+ "turn_budget": {"type": "integer", "description": "Optional positive turn budget."},+ "time_budget_seconds": {"type": "integer", "description": "Optional positive wall-clock budget."},+ },+ "required": ["objective"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Start a research goal.++ Args:+ **kwargs: Tool arguments from the model.++ Returns:+ JSON envelope with the goal snapshot or an error.+ """+ session_id = self._session_id(kwargs)+ if not session_id:+ return _json_error("session_id is required")++ try:+ criteria = _coerce_string_list(kwargs.get("criteria")) or _default_criteria()+ goal = self._store.replace_goal(+ session_id=session_id,+ objective=str(kwargs.get("objective", "")),+ criteria=criteria,+ source="agent_tool",+ protocol="thesis_review",+ risk_tier=RiskTier(str(kwargs.get("risk_tier") or RiskTier.RESEARCH_GENERAL.value)),+ token_budget=kwargs.get("token_budget"),+ turn_budget=kwargs.get("turn_budget"),+ time_budget_seconds=kwargs.get("time_budget_seconds"),+ )+ snapshot = self._store.get_goal_snapshot(goal.goal_id)+ if snapshot is not None:+ self._emit("goal.created", {"goal": snapshot["goal"]})+ return json.dumps({"status": "ok", "snapshot": snapshot}, ensure_ascii=False)+ except (TypeError, ValueError) as exc:+ return _json_error(str(exc))+++class GetResearchGoalTool(_GoalToolBase):+ """Read the current research goal snapshot."""++ name = "get_research_goal"+ description = "Read the current finance research goal, criteria, claims, and latest evidence."+ parameters = {+ "type": "object",+ "properties": {+ "session_id": {+ "type": "string",+ "description": "Optional session id. Omit when the host runtime injected the current session.",+ },+ },+ "required": [],+ }++ def execute(self, **kwargs: Any) -> str:+ """Return the current goal snapshot.++ Args:+ **kwargs: Optional session_id.++ Returns:+ JSON envelope with the current goal snapshot or a not_found error.+ """+ session_id = self._session_id(kwargs)+ if not session_id:+ return _json_error("session_id is required")+ try:+ snapshot = self._store.get_current_snapshot(session_id)+ except ValueError as exc:+ return _json_error(str(exc))+ if snapshot is None:+ return _json_error("no current goal for this session", error_type="not_found")+ return json.dumps({"status": "ok", "snapshot": snapshot}, ensure_ascii=False)+++class AddGoalEvidenceTool(_GoalToolBase):+ """Attach evidence to the current research goal."""++ name = "add_goal_evidence"+ description = (+ "Attach a concise evidence note, artifact reference, or tool result to the current "+ "research goal. Prefer linking evidence to a criterion by criterion_id or criterion_index."+ )+ is_readonly = False+ parameters = {+ "type": "object",+ "properties": {+ "session_id": {+ "type": "string",+ "description": "Optional session id. Omit when the host runtime injected the current session.",+ },+ "goal_id": {"type": "string", "description": "Optional goal id. Defaults to the current goal."},+ "expected_goal_id": {+ "type": "string",+ "description": "Optional stale-write guard. Defaults to goal_id.",+ },+ "criterion_id": {"type": "string", "description": "Criterion id to satisfy."},+ "criterion_index": {+ "type": "integer",+ "description": "1-based criterion index, used when criterion_id is not known.",+ },+ "claim_id": {"type": "string", "description": "Optional claim id."},+ "text": {"type": "string", "description": "Evidence note or artifact summary."},+ "run_id": {"type": "string", "description": "Optional local run id that produced this evidence."},+ "tool_call_id": {"type": "string", "description": "Optional tool call id for traceability."},+ "source_provider": {"type": "string", "description": "Data or tool provider."},+ "source_type": {"type": "string", "description": "Source type, e.g. backtest, market_data, manual_note."},+ "source_uri": {"type": "string", "description": "Optional source URI."},+ "symbol_universe": {+ "type": "array",+ "items": {"type": "string"},+ "description": "Symbols covered by the evidence.",+ },+ "benchmark": {+ "type": "array",+ "items": {"type": "string"},+ "description": "Benchmarks used by the evidence.",+ },+ "timeframe": {"type": "string", "description": "Evidence timeframe."},+ "method": {"type": "string", "description": "Method used to produce the evidence."},+ "artifact_path": {"type": "string", "description": "Optional local artifact path."},+ "artifact_hash": {"type": "string", "description": "Optional sha256 for artifact_path."},+ "data_as_of": {"type": "string", "description": "Timestamp/date the data is current as of."},+ "confidence": {"type": "string", "description": "Optional confidence label."},+ "caveat": {"type": "string", "description": "Optional caveat."},+ },+ "required": ["text"],+ }++ def execute(self, **kwargs: Any) -> str:+ """Append evidence to a goal.++ Args:+ **kwargs: Tool arguments from the model.++ Returns:+ JSON envelope with the evidence row and updated snapshot.+ """+ session_id = self._session_id(kwargs)+ if not session_id:+ return _json_error("session_id is required")+ try:+ snapshot = self._store.get_current_snapshot(session_id)+ if snapshot is None:+ return _json_error("no current goal for this session", error_type="not_found")++ goal_id = str(kwargs.get("goal_id") or snapshot["goal"]["goal_id"])+ expected_goal_id = str(kwargs.get("expected_goal_id") or goal_id)+ criterion_id = str(kwargs.get("criterion_id") or "").strip() or None+ if criterion_id is None and kwargs.get("criterion_index") is not None:+ index = int(kwargs["criterion_index"])+ criteria = snapshot.get("criteria") or []+ if index < 1 or index > len(criteria):+ return _json_error(f"criterion_index out of range: {index}")+ criterion_id = str(criteria[index - 1]["criterion_id"])++ record = self._store.append_evidence(+ session_id=session_id,+ goal_id=goal_id,+ expected_goal_id=expected_goal_id,+ evidence=EvidenceInput(+ criterion_id=criterion_id,+ claim_id=str(kwargs.get("claim_id") or "").strip() or None,+ text=str(kwargs.get("text", "")),+ run_id=str(kwargs.get("run_id") or "").strip() or None,+ tool_call_id=str(kwargs.get("tool_call_id") or "").strip() or None,+ source_provider=str(kwargs.get("source_provider") or "agent_tool"),+ source_type=str(kwargs.get("source_type") or "tool_note"),+ source_uri=str(kwargs.get("source_uri") or "").strip() or None,+ symbol_universe=_coerce_string_list(kwargs.get("symbol_universe")),+ benchmark=_coerce_string_list(kwargs.get("benchmark")),+ timeframe=str(kwargs.get("timeframe") or "").strip() or None,+ method=str(kwargs.get("method") or "").strip() or None,+ artifact_path=str(kwargs.get("artifact_path") or "").strip() or None,+ artifact_hash=str(kwargs.get("artifact_hash") or "").strip() or None,+ data_as_of=str(kwargs.get("data_as_of") or "").strip() or None,+ confidence=str(kwargs.get("confidence") or "").strip() or None,+ caveat=str(kwargs.get("caveat") or "").strip() or None,+ ),+ )+ updated = self._store.get_goal_snapshot(goal_id)+ self._emit(+ "goal.evidence",+ {"evidence": record.__dict__, "goal_id": goal_id},+ )+ return json.dumps(+ {"status": "ok", "evidence": record.__dict__, "snapshot": updated},+ ensure_ascii=False,+ )+ except StaleGoalError as exc:+ return _json_error(str(exc), error_type="stale_goal")+ except (TypeError, ValueError) as exc:+ return _json_error(str(exc))diff --git a/agent/src/tools/path_utils.py b/agent/src/tools/path_utils.pyindex d3fa24d5c..d13e69fe9 100644--- a/agent/src/tools/path_utils.py+++ b/agent/src/tools/path_utils.py@@ -131,6 +131,25 @@ def _allowed_run_roots() -> list[Path]:return roots+def _import_candidate(p: str) -> Path:+ """Return the filesystem candidate for an import path.++ Browser uploads are exposed as ``uploads/<name>`` so the UI never needs+ a local absolute path. Resolve that handle back to the agent upload root+ before enforcing the allowlist.+ """+ candidate = Path(p).expanduser()+ if candidate.is_absolute():+ return candidate.resolve()++ parts = candidate.parts+ if parts and parts[0] == "uploads":+ return (_agent_root() / candidate).resolve()+ if len(parts) >= 2 and parts[0] == "agent" and parts[1] == "uploads":+ return (_agent_root() / Path(*parts[1:])).resolve()+ return (Path.cwd() / candidate).resolve()++def _safe_import_path(p: str, *, purpose: str) -> Path:"""Validate a user-supplied path against explicit import roots.@@ -146,7 +165,7 @@ def _safe_import_path(p: str, *, purpose: str) -> Path:import roots."""_rejects_unc(p)- resolved = Path(p).expanduser().resolve()+ resolved = _import_candidate(p)for root in _allowed_file_roots():if resolved.is_relative_to(root):@@ -214,3 +233,33 @@ def safe_run_dir(p: str) -> Path:f"run_dir {p!r} is outside allowed run roots. "f"Set {_ALLOWED_RUN_ROOTS_ENV} to add a run directory.")+++def safe_run_id(run_id: str) -> Path:+ """Resolve a bare run id to an existing allowed run directory.++ Args:+ run_id: Bare run directory name, not a path.++ Returns:+ Existing run directory under one of the allowed run roots.++ Raises:+ ValueError: If the run id is empty, path-shaped, or not found.+ """+ _rejects_unc(run_id)+ candidate = Path(run_id)+ if (+ not run_id.strip()+ or candidate.is_absolute()+ or len(candidate.parts) != 1+ or any(part in {"", ".", ".."} for part in candidate.parts)+ ):+ raise ValueError(f"run_id {run_id!r} must be a bare run directory name")++ for root in _allowed_run_roots():+ resolved = (root / candidate.name).resolve()+ if resolved.is_relative_to(root) and resolved.is_dir():+ return resolved++ raise ValueError(f"run_id {run_id!r} was not found under allowed run roots")diff --git a/agent/tests/test_cli_goal.py b/agent/tests/test_cli_goal.pynew file mode 100644index 000000000..107b5d9f6--- /dev/null+++ b/agent/tests/test_cli_goal.py@@ -0,0 +1,123 @@+"""CLI tests for the finance research goal slash command."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++from src.goal import GoalStore+++def test_goal_command_is_registered() -> None:+ """The interactive slash router exposes /goal."""+ from cli.commands.slash_router import find_exact, match_commands++ cmd = find_exact("goal")++ assert cmd is not None+ assert cmd.handler_module == "cli.commands.goal"+ assert "goal" in [item.name for item in match_commands("/go")]+++def test_goal_command_creates_goal(tmp_path: Path, monkeypatch) -> None:+ """A bare /goal <objective> starts a research goal for the current session."""+ from cli.commands import goal as goal_cmd++ store = GoalStore(tmp_path / "goals.db")+ monkeypatch.setattr(goal_cmd, "_goal_store", store)+ ctx = SimpleNamespace(session_id="session-1")++ rc = goal_cmd.run(+ ctx,+ "Evaluate",+ "NVDA",+ "momentum",+ "as",+ "a",+ "research-only",+ "thesis.",+ )++ current = store.get_current_snapshot("session-1")+ assert rc == 0+ assert current is not None+ assert current["goal"]["objective"] == "Evaluate NVDA momentum as a research-only thesis."+ assert len(current["criteria"]) >= 2+++def test_goal_command_appends_evidence_by_criterion_index(+ tmp_path: Path,+ monkeypatch,+) -> None:+ """Manual CLI evidence can target criteria by 1-based index."""+ from cli.commands import goal as goal_cmd++ store = GoalStore(tmp_path / "goals.db")+ monkeypatch.setattr(goal_cmd, "_goal_store", store)+ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Define thesis", "Check price action"],+ )+ ctx = SimpleNamespace(session_id="session-1")++ rc = goal_cmd.run(+ ctx,+ "evidence",+ "2",+ "NVDA",+ "outperformed",+ "QQQ",+ "over",+ "the",+ "last",+ "5",+ "sessions.",+ )++ snapshot = store.get_goal_snapshot(goal.goal_id)+ assert rc == 0+ assert snapshot is not None+ assert snapshot["evidence"][0]["criterion_id"] == snapshot["criteria"][1]["criterion_id"]+ assert snapshot["evidence"][0]["text"] == "NVDA outperformed QQQ over the last 5 sessions."+++def test_goal_command_rejects_live_trading_objective(tmp_path: Path, monkeypatch) -> None:+ """CLI /goal keeps the research-only boundary."""+ from cli.commands import goal as goal_cmd++ store = GoalStore(tmp_path / "goals.db")+ monkeypatch.setattr(goal_cmd, "_goal_store", store)+ ctx = SimpleNamespace(session_id="session-1")++ rc = goal_cmd.run(ctx, "buy", "1", "BTC", "now")++ assert rc == 1+ assert store.get_current_goal("session-1") is None+++def test_goal_status_without_session_does_not_create_session(monkeypatch) -> None:+ """Read-only /goal status should not create a new session."""+ from cli.commands import goal as goal_cmd++ def fail_create(*args, **kwargs): # noqa: ANN001+ raise AssertionError("status should not create a session")++ monkeypatch.delenv("VIBE_GOAL_SESSION_ID", raising=False)+ monkeypatch.setattr(goal_cmd, "_create_cli_session", fail_create)++ assert goal_cmd.run(SimpleNamespace(), "status") == 0+++def test_goal_start_persists_session_id_on_plain_context(tmp_path: Path, monkeypatch) -> None:+ """A ctx without session_id still remembers the session after /goal start."""+ from cli.commands import goal as goal_cmd++ store = GoalStore(tmp_path / "goals.db")+ monkeypatch.setattr(goal_cmd, "_goal_store", store)+ monkeypatch.setattr(goal_cmd, "_create_cli_session", lambda ctx, title: setattr(ctx, "session_id", "session-1") or "session-1")+ ctx = SimpleNamespace()++ assert goal_cmd.run(ctx, "Evaluate", "NVDA", "momentum.") == 0+ assert ctx.session_id == "session-1"+ assert goal_cmd.run(ctx, "status") == 0diff --git a/agent/tests/test_goal_store.py b/agent/tests/test_goal_store.pynew file mode 100644index 000000000..5e0e98b9d--- /dev/null+++ b/agent/tests/test_goal_store.py@@ -0,0 +1,543 @@+"""Tests for the finance research goal store MVP."""++from __future__ import annotations++import hashlib+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import pytest++from src.goal import (+ AuditRow,+ EvidenceInput,+ GoalStatus,+ GoalStore,+ RiskTier,+ StaleGoalError,+)+++def _store(tmp_path: Path) -> GoalStore:+ return GoalStore(tmp_path / "goals.db")+++def _sha256(path: Path) -> str:+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def test_replace_goal_supersedes_current_goal(tmp_path: Path) -> None:+ store = _store(tmp_path)++ first = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum as a research-only thesis.",+ criteria=["Define thesis", "Check price action"],+ )+ second = store.replace_goal(+ session_id="session-1",+ objective="Evaluate BTC ETF flow divergence as a research-only thesis.",+ criteria=["Define thesis", "Check ETF flow"],+ )++ current = store.get_current_goal("session-1")+ first_fresh = store.get_goal(first.goal_id)++ assert current is not None+ assert current.goal_id == second.goal_id+ assert current.status is GoalStatus.ACTIVE+ assert first_fresh is not None+ assert first_fresh.status is GoalStatus.SUPERSEDED+++def test_replace_goal_creates_initial_thesis_claim(tmp_path: Path) -> None:+ store = _store(tmp_path)++ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum as a research-only thesis.",+ criteria=["Define thesis", "Check price action"],+ )++ claims = store.list_claims(goal.goal_id)++ assert len(claims) == 1+ assert claims[0].claim_type == "thesis"+ assert claims[0].text == goal.objective+ assert claims[0].status == "active"+++def test_replace_goal_rejects_live_execution_objective(tmp_path: Path) -> None:+ store = _store(tmp_path)++ with pytest.raises(ValueError, match="live trading"):+ store.replace_goal(+ session_id="session-1",+ objective="Place a live BTC order now.",+ criteria=["Execute order"],+ )+++def test_replace_goal_rejects_live_execution_risk_tier(tmp_path: Path) -> None:+ store = _store(tmp_path)++ with pytest.raises(ValueError, match="live trading"):+ store.replace_goal(+ session_id="session-1",+ objective="Evaluate BTC momentum as research only.",+ criteria=["Check price action"],+ risk_tier=RiskTier.LIVE_TRADING_OR_EXECUTION,+ )+++def test_list_criteria_preserves_numeric_protocol_order(tmp_path: Path) -> None:+ store = _store(tmp_path)+ criteria = [f"Criterion {index}" for index in range(1, 13)]++ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum as a research-only thesis.",+ criteria=criteria,+ )++ assert [item.text for item in store.list_criteria(goal.goal_id)] == criteria+++def test_blank_session_id_is_rejected(tmp_path: Path) -> None:+ store = _store(tmp_path)++ with pytest.raises(ValueError, match="session_id"):+ store.replace_goal(+ session_id=" ",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )+++def test_replace_goal_rejects_non_positive_budgets(tmp_path: Path) -> None:+ store = _store(tmp_path)++ with pytest.raises(ValueError, match="token_budget"):+ store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ token_budget=0,+ )+++def test_append_evidence_rejects_stale_expected_goal_id(tmp_path: Path) -> None:+ store = _store(tmp_path)+ old_goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )+ new_goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate TSLA momentum.",+ criteria=["Check price action"],+ )+ criterion = store.list_criteria(new_goal.goal_id)[0]++ with pytest.raises(StaleGoalError):+ store.append_evidence(+ session_id="session-1",+ goal_id=new_goal.goal_id,+ expected_goal_id=old_goal.goal_id,+ evidence=EvidenceInput(+ criterion_id=criterion.criterion_id,+ text="TSLA outperformed QQQ over the sample window.",+ source_provider="yfinance",+ data_as_of="2026-05-23T16:00:00-04:00",+ tool_call_id="tool_123",+ ),+ )+++def test_cross_connection_stale_goal_rejected(tmp_path: Path) -> None:+ db_path = tmp_path / "goals.db"+ first_store = GoalStore(db_path)+ second_store = GoalStore(db_path)+ old_goal = first_store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )+ second_store.replace_goal(+ session_id="session-1",+ objective="Evaluate TSLA momentum.",+ criteria=["Check price action"],+ )+ old_criterion = first_store.list_criteria(old_goal.goal_id)[0]++ with pytest.raises(StaleGoalError):+ first_store.append_evidence(+ session_id="session-1",+ goal_id=old_goal.goal_id,+ expected_goal_id=old_goal.goal_id,+ evidence=EvidenceInput(+ criterion_id=old_criterion.criterion_id,+ text="This should not write to a superseded goal.",+ ),+ )+++def test_completion_requires_verified_evidence_id(tmp_path: Path) -> None:+ store = _store(tmp_path)+ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )+ criterion = store.list_criteria(goal.goal_id)[0]++ with pytest.raises(ValueError, match="verified evidence"):+ store.update_status(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ status=GoalStatus.COMPLETE,+ audit=[+ AuditRow(+ criterion_id=criterion.criterion_id,+ result="satisfied",+ evidence_ids=[],+ notes="Model says price action was checked.",+ )+ ],+ )+++def test_completion_rejects_caveated_result_without_verified_evidence(tmp_path: Path) -> None:+ store = _store(tmp_path)+ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )+ criterion = store.list_criteria(goal.goal_id)[0]++ with pytest.raises(ValueError, match="verified evidence"):+ store.update_status(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ status=GoalStatus.COMPLETE,+ audit=[+ AuditRow(+ criterion_id=criterion.criterion_id,+ result="satisfied_with_caveat",+ evidence_ids=[],+ notes="Caveated but still needs evidence.",+ )+ ],+ )+++def test_completion_rejects_not_applicable_without_acceptance_notes(tmp_path: Path) -> None:+ store = _store(tmp_path)+ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )+ criterion = store.list_criteria(goal.goal_id)[0]++ with pytest.raises(ValueError, match="acceptance notes"):+ store.update_status(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ status=GoalStatus.COMPLETE,+ audit=[+ AuditRow(+ criterion_id=criterion.criterion_id,+ result="not_applicable_user_accepted",+ evidence_ids=[],+ notes="",+ )+ ],+ )+++def test_tool_call_id_alone_does_not_mark_evidence_verified(tmp_path: Path) -> None:+ store = _store(tmp_path)+ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )+ criterion = store.list_criteria(goal.goal_id)[0]++ evidence = store.append_evidence(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ evidence=EvidenceInput(+ criterion_id=criterion.criterion_id,+ text="Model says a tool was called, but no run/artifact exists.",+ tool_call_id="tool_123",+ ),+ )++ assert evidence.verification_status == "unverified"+++def test_complete_goal_with_verified_evidence(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ store = _store(tmp_path)+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", str(tmp_path))+ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )+ criterion = store.list_criteria(goal.goal_id)[0]+ artifact = tmp_path / "nvda_momentum.txt"+ artifact.write_text("NVDA outperformed QQQ over the last 5 sessions.", encoding="utf-8")+ evidence = store.append_evidence(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ evidence=EvidenceInput(+ criterion_id=criterion.criterion_id,+ text="NVDA outperformed QQQ over the last 5 sessions.",+ source_provider="yfinance",+ data_as_of="2026-05-23T16:00:00-04:00",+ artifact_path=str(artifact),+ artifact_hash=_sha256(artifact),+ symbol_universe=["NVDA"],+ benchmark=["QQQ"],+ ),+ )++ completed = store.update_status(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ status=GoalStatus.COMPLETE,+ audit=[+ AuditRow(+ criterion_id=criterion.criterion_id,+ result="satisfied",+ evidence_ids=[evidence.evidence_id],+ notes="Price action evidence is linked to a tool result.",+ )+ ],+ recap="Research-only evidence check completed.",+ )++ assert completed.status is GoalStatus.COMPLETE+ assert completed.recap == "Research-only evidence check completed."+ assert store.list_criteria(goal.goal_id)[0].status == "satisfied"+++def test_artifact_evidence_requires_allowed_path_and_hash(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ store = _store(tmp_path)+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", str(tmp_path))+ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )+ criterion = store.list_criteria(goal.goal_id)[0]+ artifact = tmp_path / "nvda_momentum.txt"+ artifact.write_text("NVDA outperformed QQQ.", encoding="utf-8")++ missing_hash = store.append_evidence(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ evidence=EvidenceInput(+ criterion_id=criterion.criterion_id,+ text="Artifact without hash should not verify.",+ artifact_path=str(artifact),+ ),+ )+ traversal = store.append_evidence(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ evidence=EvidenceInput(+ criterion_id=criterion.criterion_id,+ text="Traversal handle should not verify.",+ artifact_path="uploads/../api_server.py",+ artifact_hash="sha256:deadbeef",+ ),+ )++ assert missing_hash.verification_status == "unverified"+ assert traversal.verification_status == "unverified"+++def test_delete_session_goals_removes_ledger(tmp_path: Path) -> None:+ store = _store(tmp_path)+ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )+ criterion = store.list_criteria(goal.goal_id)[0]+ store.append_evidence(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ evidence=EvidenceInput(+ criterion_id=criterion.criterion_id,+ text="Evidence to remove with the session.",+ ),+ )++ assert store.delete_session_goals("session-1") == 1+ assert store.get_current_snapshot("session-1") is None+ assert store.get_goal_snapshot(goal.goal_id) is None+++def test_goal_snapshot_includes_claims_criteria_and_evidence(tmp_path: Path) -> None:+ store = _store(tmp_path)+ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )+ criterion = store.list_criteria(goal.goal_id)[0]+ evidence = store.append_evidence(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ evidence=EvidenceInput(+ criterion_id=criterion.criterion_id,+ text="NVDA outperformed QQQ over the last 5 sessions.",+ tool_call_id="tool_123",+ data_as_of="2026-05-23T16:00:00-04:00",+ ),+ )++ snapshot = store.get_current_snapshot("session-1")++ assert snapshot is not None+ assert snapshot["goal"]["goal_id"] == goal.goal_id+ assert snapshot["claims"][0]["claim_type"] == "thesis"+ assert snapshot["criteria"][0]["criterion_id"] == criterion.criterion_id+ assert snapshot["evidence"][0]["evidence_id"] == evidence.evidence_id+ assert snapshot["evidence_count"] == 1+++def test_goal_snapshot_caps_evidence_but_reports_total_count(tmp_path: Path) -> None:+ store = _store(tmp_path)+ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )+ criterion = store.list_criteria(goal.goal_id)[0]+ for index in range(55):+ store.append_evidence(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ evidence=EvidenceInput(+ criterion_id=criterion.criterion_id,+ text=f"Evidence {index}",+ ),+ )++ snapshot = store.get_goal_snapshot(goal.goal_id)++ assert snapshot is not None+ assert snapshot["evidence_count"] == 55+ assert len(snapshot["evidence"]) == 50+++def test_append_evidence_is_safe_from_parallel_cli_or_api_calls(tmp_path: Path) -> None:+ store = _store(tmp_path)+ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )+ criterion = store.list_criteria(goal.goal_id)[0]++ def append_note(index: int) -> str:+ return store.append_evidence(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ evidence=EvidenceInput(+ criterion_id=criterion.criterion_id,+ text=f"Parallel evidence note {index}",+ tool_call_id=f"tool_{index}",+ ),+ ).evidence_id++ with ThreadPoolExecutor(max_workers=8) as pool:+ evidence_ids = list(pool.map(append_note, range(20)))++ snapshot = store.get_goal_snapshot(goal.goal_id)+ assert snapshot is not None+ assert len(evidence_ids) == 20+ assert len(set(evidence_ids)) == 20+ assert len(snapshot["evidence"]) == 20+++def test_account_usage_marks_goal_budget_limited(tmp_path: Path) -> None:+ store = _store(tmp_path)+ goal = store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ token_budget=100,+ turn_budget=3,+ )++ active = store.account_usage(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ token_delta=40,+ time_delta_seconds=10,+ turn_delta=1,+ )+ limited = store.account_usage(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ token_delta=60,+ time_delta_seconds=10,+ turn_delta=1,+ )++ assert active.status is GoalStatus.ACTIVE+ assert active.tokens_used == 40+ assert limited.status is GoalStatus.BUDGET_LIMITED+ assert limited.tokens_used == 100+++def test_account_usage_is_serialized_across_connections(tmp_path: Path) -> None:+ db_path = tmp_path / "goals.db"+ first_store = GoalStore(db_path)+ second_store = GoalStore(db_path)+ goal = first_store.replace_goal(+ session_id="session-1",+ objective="Evaluate NVDA momentum.",+ criteria=["Check price action"],+ )++ def add_usage(index: int) -> None:+ store = first_store if index % 2 == 0 else second_store+ store.account_usage(+ session_id="session-1",+ goal_id=goal.goal_id,+ expected_goal_id=goal.goal_id,+ token_delta=1,+ )++ with ThreadPoolExecutor(max_workers=8) as pool:+ list(pool.map(add_usage, range(40)))++ current = first_store.get_goal(goal.goal_id)+ assert current is not None+ assert current.tokens_used == 40diff --git a/agent/tests/test_goal_tools.py b/agent/tests/test_goal_tools.pynew file mode 100644index 000000000..86220aace--- /dev/null+++ b/agent/tests/test_goal_tools.py@@ -0,0 +1,140 @@+"""Tests for local agent research goal tools."""++from __future__ import annotations++import json+from pathlib import Path++from src.agent.skills import SkillsLoader+from src.goal import GoalStore+from src.tools.goal_tool import (+ AddGoalEvidenceTool,+ GetResearchGoalTool,+ StartResearchGoalTool,+)+++def test_local_goal_tools_use_injected_session(tmp_path: Path) -> None:+ """Agent tools can start, inspect, and mutate the current session goal."""+ store = GoalStore(tmp_path / "goals.db")+ start = StartResearchGoalTool(default_session_id="session-1", store=store)+ get = GetResearchGoalTool(default_session_id="session-1", store=store)+ add = AddGoalEvidenceTool(default_session_id="session-1", store=store)++ created = json.loads(+ start.execute(+ objective="Evaluate NVDA momentum as a research-only thesis.",+ criteria=["Define thesis", "Check price action"],+ )+ )++ assert created["status"] == "ok"+ assert created["snapshot"]["goal"]["session_id"] == "session-1"++ fetched = json.loads(get.execute())+ assert fetched["status"] == "ok"+ assert fetched["snapshot"]["goal"]["goal_id"] == created["snapshot"]["goal"]["goal_id"]++ evidence = json.loads(+ add.execute(+ criterion_index=2,+ text="NVDA outperformed QQQ over the last 5 sessions.",+ source_provider="pytest",+ source_type="manual_note",+ )+ )++ assert evidence["status"] == "ok"+ assert evidence["snapshot"]["evidence_count"] == 1+ assert (+ evidence["evidence"]["criterion_id"]+ == created["snapshot"]["criteria"][1]["criterion_id"]+ )+++def test_goal_tool_without_session_returns_validation_error(tmp_path: Path) -> None:+ """Goal tools fail cleanly when no session id was injected or supplied."""+ store = GoalStore(tmp_path / "goals.db")+ result = json.loads(GetResearchGoalTool(store=store).execute())++ assert result["status"] == "error"+ assert result["error_type"] == "validation"+ assert "session_id" in result["error"]+++def test_goal_tool_rejects_live_trading_objective(tmp_path: Path) -> None:+ """Local agent tools keep the research-only boundary."""+ store = GoalStore(tmp_path / "goals.db")+ tool = StartResearchGoalTool(default_session_id="session-1", store=store)++ result = json.loads(tool.execute(objective="Buy 1 BTC now."))++ assert result["status"] == "error"+ assert result["error_type"] == "validation"+ assert "live trading" in result["error"]+++def test_registry_injects_session_id_into_goal_tools() -> None:+ """SessionService can build a registry with session-scoped goal tools."""+ from src.tools import build_registry++ registry = build_registry(session_id="session-xyz")+ tool = registry.get("start_research_goal")++ assert tool is not None+ assert getattr(tool, "_default_session_id") == "session-xyz"+++def test_goal_tools_emit_mutation_events(tmp_path: Path) -> None:+ """Goal tools notify the host when they mutate session-scoped goal state."""+ store = GoalStore(tmp_path / "goals.db")+ events: list[tuple[str, dict]] = []++ def emit(event_type: str, data: dict) -> None:+ events.append((event_type, data))++ start = StartResearchGoalTool(default_session_id="session-1", store=store, event_callback=emit)+ add = AddGoalEvidenceTool(default_session_id="session-1", store=store, event_callback=emit)++ created = json.loads(+ start.execute(+ objective="Evaluate NVDA momentum as a research-only thesis.",+ criteria=["Define thesis", "Check price action"],+ )+ )+ evidence = json.loads(+ add.execute(+ goal_id=created["snapshot"]["goal"]["goal_id"],+ criterion_index=1,+ text="Evidence from a local tool call.",+ )+ )++ assert created["status"] == "ok"+ assert evidence["status"] == "ok"+ assert [item[0] for item in events] == ["goal.created", "goal.evidence"]+ assert events[0][1]["goal"]["session_id"] == "session-1"+ assert events[1][1]["goal_id"] == created["snapshot"]["goal"]["goal_id"]+++def test_registry_injects_goal_event_callback() -> None:+ """SessionService can build goal tools that emit through the event bus."""+ from src.tools import build_registry++ events: list[tuple[str, dict]] = []+ registry = build_registry(+ session_id="session-xyz",+ event_callback=lambda event_type, data: events.append((event_type, data)),+ )+ tool = registry.get("start_research_goal")++ assert tool is not None+ assert getattr(tool, "_event_callback") is not None+++def test_research_goal_skill_is_bundled() -> None:+ """The agent can load workflow guidance for self-managed goals."""+ content = SkillsLoader().get_content("research-goal")++ assert "start_research_goal" in content+ assert "add_goal_evidence" in contentdiff --git a/agent/tests/test_mcp_regression.py b/agent/tests/test_mcp_regression.pyindex d5d809411..00070838c 100644--- a/agent/tests/test_mcp_regression.py+++ b/agent/tests/test_mcp_regression.py@@ -160,6 +160,9 @@ def test_mcp_server_exposes_well_known_tool_names() -> None:"read_file","list_swarm_presets","run_swarm",+ "start_research_goal",+ "get_research_goal",+ "add_goal_evidence",}missing = expected - registeredassert not missing, (diff --git a/agent/tests/test_mcp_server_smoke.py b/agent/tests/test_mcp_server_smoke.pyindex 438aece85..c2bb19fd3 100644--- a/agent/tests/test_mcp_server_smoke.py+++ b/agent/tests/test_mcp_server_smoke.py@@ -44,7 +44,14 @@ CALL_TIMEOUT = 15.0# assert ``>= 20`` so unrelated tool additions / removals don't break the# test, but a regression that drops half the catalogue still fires.EXPECTED_MIN_TOOL_COUNT = 20-REQUIRED_TOOL_NAMES = {"analyze_options", "get_market_data", "list_skills"}+REQUIRED_TOOL_NAMES = {+ "analyze_options",+ "get_market_data",+ "list_skills",+ "start_research_goal",+ "get_research_goal",+ "add_goal_evidence",+}def _reader(stream, q: Queue) -> None:diff --git a/agent/tests/test_path_safety.py b/agent/tests/test_path_safety.pyindex a6cdd42e3..01bc4f4c4 100644--- a/agent/tests/test_path_safety.py+++ b/agent/tests/test_path_safety.py@@ -6,7 +6,7 @@ from pathlib import Pathimport pytest-from src.tools.path_utils import safe_path, safe_run_dir, safe_user_path+from src.tools.path_utils import safe_document_path, safe_path, safe_run_dir, safe_run_id, safe_user_path# ---------------------------------------------------------------------------@@ -104,6 +104,17 @@ class TestSafeUserPath:safe_user_path("//evil-server/share/passwd.csv")+class TestSafeDocumentPath:+ def test_upload_handle_resolves_to_agent_uploads(self) -> None:+ result = safe_document_path("uploads/local.csv")++ assert result == (Path(__file__).resolve().parents[1] / "uploads" / "local.csv").resolve()++ def test_upload_handle_traversal_is_rejected(self) -> None:+ with pytest.raises(ValueError, match="outside allowed document roots"):+ safe_document_path("uploads/../api_server.py")++# ---------------------------------------------------------------------------# safe_run_dir — tool/backtest run roots# ---------------------------------------------------------------------------@@ -134,3 +145,26 @@ class TestSafeRunDir:result = safe_run_dir(str(agent_runs))assert result == agent_runs.resolve()+++class TestSafeRunId:+ def test_configured_run_id_accepted(self, tmp_path: Path, monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))+ run_dir = tmp_path / "run_123"+ run_dir.mkdir()++ result = safe_run_id("run_123")++ assert result == run_dir.resolve()++ def test_path_shaped_run_id_rejected(self, tmp_path: Path, monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))++ with pytest.raises(ValueError, match="bare run directory name"):+ safe_run_id("../api_server.py")++ def test_missing_run_id_rejected(self, tmp_path: Path, monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))++ with pytest.raises(ValueError, match="was not found"):+ safe_run_id("missing_run")diff --git a/agent/tests/test_security_auth_api.py b/agent/tests/test_security_auth_api.pyindex 1bd633b6d..b5e86e7bd 100644--- a/agent/tests/test_security_auth_api.py+++ b/agent/tests/test_security_auth_api.py@@ -37,6 +37,28 @@ def test_remote_write_requires_api_key_when_key_unset() -> None:assert "API_AUTH_KEY" in response.json()["detail"]+def test_remote_goal_endpoints_require_api_key_when_key_unset() -> None:+ client = _remote_client()++ cases = [+ ("post", "/sessions/abcdef012345/goal", {"objective": "Evaluate NVDA", "criteria": ["Define thesis"]}),+ ("get", "/sessions/abcdef012345/goal", None),+ (+ "post",+ "/sessions/abcdef012345/goal/evidence",+ {+ "goal_id": "goal_123",+ "expected_goal_id": "goal_123",+ "text": "Evidence",+ },+ ),+ ]+ for method, path, body in cases:+ kwargs = {"json": body} if body is not None else {}+ response = getattr(client, method)(path, **kwargs)+ assert response.status_code == 403, f"{method.upper()} {path}"++def test_local_dev_write_allowed_when_key_unset() -> None:response = _local_client().post("/sessions", json={})@@ -84,6 +106,7 @@ def test_configured_api_key_required_for_sensitive_reads(for path in ["/runs","/sessions",+ "/sessions/abcdef012345/goal","/swarm/runs",]:response = client.get(path)@@ -253,6 +276,13 @@ def test_session_endpoints_reject_traversal_session_id() -> None:("post", "/sessions/foo.bar/messages", {"content": "x"}),("get", "/sessions/foo.bar/messages", None),("post", "/sessions/foo.bar/cancel", None),+ ("post", "/sessions/foo.bar/goal", {"objective": "x", "criteria": ["y"]}),+ ("get", "/sessions/foo.bar/goal", None),+ (+ "post",+ "/sessions/foo.bar/goal/evidence",+ {"goal_id": "goal_123", "expected_goal_id": "goal_123", "text": "x"},+ ),]for method, path, body in cases:kwargs = {"json": body} if body is not None else {}diff --git a/agent/tests/test_session_events.py b/agent/tests/test_session_events.pynew file mode 100644index 000000000..26895fd3a--- /dev/null+++ b/agent/tests/test_session_events.py@@ -0,0 +1,29 @@+"""Session SSE event buffer recovery tests."""++from __future__ import annotations++from src.session.events import EventBus+++def test_first_connect_does_not_replay_completed_history_by_default() -> None:+ bus = EventBus()+ bus.emit("s1", "tool_call", {"tool": "load_skill"})++ assert bus.replay("s1") == []+++def test_active_run_first_connect_can_replay_entire_buffer() -> None:+ bus = EventBus()+ first = bus.emit("s1", "tool_call", {"tool": "load_skill"})+ second = bus.emit("s1", "tool_result", {"tool": "load_skill", "status": "ok"})++ assert bus.replay("s1", replay_all=True) == [first, second]+++def test_last_event_id_replay_still_returns_only_later_events() -> None:+ bus = EventBus()+ first = bus.emit("s1", "tool_call", {"tool": "load_skill"})+ second = bus.emit("s1", "tool_result", {"tool": "load_skill", "status": "ok"})+ third = bus.emit("s1", "text_delta", {"delta": "done"})++ assert bus.replay("s1", last_event_id=first.event_id, replay_all=True) == [second, third]diff --git a/agent/tests/test_upload_api.py b/agent/tests/test_upload_api.pyindex 993a83733..196b39664 100644--- a/agent/tests/test_upload_api.py+++ b/agent/tests/test_upload_api.py@@ -39,8 +39,11 @@ def test_upload_under_limit_succeeds(client: TestClient, tmp_path: Path) -> Nonebody = response.json()assert body["status"] == "ok"assert body["filename"] == "note.txt"+ assert body["file_path"].startswith("uploads/")+ assert not Path(body["file_path"]).is_absolute()+ assert str(tmp_path) not in response.text- saved = Path(body["file_path"])+ saved = _existing_uploads(tmp_path)[0]assert saved.exists()assert saved.read_bytes() == payloadassert saved.parent == tmp_path.resolve()@@ -79,3 +82,22 @@ def test_upload_blocked_extension_returns_400(client: TestClient, tmp_path: Pathassert _existing_uploads(tmp_path) == []+def test_upload_storage_error_does_not_expose_server_path(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ blocked_path = tmp_path / "uploads-as-file"+ blocked_path.write_text("not a directory", encoding="utf-8")+ monkeypatch.setattr(api_server, "UPLOADS_DIR", blocked_path)+ monkeypatch.setattr(api_server, "MAX_UPLOAD_SIZE", 4 * 1024)+ monkeypatch.setattr(api_server, "_UPLOAD_CHUNK_SIZE", 1024)+ client = TestClient(api_server.app)++ response = client.post(+ "/upload",+ files={"file": ("note.txt", b"x", "text/plain")},+ )++ assert response.status_code == 500+ assert "Upload failed while storing the file" in response.json()["detail"]+ assert str(tmp_path) not in response.textdiff --git a/frontend/src/components/chat/GoalDrawer.tsx b/frontend/src/components/chat/GoalDrawer.tsxnew file mode 100644index 000000000..e130da106--- /dev/null+++ b/frontend/src/components/chat/GoalDrawer.tsx@@ -0,0 +1,292 @@+import { useEffect, useMemo, useState } from "react";+import {+ AlertTriangle,+ Check,+ Circle,+ Loader2,+ Plus,+ RefreshCcw,+ Target,+ X,+} from "lucide-react";+import type { GoalCriterion, GoalSnapshot } from "@/lib/api";++interface GoalDrawerProps {+ open: boolean;+ snapshot: GoalSnapshot | null;+ loading: boolean;+ error: string | null;+ onClose: () => void;+ onRefresh: () => void;+ onStart: (objective: string) => Promise<void>;+ onAddEvidence: (criterionId: string, text: string) => Promise<void>;+}++function isCriterionStatusMet(status: string): boolean {+ return !["", "pending", "open", "unsatisfied"].includes(status.toLowerCase());+}++function criterionEvidenceCount(snapshot: GoalSnapshot | null, criterionId: string): number {+ if (!snapshot) return 0;+ return snapshot.evidence.filter((item) => item.criterion_id === criterionId).length;+}++function statusLabel(status: string): string {+ return status.replace(/_/g, " ");+}++function criterionIndexLabel(criterion: GoalCriterion, index: number): string {+ const step = criterion.protocol_step?.match(/step_(\d+)/)?.[1];+ return step || String(index + 1);+}++export function getGoalProgress(snapshot: GoalSnapshot | null): { met: number; total: number; label: string } {+ const total = snapshot?.criteria.length ?? 0;+ const met = snapshot?.criteria.filter((item) => isCriterionStatusMet(item.status)).length ?? 0;+ return {+ met,+ total,+ label: total > 0 ? `${met}/${total}` : "",+ };+}++export function GoalDrawer({+ open,+ snapshot,+ loading,+ error,+ onClose,+ onRefresh,+ onStart,+ onAddEvidence,+}: GoalDrawerProps) {+ const [objective, setObjective] = useState("");+ const [evidenceText, setEvidenceText] = useState("");+ const [criterionId, setCriterionId] = useState("");+ const [submitting, setSubmitting] = useState<"start" | "evidence" | null>(null);++ const criteria = useMemo(() => snapshot?.criteria ?? [], [snapshot]);+ const progress = useMemo(() => getGoalProgress(snapshot), [snapshot]);++ useEffect(() => {+ if (criteria.length === 0 && criterionId) {+ setCriterionId("");+ return;+ }+ if (!criterionId && criteria.length > 0) {+ setCriterionId(criteria[0].criterion_id);+ }+ if (criterionId && criteria.length > 0 && !criteria.some((item) => item.criterion_id === criterionId)) {+ setCriterionId(criteria[0].criterion_id);+ }+ }, [criterionId, criteria]);++ if (!open) return null;++ const handleStart = async () => {+ const trimmed = objective.trim();+ if (!trimmed) return;+ setSubmitting("start");+ try {+ await onStart(trimmed);+ setObjective("");+ } finally {+ setSubmitting(null);+ }+ };++ const handleAddEvidence = async () => {+ const trimmed = evidenceText.trim();+ if (!criterionId || !trimmed) return;+ setSubmitting("evidence");+ try {+ await onAddEvidence(criterionId, trimmed);+ setEvidenceText("");+ } finally {+ setSubmitting(null);+ }+ };++ return (+ <aside+ aria-label="Goal panel"+ className="fixed right-6 top-20 z-40 flex max-h-[calc(100vh-7.5rem)] w-[min(390px,calc(100vw-2rem))] flex-col overflow-hidden rounded-xl border bg-background/95 shadow-2xl backdrop-blur-xl"+ >+ <div className="border-b px-4 py-3">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <Target className="h-4 w-4 text-primary" aria-hidden="true" />+ <h2 className="text-sm font-semibold text-foreground">Research Goal</h2>+ </div>+ {snapshot ? (+ <p className="mt-2 line-clamp-3 text-xs leading-relaxed text-muted-foreground">+ {snapshot.goal.objective}+ </p>+ ) : (+ <p className="mt-2 text-xs leading-relaxed text-muted-foreground">+ Attach a research goal to keep this session evidence-driven.+ </p>+ )}+ </div>+ <button+ type="button"+ onClick={onClose}+ className="rounded-md p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ aria-label="Close goal panel"+ >+ <X className="h-4 w-4" aria-hidden="true" />+ </button>+ </div>++ <div className="mt-3 flex items-center justify-between gap-3">+ {snapshot ? (+ <span className="inline-flex h-6 items-center gap-1.5 rounded-full border border-emerald-500/30 bg-emerald-500/10 px-2.5 text-[11px] font-medium capitalize text-emerald-600 dark:text-emerald-400">+ <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" aria-hidden="true" />+ {statusLabel(snapshot.goal.status)}+ </span>+ ) : (+ <span className="inline-flex h-6 items-center gap-1.5 rounded-full border bg-muted/50 px-2.5 text-[11px] font-medium text-muted-foreground">+ <Circle className="h-2.5 w-2.5" aria-hidden="true" />+ No goal+ </span>+ )}+ <button+ type="button"+ onClick={onRefresh}+ className="inline-flex h-7 items-center gap-1.5 rounded-md border bg-background px-2 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50"+ disabled={loading}+ >+ {loading ? (+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden="true" />+ ) : (+ <RefreshCcw className="h-3 w-3" aria-hidden="true" />+ )}+ Refresh+ </button>+ </div>+ </div>++ <div className="grid gap-4 overflow-auto p-4">+ {error && (+ <div className="flex gap-2 rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-xs leading-relaxed text-destructive">+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden="true" />+ <span>{error}</span>+ </div>+ )}++ {snapshot && (+ <section className="grid gap-2">+ <div className="flex items-center justify-between text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">+ <span>Acceptance Criteria</span>+ <span className="font-mono tracking-normal text-foreground">{progress.label} met</span>+ </div>+ <div className="grid gap-2">+ {criteria.map((criterion, index) => {+ const count = criterionEvidenceCount(snapshot, criterion.criterion_id);+ const met = isCriterionStatusMet(criterion.status);+ return (+ <div+ key={criterion.criterion_id}+ className="grid grid-cols-[1.25rem_minmax(0,1fr)_auto] items-start gap-2 rounded-lg border bg-muted/20 p-2.5"+ >+ <span+ className={[+ "mt-0.5 inline-flex h-5 w-5 items-center justify-center rounded-full text-[10px]",+ met ? "bg-emerald-500/15 text-emerald-600 dark:text-emerald-400" : "bg-muted text-muted-foreground",+ ].join(" ")}+ >+ {met ? <Check className="h-3 w-3" aria-hidden="true" /> : criterionIndexLabel(criterion, index)}+ </span>+ <div className="min-w-0">+ <div className="text-xs font-medium leading-snug text-foreground">+ {criterion.text}+ </div>+ <div className="mt-1 text-[11px] text-muted-foreground">+ {statusLabel(criterion.status)}+ </div>+ </div>+ <span className="rounded-full border px-2 py-0.5 text-[10px] text-muted-foreground">+ {count} ev+ </span>+ </div>+ );+ })}+ </div>+ </section>+ )}++ {snapshot && criteria.length > 0 && (+ <section className="grid gap-2">+ <div className="flex items-center justify-between text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">+ <span>Add Evidence</span>+ <span className="font-mono tracking-normal text-foreground">{snapshot.evidence_count} total</span>+ </div>+ <div className="grid gap-2 rounded-lg border border-primary/25 bg-primary/5 p-2.5">+ <select+ value={criterionId}+ onChange={(event) => setCriterionId(event.target.value)}+ className="h-8 rounded-md border bg-background px-2 text-xs outline-none focus:ring-2 focus:ring-primary/25"+ aria-label="Evidence criterion"+ >+ {criteria.map((criterion, index) => (+ <option key={criterion.criterion_id} value={criterion.criterion_id}>+ {criterionIndexLabel(criterion, index)}. {criterion.text}+ </option>+ ))}+ </select>+ <textarea+ value={evidenceText}+ onChange={(event) => setEvidenceText(event.target.value)}+ aria-label="Evidence note"+ placeholder="Paste a concise evidence note or artifact summary."+ className="min-h-20 resize-y rounded-md border bg-background px-3 py-2 text-xs leading-relaxed outline-none placeholder:text-muted-foreground focus:ring-2 focus:ring-primary/25"+ />+ <button+ type="button"+ onClick={handleAddEvidence}+ disabled={!evidenceText.trim() || !criterionId || submitting === "evidence"}+ className="inline-flex items-center gap-1.5 justify-self-end rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground transition-opacity hover:opacity-90 disabled:opacity-40"+ >+ {submitting === "evidence" ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />+ ) : (+ <Plus className="h-3.5 w-3.5" aria-hidden="true" />+ )}+ Attach evidence+ </button>+ </div>+ </section>+ )}++ <section className="grid gap-2">+ <div className="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">+ Start New Goal+ </div>+ <div className="grid gap-2">+ <textarea+ value={objective}+ onChange={(event) => setObjective(event.target.value)}+ aria-label="Research goal"+ placeholder="Research whether SOL relative strength is beta or idiosyncratic flow."+ className="min-h-20 resize-y rounded-md border bg-background px-3 py-2 text-xs leading-relaxed outline-none placeholder:text-muted-foreground focus:ring-2 focus:ring-primary/25"+ />+ <button+ type="button"+ onClick={handleStart}+ disabled={!objective.trim() || submitting === "start"}+ className="inline-flex items-center gap-1.5 justify-self-end rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground transition-opacity hover:opacity-90 disabled:opacity-40"+ >+ {submitting === "start" ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />+ ) : (+ <Target className="h-3.5 w-3.5" aria-hidden="true" />+ )}+ Start goal+ </button>+ </div>+ </section>+ </div>+ </aside>+ );+}diff --git a/frontend/src/components/chat/MetricsCard.tsx b/frontend/src/components/chat/MetricsCard.tsxindex 573ff15ee..07d68875a 100644--- a/frontend/src/components/chat/MetricsCard.tsx+++ b/frontend/src/components/chat/MetricsCard.tsx@@ -1,6 +1,5 @@import { memo } from "react";import { cn } from "@/lib/utils";-import { useI18n } from "@/lib/i18n";import { getMetricLabel, DISPLAY_ORDER, formatMetricVal, metricSentiment } from "@/lib/formatters";const SENTIMENT = {@@ -15,7 +14,6 @@ interface Props {}export const MetricsCard = memo(function MetricsCard({ metrics, compact = false }: Props) {- const { t } = useI18n();const entries = DISPLAY_ORDER.filter((k) => metrics[k] != null).map((k) => ({ k, v: metrics[k] }));@@ -32,7 +30,7 @@ export const MetricsCard = memo(function MetricsCard({ metrics, compact = false{shown.map(({ k, v }) => (<div key={k} className="text-center py-1"><p className="text-[10px] text-muted-foreground uppercase tracking-wide font-medium">- {getMetricLabel(k, t as unknown as Record<string, string>)}+ {getMetricLabel(k)}</p><p className={cn("text-sm font-bold font-mono tabular-nums mt-0.5",diff --git a/frontend/src/components/chat/RunCompleteCard.tsx b/frontend/src/components/chat/RunCompleteCard.tsxindex 550039bf8..db99d41cc 100644--- a/frontend/src/components/chat/RunCompleteCard.tsx+++ b/frontend/src/components/chat/RunCompleteCard.tsx@@ -1,7 +1,6 @@import { memo, useEffect, useState, useCallback } from "react";import { Link } from "react-router-dom";import { BarChart3, Code2, FileText, Loader2 } from "lucide-react";-import { useI18n } from "@/lib/i18n";import { api } from "@/lib/api";import { AgentAvatar } from "./AgentAvatar";import { MetricsCard } from "./MetricsCard";@@ -14,7 +13,6 @@ interface Props {}export const RunCompleteCard = memo(function RunCompleteCard({ msg }: Props) {- const { t } = useI18n();const [curve, setCurve] = useState(msg.equityCurve);const [pineCode, setPineCode] = useState<string | null>(null);const [pineLoading, setPineLoading] = useState(false);@@ -82,7 +80,7 @@ export const RunCompleteCard = memo(function RunCompleteCard({ msg }: Props) {className="text-sm text-primary hover:underline inline-flex items-center gap-1.5 font-medium"><BarChart3 className="h-3.5 w-3.5" />- {t.fullReport}+ Full Report →</Link>)}{pineExists && (diff --git a/frontend/src/components/chat/ThinkingTimeline.tsx b/frontend/src/components/chat/ThinkingTimeline.tsxindex b6539017d..182ab8ce5 100644--- a/frontend/src/components/chat/ThinkingTimeline.tsx+++ b/frontend/src/components/chat/ThinkingTimeline.tsx@@ -1,7 +1,6 @@import { useState, useEffect, useMemo, memo } from "react";import { ChevronDown, ChevronRight, CheckCircle2, XCircle, Circle, Loader2 } from "lucide-react";import { cn } from "@/lib/utils";-import { useI18n } from "@/lib/i18n";import { localizeToolName } from "@/lib/tools";import type { AgentMessage } from "@/types/agent";@@ -11,16 +10,11 @@ interface Props {}export const ThinkingTimeline = memo(function ThinkingTimeline({ messages, isLatest = false }: Props) {- const { t } = useI18n();const [expanded, setExpanded] = useState(isLatest);const toolLabel = (tool?: string): string => {- if (!tool) return t.toolProcessing;- const key = localizeToolName(tool);- // If the lookup returned a mapped i18n key, resolve it against the- // active i18n table; otherwise fall back to the raw tool name.- if (key === tool) return tool;- return (t as Record<string, string>)[key] || tool;+ if (!tool) return "Processing";+ return localizeToolName(tool);};useEffect(() => {@@ -62,8 +56,8 @@ export const ThinkingTimeline = memo(function ThinkingTimeline({ messages, isLatconst stepCount = steps.length;const summaryText = isRunning- ? t.thinkingRunning.replace("{tool}", toolLabel(latestTool))- : t.thinkingDone.replace("{count}", String(stepCount)) + (totalMs > 0 ? ` · ${(totalMs / 1000).toFixed(1)}s` : "");+ ? `Running ${toolLabel(latestTool)}...`+ : `Done · ${stepCount} steps${totalMs > 0 ? ` · ${(totalMs / 1000).toFixed(1)}s` : ""}`;return (<div className="rounded-lg border border-border/40 bg-muted/5 overflow-hidden">@@ -125,7 +119,7 @@ export const ThinkingTimeline = memo(function ThinkingTimeline({ messages, isLat{/* Duration or status */}{step.status === "running" ? (- <span className="text-[10px] text-primary/60">{t.toolRunning}</span>+ <span className="text-[10px] text-primary/60">Running</span>) : step.elapsed_ms != null ? (<span className="text-[10px] text-muted-foreground/40 tabular-nums">{(step.elapsed_ms / 1000).toFixed(1)}s</span>) : null}diff --git a/frontend/src/components/chat/ToolProgressIndicator.tsx b/frontend/src/components/chat/ToolProgressIndicator.tsxindex c329f9c42..d69e92e1e 100644--- a/frontend/src/components/chat/ToolProgressIndicator.tsx+++ b/frontend/src/components/chat/ToolProgressIndicator.tsx@@ -1,25 +1,10 @@import { useRef, type JSX } from "react";import { Loader2, CheckCircle2, XCircle } from "lucide-react";import { cn } from "@/lib/utils";-import { useI18n } from "@/lib/i18n";import { ProgressBar } from "@/components/chat/ProgressBar";import { localizeToolName } from "@/lib/tools";import type { ToolCallEntry } from "@/types/agent";-/**- * Resolve a tool name to its user-facing label via the active i18n bundle.- * Mirrors the pattern in ThinkingTimeline.tsx (`toolLabel`): localizeToolName- * returns an i18n key when one is mapped, otherwise the raw tool name.- */-function useLocalizedToolName(): (tool: string) => string {- const { t } = useI18n();- return (tool: string) => {- const key = localizeToolName(tool);- if (key === tool) return tool;- return (t as Record<string, string>)[key] || tool;- };-}-/* ---------- ETA tracking (per-tool) ---------- */interface EtaSample {stage: string;@@ -80,7 +65,6 @@ interface RowProps {}function ToolRow({ entry, stepIndex, totalSteps, isHeader, connector = "none", eta }: RowProps): JSX.Element {- const localizeName = useLocalizedToolName();const progress = entry.progress;const hasDeterminate = !!(progress && typeof progress.current === "number" && typeof progress.total === "number" && progress.total > 0);const stage = progress?.stage || "";@@ -94,7 +78,7 @@ function ToolRow({ entry, stepIndex, totalSteps, isHeader, connector = "none", e? <ProgressRing current={progress!.current!} total={progress!.total!} />: <Loader2 className="h-3 w-3 animate-spin text-primary shrink-0" />;- const localized = localizeName(entry.tool);+ const localized = localizeToolName(entry.tool);const stepLabel = isHeader? `${totalSteps} tools running`: `Step ${stepIndex} · ${localized}`;diff --git a/frontend/src/components/chat/WelcomeScreen.tsx b/frontend/src/components/chat/WelcomeScreen.tsxindex f5a33f78f..822b3ac0a 100644--- a/frontend/src/components/chat/WelcomeScreen.tsx+++ b/frontend/src/components/chat/WelcomeScreen.tsx@@ -1,5 +1,4 @@import { Bot, TrendingUp, Globe, Sparkles, Users, UserCircle2, NotebookPen } from "lucide-react";-import { useI18n } from "@/lib/i18n";interface Example {title: string;@@ -151,8 +150,6 @@ interface Props {}export function WelcomeScreen({ onExample }: Props) {- const { t } = useI18n();-return (<div className="flex flex-col items-center justify-center min-h-[60vh] space-y-8 text-center">{/* Header */}@@ -166,7 +163,7 @@ export function WelcomeScreen({ onExample }: Props) {vibe trading with your professional financial agent team</p><p className="text-sm text-muted-foreground mt-2 max-w-md leading-relaxed mx-auto">- {t.describeStrategy}+ Describe a trading strategy to get started.</p></div></div>@@ -185,7 +182,7 @@ export function WelcomeScreen({ onExample }: Props) {{/* Example categories grid */}<div className="w-full max-w-2xl text-left space-y-4">- <p className="text-xs text-muted-foreground px-1">{t.examples}</p>+ <p className="text-xs text-muted-foreground px-1">Try an example:</p><div className="grid grid-cols-1 sm:grid-cols-2 gap-3">{CATEGORIES.map((cat) => (<div key={cat.label} className="space-y-2">diff --git a/frontend/src/components/layout/ConnectionBanner.tsx b/frontend/src/components/layout/ConnectionBanner.tsxindex c15ff7577..8248a30dd 100644--- a/frontend/src/components/layout/ConnectionBanner.tsx+++ b/frontend/src/components/layout/ConnectionBanner.tsx@@ -1,5 +1,4 @@import { WifiOff, RefreshCw } from "lucide-react";-import { useI18n } from "@/lib/i18n";import type { SSEStatus } from "@/hooks/useSSE";interface Props {@@ -8,7 +7,6 @@ interface Props {}export function ConnectionBanner({ status, retryAttempt }: Props) {- const { t } = useI18n();if (status === "connected" || status === "disconnected") return null;return (@@ -16,12 +14,12 @@ export function ConnectionBanner({ status, retryAttempt }: Props) {{status === "reconnecting" ? (<><RefreshCw className="h-3.5 w-3.5 animate-spin" />- <span>{t.reconnectingN.replace("{n}", String(retryAttempt || 1))}</span>+ <span>Connection lost, reconnecting (attempt {retryAttempt || 1})…</span></>) : (<><WifiOff className="h-3.5 w-3.5" />- <span>{t.disconnected}</span>+ <span>Connection lost</span></>)}</div>diff --git a/frontend/src/components/layout/Layout.tsx b/frontend/src/components/layout/Layout.tsxindex 7c7e304b1..f952977d4 100644--- a/frontend/src/components/layout/Layout.tsx+++ b/frontend/src/components/layout/Layout.tsx@@ -2,7 +2,6 @@import { Link, Outlet, useLocation, useSearchParams } from "react-router-dom";import { BarChart3, Bot, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings, Layers } from "lucide-react";import { cn } from "@/lib/utils";-import { useI18n } from "@/lib/i18n";import { useDarkMode } from "@/hooks/useDarkMode";import { api, type SessionItem } from "@/lib/api";import { useAgentStore } from "@/stores/agent";@@ -11,19 +10,17 @@ import { ConnectionBanner } from "@/components/layout/ConnectionBanner";// Bump on each release; one place keeps the footer in sync with package.json.const APP_VERSION = "v0.1.8";-// NAV entries: `key` looks up label in i18n; `label` overrides (used for "Alpha Zoo").const NAV = [- { to: "/", icon: BarChart3, key: "home" as const, label: null },- { to: "/agent", icon: Bot, key: "agent" as const, label: null },- { to: "/alpha-zoo", icon: Layers, key: "alphaZoo" as const, label: "Alpha Zoo" },- { to: "/settings", icon: Settings, key: "settings" as const, label: null },- { to: "/correlation", icon: BarChart3, key: "correlation" as const, label: null },+ { to: "/", icon: BarChart3, label: "Home" },+ { to: "/agent", icon: Bot, label: "Agent" },+ { to: "/alpha-zoo", icon: Layers, label: "Alpha Zoo" },+ { to: "/settings", icon: Settings, label: "Settings" },+ { to: "/correlation", icon: BarChart3, label: "Correlation Matrix" },];export function Layout() {const { pathname } = useLocation();const [searchParams] = useSearchParams();- const { t } = useI18n();const { dark, toggle } = useDarkMode();const [sessions, setSessions] = useState<SessionItem[]>([]);const [sessionsLoading, setSessionsLoading] = useState(true);@@ -87,8 +84,8 @@ export function Layout() {{/* Nav */}<nav className={cn("space-y-0.5", collapsed ? "p-1" : "p-2")}>- {NAV.map(({ to, icon: Icon, key, label }) => {- const text = label ?? t[key];+ {NAV.map(({ to, icon: Icon, label }) => {+ const text = label;return (<Linkkey={to}@@ -115,12 +112,12 @@ export function Layout() {<div className="flex items-center justify-between px-4 py-2"><span className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground"><MessageSquare className="h-3.5 w-3.5" />- {t.sessions}+ Sessions</span><Linkto="/agent"className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"- title={t.newChat}+ title="New Chat"><Plus className="h-3.5 w-3.5" /></Link>@@ -134,7 +131,7 @@ export function Layout() {))}</div>) : sessions.length === 0 ? (- <p className="px-3 py-2 text-xs text-muted-foreground/60">{t.noSessions}</p>+ <p className="px-3 py-2 text-xs text-muted-foreground/60">No sessions yet</p>) : null}{sessions.map((s) => {const isActive = s.session_id === activeSessionId;@@ -173,8 +170,8 @@ export function Layout() {)}{!isRenaming && isDeleting ? (<div className="absolute right-0.5 flex items-center gap-0.5">- <button onClick={() => deleteSession(s.session_id)} className="p-1 text-danger hover:bg-danger/10 rounded text-[10px] font-medium">{t.confirmDelete}</button>- <button onClick={() => setDeleteTarget(null)} className="p-1 text-muted-foreground hover:bg-muted rounded text-[10px]">{t.cancelDelete}</button>+ <button onClick={() => deleteSession(s.session_id)} className="p-1 text-danger hover:bg-danger/10 rounded text-[10px] font-medium">Confirm</button>+ <button onClick={() => setDeleteTarget(null)} className="p-1 text-muted-foreground hover:bg-muted rounded text-[10px]">Cancel</button></div>) : !isRenaming ? (<div className="absolute right-1 opacity-0 group-hover:opacity-100 flex items-center gap-0.5 transition-opacity">@@ -188,7 +185,7 @@ export function Layout() {<buttononClick={(e) => { e.preventDefault(); e.stopPropagation(); setDeleteTarget(s.session_id); }}className="p-1 text-muted-foreground hover:text-danger rounded"- title={t.deleteConfirm}+ title="Delete?"><Trash2 className="h-3 w-3" /></button>@@ -208,7 +205,7 @@ export function Layout() {<div className={cn("border-t", collapsed ? "p-1 flex flex-col items-center gap-1" : "p-3 space-y-2")}>{collapsed ? (<>- <button onClick={toggle} className="p-1.5 text-muted-foreground hover:text-foreground rounded transition-colors" title={dark ? t.lightMode : t.darkMode}>+ <button onClick={toggle} className="p-1.5 text-muted-foreground hover:text-foreground rounded transition-colors" title={dark ? "Light" : "Dark"}>{dark ? <Sun className="h-3.5 w-3.5" /> : <Moon className="h-3.5 w-3.5" />}</button><button onClick={() => setCollapsed(false)} className="p-1.5 text-muted-foreground hover:text-foreground rounded transition-colors" title="Expand">@@ -223,7 +220,7 @@ export function Layout() {className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors">{dark ? <Sun className="h-3.5 w-3.5" /> : <Moon className="h-3.5 w-3.5" />}- {dark ? t.lightMode : t.darkMode}+ {dark ? "Light" : "Dark"}</button><div className="flex items-center gap-1"><buttondiff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.tsindex 1063508e9..2e4247f4f 100644--- a/frontend/src/hooks/useSSE.ts+++ b/frontend/src/hooks/useSSE.ts@@ -82,6 +82,7 @@ export function useSSE(config?: SSEConfig) {const knownTypes = ["text_delta", "thinking_done", "tool_call", "tool_result", "compact","attempt.completed", "attempt.failed",+ "goal.created", "goal.evidence","heartbeat", "done",];diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex d4c238c6b..f6252d01e 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -66,6 +66,11 @@ async function uploadFile(file: File): Promise<UploadResult> {return res.json();}+function appendQueryParam(url: string, key: string, value: string): string {+ const sep = url.includes("?") ? "&" : "?";+ return `${url}${sep}${encodeURIComponent(key)}=${encodeURIComponent(value)}`;+}+export const api = {uploadFile,listRuns: () => request<RunListItem[]>("/runs"),@@ -79,7 +84,22 @@ export const api = {sendMessage: (sid: string, content: string) => request<{ message_id: string; attempt_id: string }>(`/sessions/${sid}/messages`, { method: "POST", body: JSON.stringify({ content }) }),cancelSession: (sid: string) => request<{ status: string }>(`/sessions/${sid}/cancel`, { method: "POST" }),getSessionMessages: (sid: string) => request<MessageItem[]>(`/sessions/${sid}/messages`),- sseUrl: (sid: string) => withAuthQuery(`${BASE}/sessions/${sid}/events`),+ createGoal: (sid: string, body: CreateGoalRequest) =>+ request<GoalSnapshot>(`/sessions/${sid}/goal`, {+ method: "POST",+ body: JSON.stringify(body),+ }),+ getGoal: (sid: string) => request<GoalSnapshot>(`/sessions/${sid}/goal`),+ addGoalEvidence: (sid: string, body: AddGoalEvidenceRequest) =>+ request<AddGoalEvidenceResponse>(`/sessions/${sid}/goal/evidence`, {+ method: "POST",+ body: JSON.stringify(body),+ }),+ sseUrl: (sid: string, options?: { replay?: "active" }) => {+ let url = withAuthQuery(`${BASE}/sessions/${sid}/events`);+ if (options?.replay) url = appendQueryParam(url, "replay", options.replay);+ return url;+ },// Swarm APIlistSwarmPresets: () => request<SwarmPreset[]>("/swarm/presets"),@@ -369,6 +389,152 @@ export interface SessionItem {last_attempt_id?: string;}+// --- Goal types ---++export type GoalStatus =+ | "active"+ | "paused"+ | "waiting_user"+ | "needs_refresh"+ | "insufficient_evidence"+ | "compliance_blocked"+ | "blocked"+ | "budget_limited"+ | "usage_limited"+ | "complete"+ | "cancelled"+ | "superseded";++export type GoalRiskTier =+ | "research_general"+ | "market_specific_short_term"+ | "personalized_advice_or_position_sizing";++export interface GoalRecord {+ goal_id: string;+ session_id: string;+ status: GoalStatus;+ objective: string;+ ui_summary: string;+ source: string;+ protocol: string;+ risk_tier: GoalRiskTier;+ token_budget?: number | null;+ tokens_used: number;+ turn_budget?: number | null;+ turns_used: number;+ time_budget_seconds?: number | null;+ time_used_seconds: number;+ budget_wrapup_sent: boolean;+ created_at: string;+ updated_at: string;+ completed_at?: string | null;+ recap?: string | null;+}++export interface GoalClaim {+ claim_id: string;+ goal_id: string;+ session_id: string;+ claim_type: string;+ text: string;+ status: string;+ created_at: string;+ updated_at: string;+}++export interface GoalCriterion {+ criterion_id: string;+ goal_id: string;+ session_id: string;+ text: string;+ required: boolean;+ status: string;+ freshness_requirement?: string | null;+ protocol_step?: string | null;+ created_at: string;+ updated_at: string;+}++export interface GoalEvidence {+ evidence_id: string;+ goal_id: string;+ session_id: string;+ text: string;+ criterion_id?: string | null;+ claim_id?: string | null;+ evidence_type: string;+ tool_call_id?: string | null;+ run_id?: string | null;+ source_provider?: string | null;+ source_type?: string | null;+ source_uri?: string | null;+ symbol_universe: string[];+ benchmark: string[];+ timeframe?: string | null;+ method?: string | null;+ assumptions: Record<string, unknown>;+ artifact_path?: string | null;+ artifact_hash?: string | null;+ retrieved_at: string;+ data_as_of?: string | null;+ freshness_status: string;+ verification_status: string;+ confidence?: string | null;+ caveat?: string | null;+ contradicts_claim_ids: string[];+ created_at: string;+}++export interface GoalSnapshot {+ goal: GoalRecord;+ claims: GoalClaim[];+ criteria: GoalCriterion[];+ evidence: GoalEvidence[];+ evidence_count: number;+}++export interface CreateGoalRequest {+ objective: string;+ criteria?: string[];+ ui_summary?: string;+ protocol?: string;+ risk_tier?: GoalRiskTier;+ token_budget?: number;+ turn_budget?: number;+ time_budget_seconds?: number;+}++export interface AddGoalEvidenceRequest {+ goal_id: string;+ expected_goal_id: string;+ text: string;+ criterion_id?: string | null;+ claim_id?: string | null;+ evidence_type?: string;+ tool_call_id?: string | null;+ run_id?: string | null;+ source_provider?: string | null;+ source_type?: string | null;+ source_uri?: string | null;+ symbol_universe?: string[];+ benchmark?: string[];+ timeframe?: string | null;+ method?: string | null;+ assumptions?: Record<string, unknown>;+ artifact_path?: string | null;+ artifact_hash?: string | null;+ data_as_of?: string | null;+ confidence?: string | null;+ caveat?: string | null;+ contradicts_claim_ids?: string[];+}++export interface AddGoalEvidenceResponse {+ evidence: GoalEvidence;+ snapshot: GoalSnapshot;+}+// --- Alpha Zoo types ---export interface AlphaListParams {diff --git a/frontend/src/lib/formatters.ts b/frontend/src/lib/formatters.tsindex 36f856f67..a93968418 100644--- a/frontend/src/lib/formatters.ts+++ b/frontend/src/lib/formatters.ts@@ -1,26 +1,23 @@-/** Maps metric keys to i18n translation keys */-export const METRIC_I18N_KEYS: Record<string, string> = {- total_return: "metricTotalReturn",- annual_return: "metricAnnualReturn",- sharpe: "metricSharpe",- max_drawdown: "metricMaxDrawdown",- win_rate: "metricWinRate",- trade_count: "metricTradeCount",- final_value: "metricFinalValue",- calmar: "metricCalmar",- sortino: "metricSortino",- profit_loss_ratio: "metricProfitLossRatio",- max_consecutive_loss: "metricMaxConsecutiveLoss",- avg_holding_days: "metricAvgHoldingDays",- benchmark_return: "metricBenchmarkReturn",- excess_return: "metricExcessReturn",- information_ratio: "metricIR",+export const METRIC_LABELS: Record<string, string> = {+ total_return: "Total Return",+ annual_return: "Annual",+ sharpe: "Sharpe",+ max_drawdown: "Max DD",+ win_rate: "Win Rate",+ trade_count: "Trades",+ final_value: "Final Value",+ calmar: "Calmar",+ sortino: "Sortino",+ profit_loss_ratio: "P/L Ratio",+ max_consecutive_loss: "Max Consec. Loss",+ avg_holding_days: "Avg Hold Days",+ benchmark_return: "Benchmark",+ excess_return: "Excess Return",+ information_ratio: "IR",};-/** Resolve metric label using i18n translations object */-export function getMetricLabel(k: string, t: Record<string, string>): string {- const i18nKey = METRIC_I18N_KEYS[k];- return i18nKey ? (t[i18nKey] || k) : k;+export function getMetricLabel(k: string): string {+ return METRIC_LABELS[k] || k;}const PCT_KEYS = ["total_return", "annual_return", "win_rate", "max_drawdown", "benchmark_return", "excess_return"];diff --git a/frontend/src/lib/i18n.tsx b/frontend/src/lib/i18n.tsxdeleted file mode 100644index 2d000b066..000000000--- a/frontend/src/lib/i18n.tsx+++ /dev/null@@ -1,180 +0,0 @@-import { createContext, useContext, type ReactNode } from "react";--const messages = {- home: "Home", agent: "Agent", runs: "Runs", settings: "Settings", alphaZoo: "Alpha Zoo",- settingsDesc: "Configure model credentials and market data source tokens for this local project.",- localApiAccess: "Local API access",- localApiAccessDesc: "For remote or private Web UI deployments, enter the server API key once in this browser. Localhost use can stay blank.",- localApiKey: "Server API key",- localApiKeyHint: "Stored only in this browser. Leave blank to clear it.",- localApiKeySaved: "Local API key saved",- localApiKeySave: "Save local key",- settingsUnavailable: "Settings are unavailable",- llmSettings: "LLM Settings",- llmSettingsDesc: "Choose the model used by the agent and save it to the project-local agent/.env file.",- llmConnection: "Connection",- llmGeneration: "Generation",- llmProvider: "Provider",- llmModelName: "Model",- llmBaseUrl: "Base URL",- llmApiKey: "API key",- llmApiKeyConfigured: "Configured",- llmApiKeyPlaceholder: "Leave blank to keep the current key",- llmClearApiKey: "Clear saved API key",- llmNoApiKeyRequired: "This provider does not require an API key.",- llmOauthRequired: "This provider uses OAuth. Run: {command}",- llmTemperature: "Temperature",- llmTimeoutSeconds: "Timeout seconds",- llmMaxRetries: "Max retries",- llmReasoningEffort: "Reasoning effort",- llmReasoningOff: "Off",- llmSaveSettings: "Save settings",- llmSaving: "Saving...",- llmSettingsSaved: "LLM settings saved",- llmSettingsLoadFailed: "Failed to load LLM settings",- llmSettingsSaveFailed: "Failed to save LLM settings",- llmEnvPath: "Saved to",- llmProviderHint: "Changing providers updates the recommended model and endpoint.",- llmModelHint: "Use the exact model id required by your provider.",- llmUseProviderDefaults: "Use provider defaults",- dataSourceSettings: "Data Source Settings",- dataSourceSettingsDesc: "Configure optional market data credentials used by backtests and research agents.",- tushareToken: "Tushare token",- tushareTokenConfigured: "Configured",- tushareTokenPlaceholder: "Leave blank to keep the current token",- tushareTokenHint: "Used for China A-share, futures, fund, and macro data. If unset, the project falls back to AKShare where available.",- clearTushareToken: "Clear saved Tushare token",- baostockStatus: "BaoStock",- baostockSupported: "Loader available",- baostockNotSupported: "No project loader",- baostockPackageInstalled: "Python package installed",- baostockPackageMissing: "Python package not installed",- saveDataSourceSettings: "Save data source settings",- dataSourceSettingsSaved: "Data source settings saved",- dataSourceSettingsLoadFailed: "Failed to load data source settings",- dataSourceSettingsSaveFailed: "Failed to save data source settings",- unknownError: "Unknown error",- startResearch: "Start Research", describeStrategy: "Describe a trading strategy to get started.",- prompt: "e.g. Create a dual MA crossover strategy for 000001.SZ, backtest 2024",- send: "Send", loading: "Loading...", noRuns: "No runs yet. Go to Agent to create one.",- runHistory: "Run History", status: "Status", elapsed: "Elapsed",- chart: "Chart", trades: "Trades", code: "Code", trace: "Trace",- noData: "No data available", noTrades: "No trades recorded.", noCode: "No code files.",- noTrace: "No trace data.", priceAndTrades: "Price & Trades", equityAndDrawdown: "Equity & Drawdown",- examples: "Try an example:", bye: "Goodbye",- heroTitle: "AI-Powered Quant Strategy Research",- heroDesc: "Describe a trading strategy in natural language. The agent generates code, runs backtests, and optimizes — all in real time.",- feat1: "AI Agent", feat1d: "Natural language strategy generation with ReAct reasoning",- feat2: "Built-in Backtest", feat2d: "3 data sources: A-shares, US/HK, Crypto",- feat3: "Real-time Streaming", feat3d: "Watch the agent think, call tools, and iterate",- feat4: "Strategy Replay", feat4d: "Trade journal analyzer + Shadow Account — extract your rules, backtest them, attribute PnL delta",- score: "Score", passed: "Passed", failed: "Failed", findings: "Findings", recommendations: "Recommendations",- darkMode: "Dark", lightMode: "Light", language: "Language",- sessions: "Sessions", newChat: "New Chat", deleteConfirm: "Delete?",- noSessions: "No sessions yet",- viewDetails: "View Details",- fullReport: "Full Report →",- strategyComparison: "Strategy Comparison",- baseline: "Baseline", compareTo: "Compare", delta: "Delta", metric: "Metric",- selectRun: "-- Select --",- selectTwoRuns: "Select two runs to compare their metrics.",- online: "Online", offline: "Offline",- checking: "Checking…", checkConnection: "Check Connection",- appearance: "Appearance",- connection: "Connection",- endpoints: "Endpoints",- review: "Review",- noReview: "No review data available.",- colTime: "Time", colCode: "Code", colSide: "Side",- colPrice: "Price", colQty: "Qty", colReason: "Reason",- equityDrawdown: "Equity & Drawdown",- noPriceData: "No price data", noEquityData: "No equity data",- filterLogs: "Filter logs...",- confirmDelete: "Confirm", cancelDelete: "Cancel",- reconnectingN: "Connection lost, reconnecting (attempt {n})…",- disconnected: "Connection lost",- sessionCreated: "Session started",- sendFailed: "Failed to send message, please retry.",- reconnecting: "Connection lost, reconnecting…",- connected: "Connection restored",- toolLoadSkill: "Load strategy knowledge",- toolWriteFile: "Generate code",- toolEditFile: "Edit code",- toolReadFile: "Read file",- toolRunBacktest: "Run backtest",- toolBash: "Run command",- toolReadUrl: "Read webpage",- toolReadDocument: "Read document",- toolCompact: "Compact context",- toolCreateTask: "Create task",- toolUpdateTask: "Update task",- toolSpawnSubagent: "Spawn sub-agent",- toolProcessing: "Processing",- toolRunning: "Running",- thinkingRunning: "Running {tool}...",- thinkingDone: "Done · {count} steps",- metricTotalReturn: "Total Return",- metricAnnualReturn: "Annual",- metricSharpe: "Sharpe",- metricMaxDrawdown: "Max DD",- metricWinRate: "Win Rate",- metricTradeCount: "Trades",- metricFinalValue: "Final Value",- metricCalmar: "Calmar",- metricSortino: "Sortino",- metricProfitLossRatio: "P/L Ratio",- metricMaxConsecutiveLoss: "Max Consec. Loss",- metricAvgHoldingDays: "Avg Hold Days",- metricBenchmarkReturn: "Benchmark",- metricExcessReturn: "Excess Return",- metricIR: "IR",- validation: "Validation",- overlayMA: "Moving Avg",- overlayChannel: "Channel",- overlayIndicators: "Indicators",- overlayClearAll: "Bare K (clear all)",- rename: "Rename",- goBack: "Go back",- noChartData: "No chart data available",- noChartDataHint: "The backtest engine may not have generated price data. Check the artifacts/ directory.",- executionFailed: "Execution failed",- executionTimeout: "Execution timed out, automatically stopped",- cancelSent: "Cancel request sent",- cancelFailed: "Cancel failed",- exportChat: "Export chat",- stopGeneration: "Stop generation",- newMessages: "New messages",- stepN: "Step {n}",- exportTitle: "# Chat Export",- exportTime: "Export time",- exportUser: "## User",- exportAssistant: "## Assistant",- exportError: "## Error",- exportToolCall: "> Tool call",- exportRunComplete: "> Backtest complete",- downloadTradesCsv: "Download Trades CSV",- downloadMetricsCsv: "Download Metrics CSV",- example1: "Dual MA crossover on 000001.SZ (5/20 day), backtest 2024",- example2: "Build a dual MA crossover strategy for 000001.SZ, backtest 2024",- example3: "Bollinger band mean-reversion on 600519.SH, backtest last 3 years",- correlation: "Correlation Matrix",- selectAssets: "Asset codes",- windowLabel: "Window (days)",- computeBtn: "Compute",- methodLabel: "Method",- noCorrelationData: "No correlation data available",-} as const;--type Messages = typeof messages;--const I18nCtx = createContext<{ t: Messages }>({ t: messages });--export function I18nProvider({ children }: { children: ReactNode }) {- return (- <I18nCtx.Provider value={{ t: messages }}>- {children}- </I18nCtx.Provider>- );-}--export function useI18n() { return useContext(I18nCtx); }diff --git a/frontend/src/lib/runReports.ts b/frontend/src/lib/runReports.tsnew file mode 100644index 000000000..4b8562d24--- /dev/null+++ b/frontend/src/lib/runReports.ts@@ -0,0 +1,26 @@+import type { RunData } from "@/lib/api";++function hasItems(value: unknown): boolean {+ return Array.isArray(value) && value.length > 0;+}++function hasObjectKeys(value: unknown): boolean {+ return !!value && typeof value === "object" && Object.keys(value).length > 0;+}++export function isReportWorthyRun(run: Pick<+ RunData,+ "metrics" | "run_card" | "equity_curve" | "trade_log" | "price_series" | "trade_markers" | "validation" | "artifacts"+> | null | undefined): boolean {+ if (!run) return false;+ if (hasObjectKeys(run.metrics)) return true;+ if (hasObjectKeys(run.run_card)) return true;+ if (hasItems(run.equity_curve)) return true;+ if (hasItems(run.trade_log)) return true;+ if (hasItems(run.trade_markers)) return true;+ if (hasObjectKeys(run.validation)) return true;+ if (run.price_series && Object.values(run.price_series).some(hasItems)) return true;+ return (run.artifacts || []).some((artifact) =>+ /(?:metrics|equity|trades|positions|ohlcv|validation|strategy)\.(?:csv|json|pine|py)$/i.test(artifact.name),+ );+}diff --git a/frontend/src/lib/tools.ts b/frontend/src/lib/tools.tsindex c65d14e7d..ca97aa51d 100644--- a/frontend/src/lib/tools.ts+++ b/frontend/src/lib/tools.ts@@ -1,41 +1,24 @@/**- * Single source of truth for tool name → i18n key.- *- * Values are i18n keys (looked up in `useI18n().t`), not final labels.- * The map name "TOOL_I18N_KEY" reflects this: it maps a raw tool identifier- * to the i18n bundle key whose value is the user-facing label.- *- * Consumers that need a final localized string should:- * 1. Call `localizeToolName(tool)` to get the i18n key (or fallback).- * 2. Resolve that key against the active i18n table.+ * Single source of truth for tool name → user-facing label.*/-export const TOOL_I18N_KEY: Record<string, string> = {- load_skill: "toolLoadSkill",- write_file: "toolWriteFile",- edit_file: "toolEditFile",- read_file: "toolReadFile",- run_backtest: "toolRunBacktest",- bash: "toolBash",- read_url: "toolReadUrl",- read_document: "toolReadDocument",- compact: "toolCompact",- create_task: "toolCreateTask",- update_task: "toolUpdateTask",- spawn_subagent: "toolSpawnSubagent",+export const TOOL_LABELS: Record<string, string> = {+ load_skill: "Load strategy knowledge",+ write_file: "Generate code",+ edit_file: "Edit code",+ read_file: "Read file",+ run_backtest: "Run backtest",+ bash: "Run command",+ read_url: "Read webpage",+ read_document: "Read document",+ compact: "Compact context",+ create_task: "Create task",+ update_task: "Update task",+ spawn_subagent: "Spawn sub-agent",};-/**- * Returns the i18n key (or fallback) for a tool name.- *- * - If `tool` is mapped in `TOOL_I18N_KEY`, returns the mapped key.- * - Else if `fallback` is provided, returns `fallback`.- * - Else returns `tool` unchanged.- *- * Centralizes the previously-duplicated lookup pattern.- */export function localizeToolName(tool: string, fallback?: string): string {- if (tool in TOOL_I18N_KEY) {- return TOOL_I18N_KEY[tool];+ if (tool in TOOL_LABELS) {+ return TOOL_LABELS[tool];}if (fallback !== undefined) {return fallback;diff --git a/frontend/src/main.tsx b/frontend/src/main.tsxindex 1c7e7c226..ed0b3d2a8 100644--- a/frontend/src/main.tsx+++ b/frontend/src/main.tsx@@ -2,7 +2,6 @@ import { StrictMode } from "react";import { createRoot } from "react-dom/client";import { RouterProvider } from "react-router-dom";import { Toaster } from "sonner";-import { I18nProvider } from "./lib/i18n";import { ErrorBoundary } from "./components/common/ErrorBoundary";import { router } from "./router";import "highlight.js/styles/github-dark-dimmed.min.css";@@ -11,10 +10,8 @@ import "./index.css";createRoot(document.getElementById("root")!).render(<StrictMode><ErrorBoundary>- <I18nProvider>- <RouterProvider router={router} />- <Toaster position="bottom-right" richColors closeButton duration={3500} />- </I18nProvider>+ <RouterProvider router={router} />+ <Toaster position="bottom-right" richColors closeButton duration={3500} /></ErrorBoundary></StrictMode>);diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsxindex eca730570..afd1db3f8 100644--- a/frontend/src/pages/Agent.tsx+++ b/frontend/src/pages/Agent.tsx@@ -1,11 +1,11 @@import { useEffect, useRef, useState, useMemo, useCallback, type FormEvent } from "react";import { useSearchParams } from "react-router-dom";-import { Send, Loader2, ArrowDown, Square, Download, Plus, Paperclip, X, Users } from "lucide-react";+import { Send, Loader2, ArrowDown, Square, Download, Plus, Paperclip, X, Users, Target } from "lucide-react";import { toast } from "sonner";import { useAgentStore } from "@/stores/agent";import { useSSE } from "@/hooks/useSSE";-import { useI18n } from "@/lib/i18n";-import { api } from "@/lib/api";+import { ApiError, api, type GoalSnapshot } from "@/lib/api";+import { isReportWorthyRun } from "@/lib/runReports";import type { AgentMessage, ToolCallEntry } from "@/types/agent";import { AgentAvatar } from "@/components/chat/AgentAvatar";import { WelcomeScreen } from "@/components/chat/WelcomeScreen";@@ -13,6 +13,7 @@ import { MessageBubble } from "@/components/chat/MessageBubble";import { ThinkingTimeline } from "@/components/chat/ThinkingTimeline";import { ConversationTimeline } from "@/components/chat/ConversationTimeline";import { ToolProgressIndicator } from "@/components/chat/ToolProgressIndicator";+import { GoalDrawer, getGoalProgress } from "@/components/chat/GoalDrawer";/* ---------- Message grouping ---------- */type MsgGroup =@@ -46,6 +47,7 @@ export function Agent() {const sseSessionRef = useRef<string | null>(null);const prevSseStatusRef = useRef<string>("disconnected");const genRef = useRef(0);+ const pendingGoalSessionRef = useRef<string | null>(null);const [showScrollBtn, setShowScrollBtn] = useState(false);const lastEventRef = useRef(0);@@ -59,6 +61,10 @@ export function Agent() {const uploadMenuRef = useRef<HTMLDivElement>(null);const fileInputRef = useRef<HTMLInputElement>(null);const [swarmPreset, setSwarmPreset] = useState<{ name: string; title: string } | null>(null);+ const [goalOpen, setGoalOpen] = useState(false);+ const [goalSnapshot, setGoalSnapshot] = useState<GoalSnapshot | null>(null);+ const [goalLoading, setGoalLoading] = useState(false);+ const [goalError, setGoalError] = useState<string | null>(null);const messages = useAgentStore(s => s.messages);const streamingText = useAgentStore(s => s.streamingText);@@ -68,7 +74,6 @@ export function Agent() {const sessionLoading = useAgentStore(s => s.sessionLoading);const { connect, disconnect, onStatusChange } = useSSE();- const { t } = useI18n();const urlSessionId = searchParams.get("session");@@ -112,17 +117,42 @@ export function Agent() {useEffect(() => {onStatusChange((s) => {act().setSseStatus(s);- if (s === "reconnecting" && prevSseStatusRef.current === "connected") toast.warning(t.reconnecting);- else if (s === "connected" && prevSseStatusRef.current === "reconnecting") toast.success(t.connected);+ if (s === "reconnecting" && prevSseStatusRef.current === "connected") toast.warning("Connection lost, reconnecting…");+ else if (s === "connected" && prevSseStatusRef.current === "reconnecting") toast.success("Connection restored");prevSseStatusRef.current = s;});- }, [onStatusChange, t]);+ }, [onStatusChange]);const doDisconnect = useCallback(() => {disconnect();sseSessionRef.current = null;}, [disconnect]);+ const loadGoalSnapshot = useCallback(async (sid?: string | null) => {+ const targetSession = sid || act().sessionId;+ if (!targetSession) {+ setGoalSnapshot(null);+ setGoalError(null);+ return;+ }+ setGoalLoading(true);+ setGoalError(null);+ try {+ const snapshot = await api.getGoal(targetSession);+ if (act().sessionId !== targetSession) return;+ setGoalSnapshot(snapshot);+ } catch (error) {+ if (act().sessionId !== targetSession) return;+ if (error instanceof ApiError && error.status === 404) {+ setGoalSnapshot(null);+ } else {+ setGoalError(error instanceof Error ? error.message : "Failed to load goal.");+ }+ } finally {+ if (act().sessionId === targetSession) setGoalLoading(false);+ }+ }, []);+const loadSessionMessages = useCallback(async (sid: string, gen: number) => {try {const msgs = await api.getSessionMessages(sid);@@ -140,7 +170,24 @@ export function Agent() {if (m.content && m.content !== "Strategy execution completed.") {agentMsgs.push({ id: m.message_id + "_ans", type: "answer", content: m.content, timestamp: ts });}- agentMsgs.push({ id: m.message_id, type: "run_complete", content: "", runId, metrics, timestamp: ts + 1 });+ if (metrics && Object.keys(metrics).length > 0) {+ agentMsgs.push({ id: m.message_id, type: "run_complete", content: "", runId, metrics, timestamp: ts + 1 });+ } else {+ try {+ const runData = await api.getRun(runId);+ if (isReportWorthyRun(runData)) {+ agentMsgs.push({+ id: m.message_id,+ type: "run_complete",+ content: "",+ runId,+ metrics: runData.metrics,+ equityCurve: runData.equity_curve?.map((e) => ({ time: e.time, equity: e.equity })),+ timestamp: ts + 1,+ });+ }+ } catch { /* ignore non-report attempt directories */ }+ }} else {agentMsgs.push({ id: m.message_id, type: "answer", content: m.content, timestamp: ts });}@@ -162,7 +209,7 @@ export function Agent() {const touch = () => { lastEventRef.current = Date.now(); };- connect(api.sseUrl(sid), {+ connect(api.sseUrl(sid, { replay: "active" }), {text_delta: (d) => { touch(); act().appendDelta(String(d.delta || "")); scrollToBottom(); },thinking_done: () => { touch(); /* don't flush — keep streaming text visible */ },@@ -262,11 +309,11 @@ export function Agent() {if (runId) {try {const runData = await api.getRun(runId);- const hasMetrics = runData.metrics && Object.keys(runData.metrics).length > 0;- if (hasMetrics || shadowId) {+ const hasReport = isReportWorthyRun(runData);+ if (hasReport || shadowId) {s.addMessage({id: "", type: "run_complete", content: "", runId,- metrics: hasMetrics ? runData.metrics : undefined,+ metrics: hasReport ? runData.metrics : undefined,equityCurve: runData.equity_curve?.map(e => ({ time: e.time, equity: e.equity })),shadowId,timestamp: Date.now(),@@ -294,10 +341,20 @@ export function Agent() {scrollToBottom();},+ "goal.created": () => {+ touch();+ loadGoalSnapshot(sid);+ },++ "goal.evidence": () => {+ touch();+ loadGoalSnapshot(sid);+ },+heartbeat: () => {},reconnect: (d) => { act().setSseStatus("reconnecting", Number(d.attempt ?? 0)); },});- }, [connect, disconnect, scrollToBottom]);+ }, [connect, disconnect, loadGoalSnapshot, scrollToBottom]);useEffect(() => {const gen = ++genRef.current;@@ -323,6 +380,19 @@ export function Agent() {}}, [urlSessionId, doDisconnect, loadSessionMessages, setupSSE, forceScrollToBottom]);+ useEffect(() => {+ if (!sessionId) {+ setGoalSnapshot(null);+ setGoalError(null);+ return;+ }+ if (pendingGoalSessionRef.current === sessionId) {+ pendingGoalSessionRef.current = null;+ return;+ }+ loadGoalSnapshot(sessionId);+ }, [sessionId, loadGoalSnapshot]);+useEffect(() => () => doDisconnect(), [doDisconnect]);/* Safety timeout: if streaming but no SSE event for 90s, reset to idle */@@ -370,11 +440,65 @@ export function Agent() {await api.sendMessage(sid, finalPrompt);} catch {act().setStatus("error");- toast.error(t.sendFailed);- act().addMessage({ id: "", type: "error", content: t.sendFailed, timestamp: Date.now() });+ toast.error("Failed to send message, please retry.");+ act().addMessage({ id: "", type: "error", content: "Failed to send message, please retry.", timestamp: Date.now() });}};+ const ensureGoalSession = useCallback(async (title: string): Promise<string> => {+ let sid = act().sessionId;+ if (sid) return sid;+ const session = await api.createSession(title.slice(0, 50));+ sid = session.session_id;+ pendingGoalSessionRef.current = sid;+ act().setSessionId(sid);+ setSearchParams({ session: sid }, { replace: true });+ setupSSE(sid);+ return sid;+ }, [setSearchParams, setupSSE]);++ const handleStartGoal = useCallback(async (objective: string) => {+ try {+ const sid = await ensureGoalSession(objective);+ const snapshot = await api.createGoal(sid, { objective });+ setGoalSnapshot(snapshot);+ setGoalError(null);+ toast.success("Goal started");+ } catch (error) {+ const message = error instanceof Error ? error.message : "Failed to start goal.";+ setGoalError(message);+ toast.error(message);+ }+ }, [ensureGoalSession]);++ const handleAddGoalEvidence = useCallback(async (criterionId: string, text: string) => {+ const sid = act().sessionId;+ const current = goalSnapshot;+ if (!sid || !current) {+ const message = "Start a goal before attaching evidence.";+ setGoalError(message);+ toast.error(message);+ return;+ }+ try {+ const result = await api.addGoalEvidence(sid, {+ goal_id: current.goal.goal_id,+ expected_goal_id: current.goal.goal_id,+ criterion_id: criterionId,+ text,+ source_provider: "webui",+ source_type: "manual_note",+ });+ setGoalSnapshot(result.snapshot);+ setGoalError(null);+ toast.success("Evidence attached");+ } catch (error) {+ const message = error instanceof Error ? error.message : "Failed to attach evidence.";+ setGoalError(message);+ toast.error(message);+ }+ }, [goalSnapshot]);+const handleSubmit = (e: FormEvent) => { e.preventDefault(); runPrompt(input.trim()); };const handleCancel = async () => {@@ -480,10 +604,43 @@ export function Agent() {}, [showUploadMenu]);const groups = useMemo(() => groupMessages(messages), [messages]);+ const goalProgress = useMemo(() => getGoalProgress(goalSnapshot), [goalSnapshot]);return (<div className="flex flex-col flex-1 min-w-0 overflow-hidden h-full"><div ref={listRef} className="flex-1 overflow-auto p-6 scroll-smooth relative">+ <div className="fixed right-6 top-4 z-40 flex items-center gap-2">+ <button+ type="button"+ title="Research goal"+ aria-label="Research goal"+ aria-expanded={goalOpen}+ onClick={() => {+ const nextOpen = !goalOpen;+ setGoalOpen(nextOpen);+ if (nextOpen) loadGoalSnapshot(sessionId);+ }}+ className="inline-flex h-8 items-center gap-1.5 rounded-full border bg-background px-3 text-xs font-medium text-foreground shadow-sm transition-colors hover:bg-muted"+ >+ <Target className="h-3.5 w-3.5 text-primary" aria-hidden="true" />+ <span>Goal</span>+ {goalProgress.label && (+ <span className="font-mono text-[11px] text-emerald-600 dark:text-emerald-400">{goalProgress.label}</span>+ )}+ </button>+ </div>++ <GoalDrawer+ open={goalOpen}+ snapshot={goalSnapshot}+ loading={goalLoading}+ error={goalError}+ onClose={() => setGoalOpen(false)}+ onRefresh={() => loadGoalSnapshot(sessionId)}+ onStart={handleStartGoal}+ onAddEvidence={handleAddGoalEvidence}+ />+<div className="max-w-3xl mx-auto space-y-4">{sessionLoading && (<div className="space-y-4 py-4">@@ -655,7 +812,7 @@ export function Agent() {runPrompt(input.trim());}}}- placeholder={t.prompt}+ placeholder="e.g. Create a dual MA crossover strategy for 000001.SZ, backtest 2024"className="flex-1 px-4 py-2.5 rounded-xl border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/40 transition-shadow resize-none max-h-32 overflow-y-auto"disabled={status === "streaming"}/>diff --git a/frontend/src/pages/Compare.tsx b/frontend/src/pages/Compare.tsxindex 0aa2036c5..fadbb7926 100644--- a/frontend/src/pages/Compare.tsx+++ b/frontend/src/pages/Compare.tsx@@ -2,7 +2,6 @@ import { useEffect, useRef, useState } from "react";import { GitCompare, ArrowRight } from "lucide-react";import { cn } from "@/lib/utils";import { api, type RunListItem, type RunData, type EquityPoint } from "@/lib/api";-import { useI18n } from "@/lib/i18n";import { echarts, CHART_GROUP, connectCharts } from "@/lib/echarts";import { getChartTheme } from "@/lib/chart-theme";import { useDarkMode } from "@/hooks/useDarkMode";@@ -197,7 +196,6 @@ function EquityChartOverlay({ leftCurve, rightCurve, leftLabel, rightLabel }: Eq}export function Compare() {- const { t } = useI18n();const [runs, setRuns] = useState<RunListItem[]>([]);const [leftId, setLeftId] = useState("");const [rightId, setRightId] = useState("");@@ -244,23 +242,23 @@ export function Compare() {return (<div className="p-8 max-w-4xl space-y-6"><h1 className="text-xl font-bold flex items-center gap-2">- <GitCompare className="h-5 w-5" /> {t.strategyComparison}+ <GitCompare className="h-5 w-5" /> Strategy Comparison</h1>{/* Selectors */}<div className="flex gap-4 items-end"><div className="flex-1">- <label className="text-xs text-muted-foreground block mb-1">{t.baseline}</label>+ <label className="text-xs text-muted-foreground block mb-1">Baseline</label><select value={leftId} onChange={(e) => setLeftId(e.target.value)} className="w-full px-3 py-2 rounded-lg border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" title={leftRun?.prompt || leftId}>- <option value="">{t.selectRun}</option>+ <option value="">-- Select --</option>{runs.map((r) => <option key={r.run_id} value={r.run_id}>{runLabel(r)} ({r.status})</option>)}</select></div><ArrowRight className="h-5 w-5 text-muted-foreground mb-2 shrink-0" /><div className="flex-1">- <label className="text-xs text-muted-foreground block mb-1">{t.compareTo}</label>+ <label className="text-xs text-muted-foreground block mb-1">Compare</label><select value={rightId} onChange={(e) => setRightId(e.target.value)} className="w-full px-3 py-2 rounded-lg border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" title={rightRun?.prompt || rightId}>- <option value="">{t.selectRun}</option>+ <option value="">-- Select --</option>{runs.map((r) => <option key={r.run_id} value={r.run_id}>{runLabel(r)} ({r.status})</option>)}</select></div>@@ -269,12 +267,12 @@ export function Compare() {{/* Equity curve overlay */}{(leftCurve.length > 0 || rightCurve.length > 0) && (<div className="border rounded-xl p-4">- <h2 className="text-sm font-medium text-muted-foreground mb-2">{t.equityDrawdown}</h2>+ <h2 className="text-sm font-medium text-muted-foreground mb-2">Equity & Drawdown</h2><EquityChartOverlayleftCurve={leftCurve}rightCurve={rightCurve}- leftLabel={leftRun ? truncatePrompt(leftRun.prompt, 20) || t.baseline : t.baseline}- rightLabel={rightRun ? truncatePrompt(rightRun.prompt, 20) || t.compareTo : t.compareTo}+ leftLabel={leftRun ? truncatePrompt(leftRun.prompt, 20) || "Baseline" : "Baseline"}+ rightLabel={rightRun ? truncatePrompt(rightRun.prompt, 20) || "Compare" : "Compare"}/></div>)}@@ -285,10 +283,10 @@ export function Compare() {<table className="w-full text-sm"><thead><tr className="border-b bg-muted/40">- <th className="text-left px-4 py-2.5 text-muted-foreground font-medium">{t.metric}</th>- <th className="text-right px-4 py-2.5 text-muted-foreground font-medium">{t.baseline}</th>- <th className="text-right px-4 py-2.5 text-muted-foreground font-medium">{t.compareTo}</th>- <th className="text-right px-4 py-2.5 text-muted-foreground font-medium">{t.delta}</th>+ <th className="text-left px-4 py-2.5 text-muted-foreground font-medium">Metric</th>+ <th className="text-right px-4 py-2.5 text-muted-foreground font-medium">Baseline</th>+ <th className="text-right px-4 py-2.5 text-muted-foreground font-medium">Compare</th>+ <th className="text-right px-4 py-2.5 text-muted-foreground font-medium">Delta</th></tr></thead><tbody>@@ -312,7 +310,7 @@ export function Compare() {{!leftData && !rightData && (<div className="text-center py-16 text-muted-foreground"><GitCompare className="h-12 w-12 mx-auto mb-3 opacity-20" />- <p className="text-sm">{t.selectTwoRuns}</p>+ <p className="text-sm">Select two runs to compare their metrics.</p></div>)}</div>diff --git a/frontend/src/pages/Correlation.tsx b/frontend/src/pages/Correlation.tsxindex fde50b6f3..e6e7e9db1 100644--- a/frontend/src/pages/Correlation.tsx+++ b/frontend/src/pages/Correlation.tsx@@ -1,12 +1,10 @@import { useState } from "react";import { BarChart3 } from "lucide-react";-import { useI18n } from "@/lib/i18n";import { CorrelationMatrix } from "@/components/charts/CorrelationMatrix";const WINDOWS = [30, 60, 90, 180, 365] as const;export function Correlation() {- const { t } = useI18n();const [codes, setCodes] = useState("BTC-USDT,ETH-USDT,SPY,AAPL");const [days, setDays] = useState<number>(90);const [method, setMethod] = useState<"pearson" | "spearman">("pearson");@@ -37,13 +35,13 @@ export function Correlation() {{/* Header */}<div className="flex items-center gap-3"><BarChart3 className="h-6 w-6 text-primary" />- <h1 className="text-2xl font-bold">{t.correlation || "Correlation Matrix"}</h1>+ <h1 className="text-2xl font-bold">Correlation Matrix</h1></div>{/* Controls */}<div className="flex flex-col gap-4 border rounded-lg p-4"><div className="flex flex-col gap-1.5">- <label className="text-sm font-medium">{t.selectAssets || "Asset codes"}</label>+ <label className="text-sm font-medium">Asset codes</label><inputtype="text"value={codes}@@ -58,7 +56,7 @@ export function Correlation() {<div className="flex flex-wrap gap-4"><div className="flex flex-col gap-1.5">- <label className="text-sm font-medium">{t.windowLabel || "Window (days)"}</label>+ <label className="text-sm font-medium">Window (days)</label><div className="flex gap-1.5">{WINDOWS.map((w) => (<button@@ -77,7 +75,7 @@ export function Correlation() {</div><div className="flex flex-col gap-1.5">- <label className="text-sm font-medium">{t.methodLabel || "Method"}</label>+ <label className="text-sm font-medium">Method</label><div className="flex gap-1.5">{(["pearson", "spearman"] as const).map((m) => (<button@@ -101,7 +99,7 @@ export function Correlation() {disabled={loading}className="self-start px-4 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50 transition-opacity">- {loading ? (t.loading || "Loading...") : (t.computeBtn || "Compute")}+ {loading ? "Loading..." : "Compute"}</button></div>diff --git a/frontend/src/pages/Home.tsx b/frontend/src/pages/Home.tsxindex 70c640147..95ede0c5d 100644--- a/frontend/src/pages/Home.tsx+++ b/frontend/src/pages/Home.tsx@@ -1,27 +1,24 @@import { Link } from "react-router-dom";import { ArrowRight, Bot, BarChart3, Zap, UserCircle2 } from "lucide-react";-import { useI18n } from "@/lib/i18n";export function Home() {- const { t } = useI18n();-const FEATURES = [- { icon: Bot, title: t.feat1, desc: t.feat1d },- { icon: BarChart3, title: t.feat2, desc: t.feat2d },- { icon: Zap, title: t.feat3, desc: t.feat3d },- { icon: UserCircle2, title: t.feat4, desc: t.feat4d },+ { icon: Bot, title: "AI Agent", desc: "Natural language strategy generation with ReAct reasoning" },+ { icon: BarChart3, title: "Built-in Backtest", desc: "3 data sources: A-shares, US/HK, Crypto" },+ { icon: Zap, title: "Real-time Streaming", desc: "Watch the agent think, call tools, and iterate" },+ { icon: UserCircle2, title: "Strategy Replay", desc: "Trade journal analyzer + Shadow Account — extract your rules, backtest them, attribute PnL delta" },];return (<div className="flex flex-col items-center justify-center min-h-screen p-8"><div className="max-w-2xl text-center space-y-6">- <h1 className="text-4xl font-bold tracking-tight">{t.heroTitle}</h1>- <p className="text-lg text-muted-foreground">{t.heroDesc}</p>+ <h1 className="text-4xl font-bold tracking-tight">AI-Powered Quant Strategy Research</h1>+ <p className="text-lg text-muted-foreground">Describe a trading strategy in natural language. The agent generates code, runs backtests, and optimizes — all in real time.</p><Linkto="/agent"className="inline-flex items-center gap-2 px-6 py-3 rounded-lg bg-primary text-primary-foreground font-medium hover:opacity-90 transition">- {t.startResearch} <ArrowRight className="h-4 w-4" />+ Start Research <ArrowRight className="h-4 w-4" /></Link></div>diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsxindex efacb8503..728fc40f4 100644--- a/frontend/src/pages/RunDetail.tsx+++ b/frontend/src/pages/RunDetail.tsx@@ -16,7 +16,6 @@ import {XCircle,} from "lucide-react";import { cn } from "@/lib/utils";-import { useI18n } from "@/lib/i18n";import { api, type BacktestMetrics, type RunCard, type RunData } from "@/lib/api";import ReactMarkdown from "react-markdown";import rehypeHighlight from "rehype-highlight";@@ -65,7 +64,6 @@ function buildMetricsCsv(metrics: BacktestMetrics): string {export function RunDetail() {const { runId } = useParams<{ runId: string }>();- const { t } = useI18n();const navigate = useNavigate();const [run, setRun] = useState<RunData | null>(null);const [code, setCode] = useState<Record<string, string>>({});@@ -75,11 +73,11 @@ export function RunDetail() {const hasValidation = !!run?.validation;const hasRunCard = !!run?.run_card;const TABS: { id: Tab; label: string; icon: typeof BarChart3; hidden?: boolean }[] = [- { id: "chart", label: t.chart, icon: BarChart3 },- { id: "trades", label: t.trades, icon: List },- { id: "validation", label: t.validation, icon: ShieldCheck, hidden: !hasValidation },+ { id: "chart", label: "Chart", icon: BarChart3 },+ { id: "trades", label: "Trades", icon: List },+ { id: "validation", label: "Validation", icon: ShieldCheck, hidden: !hasValidation },{ id: "runCard", label: "Run Card", icon: FileCheck2, hidden: !hasRunCard },- { id: "code", label: t.code, icon: Code2 },+ { id: "code", label: "Code", icon: Code2 },];useEffect(() => {@@ -141,18 +139,18 @@ export function RunDetail() {<buttononClick={() => downloadCsv(`trades_${runId}.csv`, buildTradesCsv(run.trade_log!))}className="flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs text-muted-foreground hover:bg-muted transition-colors"- title={t.downloadTradesCsv}+ title="Download Trades CSV">- <Download className="h-3.5 w-3.5" /> {t.downloadTradesCsv}+ <Download className="h-3.5 w-3.5" /> Download Trades CSV</button>)}{run.metrics && (<buttononClick={() => downloadCsv(`metrics_${runId}.csv`, buildMetricsCsv(run.metrics!))}className="flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs text-muted-foreground hover:bg-muted transition-colors"- title={t.downloadMetricsCsv}+ title="Download Metrics CSV">- <Download className="h-3.5 w-3.5" /> {t.downloadMetricsCsv}+ <Download className="h-3.5 w-3.5" /> Download Metrics CSV</button>)}</div>diff --git a/frontend/src/pages/Settings.tsx b/frontend/src/pages/Settings.tsxindex d5e6e23d4..2a18f9f6f 100644--- a/frontend/src/pages/Settings.tsx+++ b/frontend/src/pages/Settings.tsx@@ -3,7 +3,6 @@ import { Database, KeyRound, Loader2, RotateCcw, Save, Server, SlidersHorizontalimport { toast } from "sonner";import { api, isAuthRequiredError, type DataSourceSettings, type LLMProviderOption, type LLMSettings } from "@/lib/api";import { getApiAuthKey, setApiAuthKey } from "@/lib/apiAuth";-import { useI18n } from "@/lib/i18n";interface LLMFormState {provider: string;@@ -33,7 +32,6 @@ function toForm(settings: LLMSettings): LLMFormState {}export function Settings() {- const { t } = useI18n();const [settings, setSettings] = useState<LLMSettings | null>(null);const [dataSettings, setDataSettings] = useState<DataSourceSettings | null>(null);const [form, setForm] = useState<LLMFormState | null>(null);@@ -58,20 +56,20 @@ export function Settings() {setSettingsLoadError(null);}).catch((error) => {- const message = error instanceof Error ? error.message : t.unknownError;+ const message = error instanceof Error ? error.message : "Unknown error";setSettingsLoadError(message);if (isAuthRequiredError(error)) {toast.error(message);} else {- toast.error(`${t.llmSettingsLoadFailed}: ${message}`);- toast.error(`${t.dataSourceSettingsLoadFailed}: ${message}`);+ toast.error(`Failed to load LLM settings: ${message}`);+ toast.error(`Failed to load data source settings: ${message}`);}}).finally(() => {if (alive) setLoading(false);});return () => { alive = false; };- }, [t.dataSourceSettingsLoadFailed, t.llmSettingsLoadFailed]);+ }, []);const providers = settings?.providers ?? [];const selectedProvider = useMemo<LLMProviderOption | undefined>(@@ -104,7 +102,7 @@ export function Settings() {const submitLocalApiKey = (event: FormEvent) => {event.preventDefault();setApiAuthKey(localApiKey);- toast.success(t.localApiKeySaved);+ toast.success("Local API key saved");window.location.reload();};@@ -122,9 +120,9 @@ export function Settings() {setForm(toForm(updated));setApiKey("");setClearApiKey(false);- toast.success(t.llmSettingsSaved);+ toast.success("LLM settings saved");} catch (error) {- toast.error(`${t.llmSettingsSaveFailed}: ${error instanceof Error ? error.message : t.unknownError}`);+ toast.error(`Failed to save LLM settings: ${error instanceof Error ? error.message : "Unknown error"}`);} finally {setSaving(false);}@@ -141,9 +139,9 @@ export function Settings() {setDataSettings(updated);setTushareToken("");setClearTushareToken(false);- toast.success(t.dataSourceSettingsSaved);+ toast.success("Data source settings saved");} catch (error) {- toast.error(`${t.dataSourceSettingsSaveFailed}: ${error instanceof Error ? error.message : t.unknownError}`);+ toast.error(`Failed to save data source settings: ${error instanceof Error ? error.message : "Unknown error"}`);} finally {setDataSaving(false);}@@ -154,19 +152,19 @@ export function Settings() {<div className="mb-4 space-y-1"><div className="flex items-center gap-2"><KeyRound className="h-4 w-4 text-primary" />- <h2 className="text-base font-semibold">{t.localApiAccess}</h2>+ <h2 className="text-base font-semibold">{"Local API access"}</h2></div>- <p className="text-sm text-muted-foreground">{t.localApiAccessDesc}</p>+ <p className="text-sm text-muted-foreground">{"For remote or private Web UI deployments, enter the server API key once in this browser. Localhost use can stay blank."}</p></div><div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]"><label className="grid gap-2">- <span className={labelClass}>{t.localApiKey}</span>+ <span className={labelClass}>{"Server API key"}</span><inputtype="password"value={localApiKey}onChange={(event) => setLocalApiKeyState(event.target.value)}className={fieldClass}- placeholder={t.localApiKeyHint}+ placeholder={"Stored only in this browser. Leave blank to clear it."}autoComplete="current-password"/></label>@@ -175,10 +173,10 @@ export function Settings() {className="inline-flex items-center justify-center gap-2 self-end rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90"><Save className="h-4 w-4" />- {t.localApiKeySave}+ {"Save local key"}</button></div>- <p className="mt-2 text-xs text-muted-foreground">{t.localApiKeyHint}</p>+ <p className="mt-2 text-xs text-muted-foreground">{"Stored only in this browser. Leave blank to clear it."}</p></form>);@@ -186,20 +184,20 @@ export function Settings() {return (<div className="mx-auto max-w-5xl space-y-6 p-6"><div className="space-y-2">- <h1 className="text-2xl font-semibold tracking-tight">{t.settings}</h1>- <p className="max-w-3xl text-sm text-muted-foreground">{t.settingsDesc}</p>+ <h1 className="text-2xl font-semibold tracking-tight">{"Settings"}</h1>+ <p className="max-w-3xl text-sm text-muted-foreground">{"Configure model credentials and market data source tokens for this local project."}</p></div>{localApiAccessSection}<div className="flex min-h-32 items-center justify-center rounded-lg border bg-card p-5 text-sm text-muted-foreground">{settingsLoadError ? (<div className="text-center">- <div className="font-medium text-foreground">{t.settingsUnavailable}</div>+ <div className="font-medium text-foreground">{"Settings are unavailable"}</div><div className="mt-1">{settingsLoadError}</div></div>) : (<><Loader2 className="mr-2 h-4 w-4 animate-spin" />- {t.loading}+ {"Loading..."}</>)}</div>@@ -208,41 +206,41 @@ export function Settings() {}const keyStatus = settings.api_key_configured- ? t.llmApiKeyConfigured+ ? "Configured": settings.api_key_required- ? t.llmApiKeyPlaceholder+ ? "Leave blank to keep the current key": selectedProvider?.auth_type === "oauth" && selectedProvider.login_command- ? t.llmOauthRequired.replace("{command}", selectedProvider.login_command)- : t.llmNoApiKeyRequired;+ ? `This provider uses OAuth. Run: ${selectedProvider.login_command}`+ : "This provider does not require an API key.";const apiKeyDisabled = !selectedProvider?.api_key_required || clearApiKey;const tushareStatus = dataSettings.tushare_token_configured- ? t.tushareTokenConfigured- : t.tushareTokenPlaceholder;+ ? "Configured"+ : "Leave blank to keep the current token";return (<div className="mx-auto max-w-5xl space-y-6 p-6"><div className="space-y-2">- <h1 className="text-2xl font-semibold tracking-tight">{t.settings}</h1>- <p className="max-w-3xl text-sm text-muted-foreground">{t.settingsDesc}</p>+ <h1 className="text-2xl font-semibold tracking-tight">{"Settings"}</h1>+ <p className="max-w-3xl text-sm text-muted-foreground">{"Configure model credentials and market data source tokens for this local project."}</p></div>{localApiAccessSection}<div className="space-y-2">- <h2 className="text-lg font-semibold tracking-tight">{t.llmSettings}</h2>- <p className="max-w-3xl text-sm text-muted-foreground">{t.llmSettingsDesc}</p>+ <h2 className="text-lg font-semibold tracking-tight">{"LLM Settings"}</h2>+ <p className="max-w-3xl text-sm text-muted-foreground">{"Choose the model used by the agent and save it to the project-local agent/.env file."}</p></div><form onSubmit={submit} className="grid gap-6 lg:grid-cols-[minmax(0,1.4fr)_minmax(320px,0.8fr)]"><section className="rounded-lg border bg-card p-5 shadow-sm"><div className="mb-5 flex items-center gap-2"><Server className="h-4 w-4 text-primary" />- <h2 className="text-base font-semibold">{t.llmConnection}</h2>+ <h2 className="text-base font-semibold">{"Connection"}</h2></div><div className="grid gap-4"><label className="grid gap-2">- <span className={labelClass}>{t.llmProvider}</span>+ <span className={labelClass}>{"Provider"}</span><selectvalue={form.provider}onChange={(event) => onProviderChange(event.target.value)}@@ -252,11 +250,11 @@ export function Settings() {<option key={provider.name} value={provider.name}>{provider.label}</option>))}</select>- <span className={hintClass}>{t.llmProviderHint}</span>+ <span className={hintClass}>{"Changing providers updates the recommended model and endpoint."}</span></label><label className="grid gap-2">- <span className={labelClass}>{t.llmModelName}</span>+ <span className={labelClass}>{"Model"}</span><div className="flex gap-2"><inputvalue={form.model_name}@@ -268,17 +266,17 @@ export function Settings() {type="button"onClick={() => applyProviderDefaults()}className="inline-flex shrink-0 items-center gap-2 rounded-md border px-3 py-2 text-sm text-muted-foreground transition hover:bg-muted hover:text-foreground"- title={t.llmUseProviderDefaults}+ title={"Use provider defaults"}><RotateCcw className="h-4 w-4" />- <span className="hidden sm:inline">{t.llmUseProviderDefaults}</span>+ <span className="hidden sm:inline">{"Use provider defaults"}</span></button></div>- <span className={hintClass}>{t.llmModelHint}</span>+ <span className={hintClass}>{"Use the exact model id required by your provider."}</span></label><label className="grid gap-2">- <span className={labelClass}>{t.llmBaseUrl}</span>+ <span className={labelClass}>{"Base URL"}</span><inputvalue={form.base_url}onChange={(event) => setForm({ ...form, base_url: event.target.value })}@@ -290,7 +288,7 @@ export function Settings() {<label className="grid gap-2"><span className={labelClass}>- {selectedProvider?.auth_type === "oauth" ? "OAuth" : t.llmApiKey}+ {selectedProvider?.auth_type === "oauth" ? "OAuth" : "API key"}</span><div className="relative"><KeyRound className="pointer-events-none absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" />@@ -317,7 +315,7 @@ export function Settings() {}}className="h-3.5 w-3.5 accent-primary"/>- {t.llmClearApiKey}+ {"Clear saved API key"}</label>) : null}</div>@@ -328,12 +326,12 @@ export function Settings() {<section className="rounded-lg border bg-card p-5 shadow-sm"><div className="mb-5 flex items-center gap-2"><SlidersHorizontal className="h-4 w-4 text-primary" />- <h2 className="text-base font-semibold">{t.llmGeneration}</h2>+ <h2 className="text-base font-semibold">{"Generation"}</h2></div><div className="grid gap-4"><label className="grid gap-2">- <span className={labelClass}>{t.llmTemperature}</span>+ <span className={labelClass}>{"Temperature"}</span><inputtype="number"min={0}@@ -346,7 +344,7 @@ export function Settings() {</label><label className="grid gap-2">- <span className={labelClass}>{t.llmTimeoutSeconds}</span>+ <span className={labelClass}>{"Timeout seconds"}</span><inputtype="number"min={1}@@ -359,7 +357,7 @@ export function Settings() {</label><label className="grid gap-2">- <span className={labelClass}>{t.llmMaxRetries}</span>+ <span className={labelClass}>{"Max retries"}</span><inputtype="number"min={0}@@ -372,13 +370,13 @@ export function Settings() {</label><label className="grid gap-2">- <span className={labelClass}>{t.llmReasoningEffort}</span>+ <span className={labelClass}>{"Reasoning effort"}</span><selectvalue={form.reasoning_effort}onChange={(event) => setForm({ ...form, reasoning_effort: event.target.value })}className={fieldClass}>- <option value="">{t.llmReasoningOff}</option>+ <option value="">{"Off"}</option><option value="low">low</option><option value="medium">medium</option><option value="high">high</option>@@ -387,7 +385,7 @@ export function Settings() {</label><div className="rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground">- <span className="font-medium text-foreground">{t.llmEnvPath}: </span>+ <span className="font-medium text-foreground">{"Saved to"}: </span><span className="break-all font-mono">{settings.env_path}</span></div>@@ -397,7 +395,7 @@ export function Settings() {className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-70">{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}- {saving ? t.llmSaving : t.llmSaveSettings}+ {saving ? "Saving..." : "Save settings"}</button></div></section>@@ -407,15 +405,15 @@ export function Settings() {<div className="mb-5 space-y-1"><div className="flex items-center gap-2"><Database className="h-4 w-4 text-primary" />- <h2 className="text-base font-semibold">{t.dataSourceSettings}</h2>+ <h2 className="text-base font-semibold">{"Data Source Settings"}</h2></div>- <p className="text-sm text-muted-foreground">{t.dataSourceSettingsDesc}</p>+ <p className="text-sm text-muted-foreground">{"Configure optional market data credentials used by backtests and research agents."}</p></div><div className="grid gap-5 lg:grid-cols-[minmax(0,1.1fr)_minmax(280px,0.9fr)]"><div className="grid gap-4"><label className="grid gap-2">- <span className={labelClass}>{t.tushareToken}</span>+ <span className={labelClass}>{"Tushare token"}</span><div className="relative"><KeyRound className="pointer-events-none absolute left-3 top-2.5 h-4 w-4 text-muted-foreground" /><input@@ -429,7 +427,7 @@ export function Settings() {/></div><div className="flex items-center justify-between gap-3">- <span className={hintClass}>{t.tushareTokenHint}</span>+ <span className={hintClass}>{"Used for China A-share, futures, fund, and macro data. If unset, the project falls back to AKShare where available."}</span><label className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground"><inputtype="checkbox"@@ -440,13 +438,13 @@ export function Settings() {}}className="h-3.5 w-3.5 accent-primary"/>- {t.clearTushareToken}+ {"Clear saved Tushare token"}</label></div></label><div className="rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground">- <span className="font-medium text-foreground">{t.llmEnvPath}: </span>+ <span className="font-medium text-foreground">{"Saved to"}: </span><span className="break-all font-mono">{dataSettings.env_path}</span></div>@@ -456,23 +454,23 @@ export function Settings() {className="inline-flex items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-70">{dataSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}- {dataSaving ? t.llmSaving : t.saveDataSourceSettings}+ {dataSaving ? "Saving..." : "Save data source settings"}</button></div><div className="rounded-md border bg-muted/20 p-4"><div className="mb-3 flex items-center justify-between gap-3">- <span className="text-sm font-medium">{t.baostockStatus}</span>+ <span className="text-sm font-medium">{"BaoStock"}</span><span className={`rounded-full px-2 py-0.5 text-xs ${dataSettings.baostock_supported ? "bg-success/10 text-success" : "bg-warning/10 text-warning"}`}>- {dataSettings.baostock_supported ? t.baostockSupported : t.baostockNotSupported}+ {dataSettings.baostock_supported ? "Loader available" : "No project loader"}</span></div><div className="space-y-2 text-sm text-muted-foreground"><p>{dataSettings.baostock_message}</p><p>{dataSettings.baostock_installed- ? t.baostockPackageInstalled- : t.baostockPackageMissing}+ ? "Python package installed"+ : "Python package not installed"}</p></div></div>