Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(cli): inject a host session id into non-interactive runs

Haozhe Wu6a859902e91b
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 089054615..bdb0058f8 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -979,6 +979,50 @@ def _mandate_proposal_from_tool_result(data: Dict[str, Any]) -> Optional[Dict[st
return _load_full_proposal(match.group(1))
+def _ensure_session_id(title: str, *, session_id: Optional[str] = None) -> str:
+ """Return a host-owned session id, registering the session record if new.
+
+ The research-goal tools are registered unconditionally and resolve their
+ session from the host runtime, so any entry point that calls
+ :func:`_run_agent` without an id makes every goal call fail validation with
+ ``session_id is required`` while the run still reports success (#885).
+
+ Persistence is best effort. ``Session`` populates ``session_id`` on
+ construction, so a store or index failure still yields a usable id rather
+ than falling back to the empty string that caused the bug.
+
+ Args:
+ title: Text used as the session title; truncated for display.
+ session_id: Explicit id to register, for callers that need the same
+ session across repeated invocations. Defaults to a fresh id.
+
+ Returns:
+ A non-empty session id.
+ """
+ from src.session.models import Session, SessionStatus
+ from src.session.store import SessionStore
+
+ session = Session(
+ title=title.strip()[:60] or "untitled",
+ status=SessionStatus.ACTIVE,
+ )
+ if session_id:
+ session.session_id = session_id
+ try:
+ SessionStore(base_dir=SESSIONS_DIR).create_session(session)
+ except Exception: # noqa: BLE001 — an existing or unwritable session must not block the run
+ return session.session_id
+
+ # Index for FTS5 cross-session search, mirroring the interactive REPL.
+ try:
+ from src.session.search import get_shared_index
+
+ get_shared_index().index_session(session.session_id, session.title)
+ except Exception: # noqa: BLE001 — search index is optional
+ pass
+ return session.session_id
+
+
def _run_agent(
prompt: str,
history: Optional[List[Dict]] = None,
@@ -1417,14 +1461,23 @@ def cmd_run(prompt: str, max_iter: int, *, json_mode: bool = False, no_rich: boo
else:
console.print(f"[dim]Prompt:[/dim] {preview}{suffix}\n")
start = time.perf_counter()
+ session_id = _ensure_session_id(prompt)
try:
if json_mode or no_rich:
- result = _run_agent(prompt, max_iter=max_iter, no_rich=no_rich, stream_output=not json_mode)
+ result = _run_agent(
+ prompt,
+ max_iter=max_iter,
+ no_rich=no_rich,
+ stream_output=not json_mode,
+ session_id=session_id,
+ )
else:
dashboard = _RunDashboard(prompt, max_iter)
with Live(dashboard.render(), console=console, refresh_per_second=6, transient=True) as live:
dashboard.live = live
- result = _run_agent(prompt, max_iter=max_iter, dashboard=dashboard)
+ result = _run_agent(
+ prompt, max_iter=max_iter, dashboard=dashboard, session_id=session_id
+ )
dashboard.finish(result, time.perf_counter() - start)
except KeyboardInterrupt:
if json_mode:
@@ -1498,6 +1551,13 @@ def cmd_continue(
trace_dir.mkdir(parents=True, exist_ok=True)
history = _build_history_from_trace(trace_dir)
+ # Continuations of one run share a session so goals and evidence accumulate
+ # across them. A session-backed run_id already *is* a session id (sessions
+ # and their traces share ``SESSIONS_DIR``); a plain run gets a derived id.
+ session_id = _ensure_session_id(
+ prompt,
+ session_id=run_id if session_trace_dir.exists() else f"run-{run_id}",
+ )
if not json_mode and no_rich:
print(f"Continue {run_id}: {prompt[:120]}\n")
if json_mode or no_rich:
@@ -1510,6 +1570,7 @@ def cmd_continue(
max_iter=max_iter,
no_rich=no_rich,
stream_output=not json_mode,
+ session_id=session_id,
)
except KeyboardInterrupt:
if json_mode:
@@ -1542,6 +1603,7 @@ def cmd_continue(
run_dir_override=str(trace_dir),
max_iter=max_iter,
dashboard=dashboard,
+ session_id=session_id,
)
dashboard.finish(result, time.perf_counter() - start)
except KeyboardInterrupt:
@@ -1910,6 +1972,9 @@ def cmd_interactive(max_iter: int) -> None:
history: List[Dict[str, str]] = []
stats = _SessionStats(session_start=time.monotonic())
prompt_session = _create_prompt_session(stats)
+ # Created on the first agent turn so a REPL used only for slash commands
+ # leaves no empty session behind.
+ session_id = ""
while True:
if prompt_session is None:
@@ -1934,11 +1999,19 @@ def cmd_interactive(max_iter: int) -> None:
# Natural language -> agent
start = time.perf_counter()
+ if not session_id:
+ session_id = _ensure_session_id(user_input)
try:
dashboard = _RunDashboard(user_input, max_iter)
with Live(dashboard.render(), console=console, refresh_per_second=6, transient=True) as live:
dashboard.live = live
- result = _run_agent(user_input, history=history[-6:], max_iter=max_iter, dashboard=dashboard)
+ result = _run_agent(
+ user_input,
+ history=history[-6:],
+ max_iter=max_iter,
+ dashboard=dashboard,
+ session_id=session_id,
+ )
dashboard.finish(result, time.perf_counter() - start)
except KeyboardInterrupt:
console.print("\n[yellow]Interrupted[/yellow]")
@@ -2738,7 +2811,9 @@ def cmd_session_chat(session_id: str, max_iter: int) -> None:
_timer = threading.Thread(target=_session_event_timer, args=(spinner,), daemon=True)
_timer.start()
try:
- result = _run_agent(prompt, history=history[-6:], max_iter=max_iter)
+ result = _run_agent(
+ prompt, history=history[-6:], max_iter=max_iter, session_id=session_id
+ )
except KeyboardInterrupt:
console.print("\n[yellow]Interrupted[/yellow]")
continue
diff --git a/agent/cli/main.py b/agent/cli/main.py
index b06b136e7..e6378c470 100644
--- a/agent/cli/main.py
+++ b/agent/cli/main.py
@@ -24,6 +24,7 @@ import os
import sys
import threading
import time
+import uuid
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence
@@ -703,7 +704,10 @@ def _run_one_turn(user_input: str, ctx: InteractiveContext) -> None:
console = get_console()
if ctx.session_id is None:
- ctx.session_id = _new_session(user_input)
+ # Fall back to an unpersisted id: a session-store failure must not strip
+ # the turn of its session, which would fail every research-goal call
+ # with ``session_id is required`` (#885).
+ ctx.session_id = _new_session(user_input) or uuid.uuid4().hex[:12]
_append_message(ctx.session_id or "", "user", user_input)
start = time.perf_counter()
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index 80de23c2e..6b29a5545 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -335,6 +335,36 @@ def _get_goal_store():
return _goal_store
+_mcp_session_id: str | None = None
+
+
+def _resolve_session_id(session_id: str = "") -> str:
+ """Resolve the goal session, defaulting to this server process's session.
+
+ The in-process tool registry injects the host session and keeps
+ ``session_id`` out of its required schema. MCP has no such injection point,
+ so these tools used to mark the id required — asking the model to invent an
+ internal identifier it has no way to know, the opposite contract from the
+ local path (#885). Default instead to one stable id per server process,
+ which is the closest MCP equivalent of a host-owned session, while still
+ honouring an explicit id from a client that tracks its own conversations.
+
+ Args:
+ session_id: Optional client-supplied session id.
+
+ Returns:
+ A non-empty session id.
+ """
+ global _mcp_session_id
+ if cleaned := session_id.strip():
+ return cleaned
+ if _mcp_session_id is None:
+ import uuid
+
+ _mcp_session_id = f"mcp-{uuid.uuid4().hex[:12]}"
+ return _mcp_session_id
+
+
def _json_ok(**payload: Any) -> str:
"""Return a standard MCP JSON success envelope."""
return json.dumps({"status": "ok", **payload}, ensure_ascii=False, indent=2)
@@ -442,8 +472,8 @@ def load_skill(name: str) -> str:
@mcp.tool
def start_research_goal(
- session_id: str,
objective: str,
+ session_id: str = "",
criteria: list[str] | None = None,
ui_summary: str = "",
protocol: str = "thesis_review",
@@ -459,8 +489,9 @@ def start_research_goal(
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.
+ session_id: Optional conversation id. Omit it unless the client tracks
+ its own sessions; this server then uses one id per process.
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.
@@ -472,7 +503,7 @@ def start_research_goal(
try:
clean_criteria = _clean_list(criteria) or _default_goal_criteria()
goal = _get_goal_store().replace_goal(
- session_id=session_id.strip(),
+ session_id=_resolve_session_id(session_id),
objective=objective,
criteria=clean_criteria,
ui_summary=ui_summary,
@@ -490,14 +521,15 @@ def start_research_goal(
@mcp.tool
-def get_research_goal(session_id: str) -> str:
+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.
+ session_id: Optional conversation id. Omit it unless the client tracks
+ its own sessions; this server then uses one id per process.
"""
try:
- snapshot = _get_goal_store().get_current_snapshot(session_id.strip())
+ snapshot = _get_goal_store().get_current_snapshot(_resolve_session_id(session_id))
except ValueError as exc:
return _json_error(str(exc), error_type="validation")
if snapshot is None:
@@ -507,10 +539,10 @@ def get_research_goal(session_id: str) -> str:
@mcp.tool
def add_goal_evidence(
- session_id: str,
goal_id: str,
expected_goal_id: str,
text: str,
+ session_id: str = "",
criterion_id: str | None = None,
claim_id: str | None = None,
evidence_type: str = "evidence",
@@ -534,10 +566,11 @@ def add_goal_evidence(
"""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.
+ session_id: Optional conversation id. Omit it unless the client tracks
+ its own sessions; this server then uses one id per process.
criterion_id: Optional criterion this evidence satisfies.
claim_id: Optional claim this evidence supports or contradicts.
evidence_type: Evidence category, default evidence.
@@ -562,7 +595,7 @@ def add_goal_evidence(
from src.goal import EvidenceInput, StaleGoalError
evidence = _get_goal_store().append_evidence(
- session_id=session_id.strip(),
+ session_id=_resolve_session_id(session_id),
goal_id=goal_id.strip(),
expected_goal_id=expected_goal_id.strip(),
evidence=EvidenceInput(
@@ -602,10 +635,10 @@ def add_goal_evidence(
@mcp.tool
def update_research_goal_status(
- session_id: str,
goal_id: str,
expected_goal_id: str,
status: str,
+ session_id: str = "",
audit: list[dict[str, Any]] | None = None,
recap: str | None = None,
) -> str:
@@ -616,10 +649,11 @@ def update_research_goal_status(
required criterion and verified evidence for satisfied rows.
Args:
- session_id: External conversation/session id.
goal_id: Goal being mutated.
expected_goal_id: Goal id captured before the tool/model turn started.
status: Goal lifecycle status, e.g. complete, cancelled, blocked.
+ session_id: Optional conversation id. Omit it unless the client tracks
+ its own sessions; this server then uses one id per process.
audit: Optional list of criterion audit rows.
recap: Optional concise status recap.
"""
@@ -627,7 +661,7 @@ def update_research_goal_status(
from src.goal import GoalStatus, StaleGoalError
updated = _get_goal_store().update_status(
- session_id=session_id.strip(),
+ session_id=_resolve_session_id(session_id),
goal_id=goal_id.strip(),
expected_goal_id=expected_goal_id.strip(),
status=GoalStatus(status),
diff --git a/agent/tests/test_cli_session_id.py b/agent/tests/test_cli_session_id.py
new file mode 100644
index 000000000..2dd1aefbb
--- /dev/null
+++ b/agent/tests/test_cli_session_id.py
@@ -0,0 +1,173 @@
+"""Regression tests for host session-id injection in non-interactive CLI runs.
+
+Issue #885: ``cmd_run`` registered the research-goal tools but never gave them a
+session, so every goal call failed validation with ``session_id is required``
+while the run still reported success. The same omission affected
+``cmd_continue``, ``cmd_interactive`` and ``cmd_session_chat``.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from cli import _legacy
+from src.agent.trace import TraceWriter
+from src.goal import GoalStore
+from src.tools.goal_tool import StartResearchGoalTool
+
+
+def sessions_dir(tmp_path, monkeypatch) -> Path:
+ """Point the session store at a temp dir so tests never touch agent/sessions."""
+ path = tmp_path / "sessions"
+ path.mkdir()
+ monkeypatch.setattr(_legacy, "SESSIONS_DIR", path)
+ monkeypatch.setattr(_legacy, "RUNS_DIR", tmp_path / "runs")
+ return path
+
+
+def _capture_session_ids(monkeypatch) -> list:
+ """Replace ``_run_agent`` with a spy recording the session id it receives."""
+ seen: list = []
+
+ def fake_run_agent(prompt, history=None, run_dir_override=None, **kwargs):
+ seen.append(kwargs.get("session_id"))
+ return {"status": "success", "run_id": "r1", "run_dir": run_dir_override or "d"}
+
+ monkeypatch.setattr(_legacy, "_run_agent", fake_run_agent)
+ monkeypatch.setattr(_legacy, "_print_json_result", lambda result: None)
+ return seen
+
+
+# ---------------------------------------------------------------------------
+# The defect itself
+# ---------------------------------------------------------------------------
+
+
+def test_goal_tool_fails_without_a_session_id() -> None:
+ """Pin the reported symptom: no host session means every goal call errors."""
+ result = StartResearchGoalTool(default_session_id=None).execute(objective="x")
+ assert '"session_id is required"' in result
+
+
+def test_cmd_run_injects_a_nonempty_session_id(sessions_dir, monkeypatch) -> None:
+ seen = _capture_session_ids(monkeypatch)
+ monkeypatch.setattr(_legacy, "run_preflight", lambda console: [], raising=False)
+
+ assert _legacy.cmd_run("backtest SPY", 5, json_mode=True) == _legacy.EXIT_SUCCESS
+
+ assert len(seen) == 1
+ assert seen[0]
+
+
+def test_injected_session_id_makes_the_goal_tool_work(sessions_dir, tmp_path) -> None:
+ """The end-to-end point of the fix: goals resolve instead of erroring."""
+ session_id = _legacy._ensure_session_id("backtest SPY")
+ store = GoalStore(db_path=tmp_path / "goals.db")
+
+ result = StartResearchGoalTool(default_session_id=session_id, store=store).execute(
+ objective="Backtest a 20/50-day moving average crossover on SPY"
+ )
+
+ assert '"status": "ok"' in result
+ assert "session_id is required" not in result
+
+
+# ---------------------------------------------------------------------------
+# _ensure_session_id contract
+# ---------------------------------------------------------------------------
+
+
+def test_ensure_session_id_persists_a_session_record(sessions_dir) -> None:
+ session_id = _legacy._ensure_session_id("a prompt used as the title")
+
+ assert (sessions_dir / session_id / "session.json").exists()
+
+
+def test_ensure_session_id_survives_an_unwritable_store(sessions_dir, monkeypatch) -> None:
+ """Persistence is best effort — a store failure must not restore the bug."""
+
+ class _Boom:
+ def __init__(self, *a, **kw) -> None:
+ raise OSError("disk gone")
+
+ monkeypatch.setattr("src.session.store.SessionStore", _Boom)
+
+ assert _legacy._ensure_session_id("prompt")
+
+
+def test_ensure_session_id_honours_an_explicit_id(sessions_dir) -> None:
+ assert _legacy._ensure_session_id("t", session_id="run-abc") == "run-abc"
+
+
+def test_ensure_session_id_is_idempotent_for_a_known_id(sessions_dir) -> None:
+ """Re-registering an existing session returns the id rather than raising."""
+ first = _legacy._ensure_session_id("t", session_id="run-abc")
+ second = _legacy._ensure_session_id("t", session_id="run-abc")
+
+ assert first == second == "run-abc"
+
+
+# ---------------------------------------------------------------------------
+# The other three entry points
+# ---------------------------------------------------------------------------
+
+
+def test_cmd_continue_reuses_one_session_across_continuations(
+ sessions_dir, monkeypatch
+) -> None:
+ """Goals must accumulate across continuations, so the id has to be stable."""
+ trace_dir = sessions_dir / "session-1"
+ writer = TraceWriter(trace_dir)
+ writer.write({"type": "start", "prompt": "q"})
+ writer.write({"type": "answer", "content": "a"})
+ writer.close()
+
+ seen = _capture_session_ids(monkeypatch)
+
+ _legacy.cmd_continue("session-1", "first", 5, json_mode=True)
+ _legacy.cmd_continue("session-1", "second", 5, json_mode=True)
+
+ assert seen[0]
+ assert seen[0] == seen[1]
+ # A session-backed run_id already *is* a session id, so it is used directly.
+ assert seen[0] == "session-1"
+
+
+def test_cmd_continue_derives_an_id_for_a_plain_run(sessions_dir, tmp_path, monkeypatch) -> None:
+ runs_dir = tmp_path / "runs"
+ trace_dir = runs_dir / "run-x"
+ writer = TraceWriter(trace_dir)
+ writer.write({"type": "start", "prompt": "q"})
+ writer.close()
+
+ seen = _capture_session_ids(monkeypatch)
+
+ _legacy.cmd_continue("run-x", "follow up", 5, json_mode=True)
+
+ assert seen == ["run-run-x"]
+
+
+def test_cmd_session_chat_passes_the_session_it_was_given(
+ sessions_dir, monkeypatch
+) -> None:
+ """The id was already in scope as a parameter and simply was not forwarded."""
+ from src.session.models import Session
+ from src.session.store import SessionStore
+
+ store = SessionStore(base_dir=sessions_dir)
+ session = Session(title="existing")
+ store.create_session(session)
+
+ seen = _capture_session_ids(monkeypatch)
+ replies = iter(["analyse AAPL", "q"])
+ monkeypatch.setattr(_legacy, "_read_input", lambda _s: next(replies))
+ monkeypatch.setattr(_legacy, "_create_prompt_session", lambda _stats: None)
+ monkeypatch.setattr(_legacy, "_print_status_bar", lambda _stats: None)
+ monkeypatch.setattr(_legacy, "_print_result", lambda *a, **kw: None)
+
+ _legacy.cmd_session_chat(session.session_id, 5)
+
+ assert seen == [session.session_id]
diff --git a/agent/tests/test_mcp_goal_session_contract.py b/agent/tests/test_mcp_goal_session_contract.py
new file mode 100644
index 000000000..e71b050be
--- /dev/null
+++ b/agent/tests/test_mcp_goal_session_contract.py
@@ -0,0 +1,84 @@
+"""The MCP goal tools must not ask the model to invent a session id.
+
+Issue #885, second half: the in-process tool registry injects the host session
+and keeps ``session_id`` optional, while the MCP entry points declared it
+required. The two paths declared opposite contracts, and on the MCP path the
+model was asked for an internal identifier it has no way to know.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import sys
+from pathlib import Path
+
+import pytest
+
+GOAL_TOOLS = (
+ "start_research_goal",
+ "get_research_goal",
+ "add_goal_evidence",
+ "update_research_goal_status",
+)
+
+
[email protected](scope="module")
+def mcp_server():
+ """Import agent/mcp_server.py without executing main()."""
+ agent_dir = Path(__file__).resolve().parent.parent
+ if str(agent_dir) not in sys.path:
+ sys.path.insert(0, str(agent_dir))
+ return importlib.import_module("mcp_server")
+
+
+def tool_parameters(mcp_server) -> dict:
+ tools = asyncio.run(mcp_server.mcp.list_tools())
+ return {t.name: t.parameters for t in tools}
+
+
[email protected]("name", GOAL_TOOLS)
+def test_session_id_is_not_a_required_argument(name, tool_parameters) -> None:
+ params = tool_parameters[name]
+ assert "session_id" in params["properties"], f"{name} dropped session_id entirely"
+ assert "session_id" not in params.get("required", [])
+
+
+def test_the_other_arguments_stay_required(tool_parameters) -> None:
+ """Making session_id optional must not loosen the real inputs."""
+ assert tool_parameters["start_research_goal"]["required"] == ["objective"]
+ assert set(tool_parameters["update_research_goal_status"]["required"]) == {
+ "goal_id",
+ "expected_goal_id",
+ "status",
+ }
+
+
+def test_resolve_session_id_is_stable_within_a_process(mcp_server, monkeypatch) -> None:
+ monkeypatch.setattr(mcp_server, "_mcp_session_id", None)
+
+ first = mcp_server._resolve_session_id()
+ second = mcp_server._resolve_session_id("")
+
+ assert first and first == second
+ assert first.startswith("mcp-")
+
+
+def test_resolve_session_id_honours_an_explicit_client_id(mcp_server) -> None:
+ assert mcp_server._resolve_session_id(" conv-42 ") == "conv-42"
+
+
+def test_start_research_goal_works_without_a_session_id(
+ mcp_server, tmp_path, monkeypatch
+) -> None:
+ """The end-to-end point: an omitted id must not become a validation error."""
+ from src.goal import GoalStore
+
+ monkeypatch.setattr(mcp_server, "_goal_store", GoalStore(db_path=tmp_path / "g.db"))
+ monkeypatch.setattr(mcp_server, "_mcp_session_id", None)
+
+ result = mcp_server.start_research_goal(objective="Analyse SPY drawdowns")
+
+ assert '"status": "ok"' in result
+ assert "session_id is required" not in result