"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: close the gaps an independent pre-push audit found
Haozhe Wu4df1862eccb7
diff --git a/agent/backtest/engines/china_a.py b/agent/backtest/engines/china_a.pyindex 10664196d..0b5f73cb5 100644--- a/agent/backtest/engines/china_a.py+++ b/agent/backtest/engines/china_a.py@@ -154,7 +154,11 @@ def _blocked_by_limit(if band is None:return Falselower, upper = band- fill = engine.prospective_fill_price(bar, direction)+ # BaseEngine books a close with the OPPOSITE of the position's direction,+ # so slippage moves the price the other way. Checking the raw open here+ # would approve a fill that is then booked outside the band.+ fill_direction = -(position_direction or 1) if direction == 0 else direction+ fill = engine.prospective_fill_price(bar, fill_direction)if fill is None:return Falsediff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 2ae418d21..5597e12bc 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -989,7 +989,7 @@ class AgentLoop:final_reason: str | None = Noneif self._cancel_event.is_set():final_reason = "cancelled by user"- state_store.mark_failure(run_dir, final_reason)+ state_store.mark_cancelled(run_dir, final_reason)final_status = "cancelled"elif content_filter_circuit_breaker:final_reason = (diff --git a/agent/src/agent/trace.py b/agent/src/agent/trace.pyindex 70b3f9654..7b73e8c05 100644--- a/agent/src/agent/trace.py+++ b/agent/src/agent/trace.py@@ -217,29 +217,51 @@ class TraceWriter:entry[f"{field}_size"] = len(value)def _write_sidecar_durable(self, path: Path, value: str) -> None:- """Atomically and durably write a sidecar blob.+ """Atomically write a sidecar blob, durably where the filesystem allows.- Write sequence: temp file in same dir -> fsync -> ``os.replace`` ->- parent-directory fsync. A crash at any step leaves either no sidecar- or a complete one, never a partial write under the final name.+ Write sequence: temp file in the same directory -> write every byte ->+ fsync -> ``os.replace`` -> parent-directory fsync. The rename is what+ makes it atomic: a crash leaves either no sidecar or a complete one,+ never a partial write under the final name. Because the blob is fully+ renamed into place before the caller writes the record that points at+ it, a record never references a sidecar that is not on disk.++ Durability against a HOST crash additionally needs fsync. Where fsync+ is unsupported the error is logged once and the write still completes:+ the sidecar is present and readable, only its survival across a power+ loss is not guaranteed. Failing the run instead would lose the trace+ outright, which is the worse outcome for a diagnostic artifact.Args:path: Final sidecar path.value: Full text to persist.Raises:- OSError: When the temp file cannot be written or renamed. The+ OSError: When the blob cannot be written or renamed at all. Thecaller must not write the referencing record in that case."""tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)try:- os.write(fd, value.encode("utf-8"))+ payload = value.encode("utf-8")+ written = 0+ # os.write may write fewer bytes than requested; a single call can+ # silently truncate a large sidecar.+ while written < len(payload):+ written += os.write(fd, payload[written:])try:os.fsync(fd)except OSError as exc:self._warn_fsync_failure(exc, tmp)- finally:+ except BaseException:+ os.close(fd)+ # Never leave a half-written temp file behind for the next run.+ try:+ os.unlink(tmp)+ except OSError:+ pass+ raise+ else:os.close(fd)os.replace(tmp, path)self._fsync_dir(path.parent)diff --git a/agent/src/api/runs_routes.py b/agent/src/api/runs_routes.pyindex bf7e62533..39fca62b1 100644--- a/agent/src/api/runs_routes.py+++ b/agent/src/api/runs_routes.py@@ -81,8 +81,8 @@ def _build_response_from_run_dir(state_status = str(state_data.get("status") or "").lower()if state_status == "success":response.status = "success"- elif state_status == "failed":- response.status = "failed"+ elif state_status in {"failed", "cancelled"}:+ response.status = state_statusresponse.reason = state_data.get("reason", "")else:response.status = state_status or "unknown"diff --git a/agent/src/core/state.py b/agent/src/core/state.pyindex 83813a40f..305a6705d 100644--- a/agent/src/core/state.py+++ b/agent/src/core/state.py@@ -63,6 +63,19 @@ class RunStateStore:"""self._write_json(run_dir / "state.json", {"status": "failed", "reason": reason})+ def mark_cancelled(self, run_dir: Path, reason: str = "cancelled by user") -> None:+ """Mark the run as cancelled by the user.++ Distinct from a failure so the run artifact agrees with the session+ transcript: a user stop is not an outage, and reporting it as one made+ the Reports view contradict the chat history.++ Args:+ run_dir: Run directory.+ reason: Cancellation reason.+ """+ self._write_json(run_dir / "state.json", {"status": "cancelled", "reason": reason})+@staticmethoddef _write_json(path: Path, data: Any) -> None:# Write + fsync so a crash can't leave a truncated/empty state.json.diff --git a/agent/src/openbb_bridge/adapter.py b/agent/src/openbb_bridge/adapter.pyindex cc13e08a1..9c390db03 100644--- a/agent/src/openbb_bridge/adapter.py+++ b/agent/src/openbb_bridge/adapter.py@@ -48,7 +48,7 @@ _ROLE_AI = "ai"# replayed as turns; their payload is folded into the context prefix instead._ROLE_TO_VIBE = {_ROLE_HUMAN: "user", _ROLE_AI: "assistant"}-_TERMINAL_EVENTS = {"attempt.completed", "attempt.failed"}+_TERMINAL_EVENTS = {"attempt.completed", "attempt.failed", "attempt.cancelled"}# Session titles surface in the Vibe-Trading UI; keep them short but identifiable._TITLE_MAX_CHARS = 48@@ -185,6 +185,14 @@ class OpenBBQueryAdapter:yield message_chunk(text=f"The agent run failed: {error}")return+ if event_type == "attempt.cancelled":+ # A stop is terminal too; without this the stream would keep+ # emitting heartbeats until the client gave up.+ yield reasoning_step(message="Run cancelled.", event_type="WARNING")+ if not saw_text:+ yield message_chunk(text="The agent run was cancelled.")+ return+# attempt.completed: only send the summary if nothing was streamed.if not saw_text:summary = data.get("summary") or ""diff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.pyindex bbfe38875..e87b91722 100644--- a/agent/src/providers/llm.py+++ b/agent/src/providers/llm.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport loggingimport os+from urllib.parse import urlparseimport refrom collections.abc import Sequencefrom importlib import import_module@@ -718,7 +719,23 @@ def _supports_top_level_reasoning_effort(provider: str, caps_name: str) -> bool:the capability name check drops model-inferred providers (e.g. provider``openai`` with a ``deepseek-*`` model resolves to DeepSeek)."""- return caps_name == "openai" and provider.strip().lower() in {"", "openai"}+ if caps_name != "openai" or provider.strip().lower() not in {"", "openai"}:+ return False+ # A base-URL override points the OpenAI client at some other gateway+ # (Ollama, LiteLLM, a corporate proxy). Those speak the OpenAI wire format+ # but need not accept this field, so the label alone is not enough.+ try:+ base_url = (+ get_llm_credentials("openai", get_env_config().llm.langchain_model_name)+ .get("base_url")+ or ""+ ).strip()+ except Exception: # noqa: BLE001 - a credential lookup must not break the check+ return False+ if not base_url:+ return True+ host = urlparse(base_url if "//" in base_url else f"https://{base_url}").hostname or ""+ return host.lower() in {"api.openai.com", "openai.com"}def provider_diagnostics() -> dict[str, Any]:diff --git a/agent/src/session/service.py b/agent/src/session/service.pyindex 8cdd8d2ab..9cf3269e8 100644--- a/agent/src/session/service.py+++ b/agent/src/session/service.py@@ -76,6 +76,12 @@ class SessionService:# concurrency gate, so in-flight sessions are tracked separately and# reserved synchronously in send_message.self._active_loops: Dict[str, "AgentLoop"] = {}+ # Task handles are kept from the moment the run is scheduled, so a run+ # still building its registry can be cancelled. _active_loops only+ # exists once construction finished, which is far too late to be the+ # only cancellation route: a hung discovery would otherwise hold the+ # claim forever and lock the session behind 409.+ self._active_tasks: Dict[str, "asyncio.Task"] = {}self._inflight: set[str] = set()self._inflight_lock = threading.Lock()self._search_index = get_shared_index()@@ -188,7 +194,10 @@ class SessionService:self.store.update_session(session)self.event_bus.emit(session_id, "attempt.created", {"attempt_id": attempt.attempt_id, "prompt": content})- asyncio.create_task(self._run_attempt(session, attempt, include_shell_tools=include_shell_tools))+ task = asyncio.create_task(+ self._run_attempt(session, attempt, include_shell_tools=include_shell_tools)+ )+ self._active_tasks[session_id] = task# _run_attempt now owns the claim and releases it in its finally.handed_off = Truereturn {"message_id": message.message_id, "attempt_id": attempt.attempt_id}@@ -210,18 +219,29 @@ class SessionService:Whether cancellation succeeded. True means an active loop existed and received a cancel signal."""loop = self._active_loops.get(session_id)- if loop is None:- return False- loop.cancel()- return True+ if loop is not None:+ loop.cancel()+ return True+ # No loop yet: the run is still building its registry. Cancel the task+ # itself so the claim is released instead of stranding the session.+ task = self._active_tasks.get(session_id)+ if task is not None and not task.done():+ task.cancel()+ return True+ return Falseasync def _run_attempt(self, session: Session, attempt: Attempt, *, include_shell_tools: bool = False) -> None:- """Execute an Attempt in the background."""- attempt.mark_running()- self.store.update_attempt(attempt)- self.event_bus.emit(session.session_id, "attempt.started", {"attempt_id": attempt.attempt_id})+ """Execute an Attempt in the background.+ The whole body runs under try/finally: this coroutine owns the+ in-flight claim taken in :meth:`send_message`, and a failure anywhere —+ including in the pre-run bookkeeping below — must not leave the session+ permanently busy.+ """try:+ attempt.mark_running()+ self.store.update_attempt(attempt)+ self.event_bus.emit(session.session_id, "attempt.started", {"attempt_id": attempt.attempt_id})messages = self.store.get_messages(session.session_id)result = await self._run_with_agent(attempt,@@ -273,12 +293,25 @@ class SessionService:"summary": attempt.summary, "error": attempt.error, "run_dir": attempt.run_dir},)+ except asyncio.CancelledError:+ # cancel_current() cancels this task when the run has not reached+ # its AgentLoop yet. CancelledError is a BaseException, so it would+ # slip past the handler below and leave the attempt stuck RUNNING.+ attempt.mark_cancelled(reason="cancelled by user")+ self.store.update_attempt(attempt)+ self.event_bus.emit(+ session.session_id,+ "attempt.cancelled",+ {"attempt_id": attempt.attempt_id, "status": attempt.status.value},+ )+ raiseexcept Exception as exc:attempt.mark_failed(error=str(exc))self.store.update_attempt(attempt)self.event_bus.emit(session.session_id, "attempt.failed", {"attempt_id": attempt.attempt_id, "error": str(exc)})finally:# The only release path for the claim taken in send_message.+ self._active_tasks.pop(session.session_id, None)self._release_session(session.session_id)async def _run_with_agent(diff --git a/agent/src/tools/redaction.py b/agent/src/tools/redaction.pyindex a874b6369..49350a1ee 100644--- a/agent/src/tools/redaction.py+++ b/agent/src/tools/redaction.py@@ -325,7 +325,10 @@ def redact_payload(obj: Any, *, sink: str = ARGUMENTS_SINK) -> Any:}if isinstance(obj, list):return [redact_payload(item, sink=sink) for item in obj]- if sink == RESULT_SINK and isinstance(obj, str):+ if isinstance(obj, str):+ # Both sinks: key-based classification cannot see a credential embedded+ # inside an otherwise-benign value, e.g. a bearer token in a shell+ # command argument or in a broker error string bound for the ledger.return redact_text(obj)return obj@@ -400,6 +403,22 @@ def _sub_credential_pair(match: re.Match[str]) -> str:)+#: Credential formats recognised WITHOUT a key label. Key-based and+#: ``key=value`` matching both miss a bare token pasted into shell output or an+#: error string, so the well-known issuer prefixes are matched on shape. Each+#: alternative is anchored and length-bounded so ordinary prose cannot match.+_TEXT_TOKEN_PATTERN = re.compile(+ r"(?<![A-Za-z0-9_-])("+ r"sk-[A-Za-z0-9_-]{20,}" # OpenAI / Anthropic style+ r"|gh[pousr]_[A-Za-z0-9]{30,}" # GitHub PAT family+ r"|xox[baprs]-[A-Za-z0-9-]{10,}" # Slack+ r"|AKIA[0-9A-Z]{16}" # AWS access key id+ r"|pypi-[A-Za-z0-9_-]{16,}" # PyPI upload token+ r"|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}" # JWT+ r")(?![A-Za-z0-9_-])"+)++def redact_text(text: object) -> str:"""Scrub credential-shaped values from a free-form string.@@ -425,7 +444,9 @@ def redact_text(text: object) -> str:if not s:return ss = _TEXT_BEARER_PATTERN.sub(r"\g<scheme> " + _REDACTED, s)- return _TEXT_KV_PATTERN.sub(_sub_credential_pair, s)+ s = _TEXT_KV_PATTERN.sub(_sub_credential_pair, s)+ # Bare tokens with no key label in front of them.+ return _TEXT_TOKEN_PATTERN.sub(_REDACTED, s)def redact_tool_result(result: object) -> str:diff --git a/agent/tests/test_price_limit_lookahead.py b/agent/tests/test_price_limit_lookahead.pyindex c7acf361e..fc8bbd1c0 100644--- a/agent/tests/test_price_limit_lookahead.py+++ b/agent/tests/test_price_limit_lookahead.py@@ -151,3 +151,39 @@ def test_futures_prefer_pre_settle_over_pre_close() -> None:# 132 and would wrongly allow this open.bar = pd.Series({"open": 110.0, "close": 101.0, "pre_settle": 100.0, "pre_close": 120.0})assert engine.can_execute("IF2406.CFFEX", 1, bar) is False+++# --------------------------------------------------------------------------- #+# The booked price, not the raw open, must be the one tested+# --------------------------------------------------------------------------- #++[email protected]("engine, symbol, band", _equity_cases())+def test_close_is_judged_on_the_price_actually_booked(engine, symbol, band) -> None:+ """A close is booked with the opposite of the position direction.++ Testing the raw open would approve a fill whose booked sell price, after+ slippage, lands outside the band.+ """+ engine.positions[symbol] = Position(symbol, 1, _BASE, pd.Timestamp("2025-06-09"), 100.0)+ lower = _BASE * (1 - band)+ just_inside = lower * 1.0005 # inside the band before slippage...+ booked = engine.apply_slippage(just_inside, -1) # ...outside it after+ assert booked < lower, "fixture no longer exercises the slippage gap"+ bar = _bar(open_=just_inside, close=_BASE * 0.99)+ bar["trade_date"] = pd.Timestamp("2025-06-10")+ assert engine.can_execute(symbol, 0, bar) is False+++def test_closing_a_short_is_judged_as_a_buy_after_slippage() -> None:+ """Covering a short is booked as a buy, so slippage pushes it UP."""+ engine = ChinaFuturesEngine({})+ engine.positions["IF2406.CFFEX"] = Position(+ "IF2406.CFFEX", -1, _BASE, pd.Timestamp("2025-06-09"), 1.0,+ )+ upper = _BASE * 1.10+ just_inside = upper * 0.9999+ booked = engine.apply_slippage(just_inside, 1)+ assert booked > upper, "fixture no longer exercises the slippage gap"+ bar = _bar(open_=just_inside, close=_BASE * 1.01, base_field="pre_settle")+ assert engine.can_execute("IF2406.CFFEX", 0, bar) is Falsediff --git a/agent/tests/test_redaction_shared.py b/agent/tests/test_redaction_shared.pyindex 2394bb613..8be3cf90c 100644--- a/agent/tests/test_redaction_shared.py+++ b/agent/tests/test_redaction_shared.py@@ -25,6 +25,7 @@ from src.tools.redaction import (RESULT_SINK,is_sensitive_arg,redact_payload,+ redact_text,redact_tool_result,)@@ -420,3 +421,28 @@ def test_write_file_content_argument_never_lands_in_the_trace(tmp_path: Path) ->call_events = [data for event_type, data in events if event_type == "tool_call"]assert call_events, "expected a tool_call event"assert _WRITE_FILE_DOC_SECRET not in json.dumps(call_events, default=str)+++def test_arguments_sink_scrubs_credentials_embedded_in_benign_values() -> None:+ """Key-based classification cannot see a token inside a shell command."""+ args = {"command": 'curl -H "Authorization: Bearer arg-secret-123" https://x'}+ out = redact_payload(args)+ assert "arg-secret-123" not in out["command"]+ assert "curl" in out["command"] and "https://x" in out["command"]+++def test_bare_issuer_tokens_are_scrubbed_without_a_key_label() -> None:+ """A token pasted with no ``key=`` in front of it must still go."""+ for token in (+ "sk-proj-abcdefghijklmnopqrstuvwxyz012345",+ "ghp_" + "a" * 36,+ "xoxb-1234567890-abcdefghij",+ "AKIAIOSFODNN7EXAMPLE",+ ):+ assert token not in redact_text(f"leaked {token} here")+++def test_bare_token_scrub_leaves_ordinary_output_alone() -> None:+ """Short sk-prefixed words and usage counters are not credentials."""+ text = "tokens: 1204 in / 318 out, sk-ok, account 12345"+ assert redact_text(text) == textdiff --git a/agent/tests/test_session_service_lifecycle.py b/agent/tests/test_session_service_lifecycle.pyindex 361a13e18..6eb7b550b 100644--- a/agent/tests/test_session_service_lifecycle.py+++ b/agent/tests/test_session_service_lifecycle.py@@ -246,3 +246,70 @@ def test_normal_history_is_untouched():]history = SessionService._convert_messages_to_history(messages)assert [m["content"] for m in history] == ["first", "second"]+++def test_claim_is_released_when_pre_run_bookkeeping_fails(tmp_path, monkeypatch):+ """A failure before the agent even starts must not brick the session.++ mark_running/update_attempt/emit used to run outside the try, so a disk+ error there stranded the claim and every later send returned 409.+ """++ async def scenario() -> None:+ service = _service(tmp_path, monkeypatch)+ session = service.create_session(title="bookkeeping")+ _stub_agent(service, monkeypatch, {"status": "success", "content": "ok"})++ original = service.store.update_attempt+ calls = {"n": 0}++ def _fail_first(attempt):+ calls["n"] += 1+ if calls["n"] == 1:+ raise OSError("no space left on device")+ return original(attempt)++ monkeypatch.setattr(service.store, "update_attempt", _fail_first)++ await service.send_message(session.session_id, "one")+ for _ in range(100):+ await asyncio.sleep(0.01)+ if session.session_id not in service._inflight:+ break+ assert session.session_id not in service._inflight+ # And the session is usable again.+ monkeypatch.setattr(service.store, "update_attempt", original)+ assert await service.send_message(session.session_id, "two")++ asyncio.run(scenario())+++def test_cancel_before_the_agent_loop_exists_releases_the_claim(tmp_path, monkeypatch):+ """cancel_current must work while the registry is still being built.++ _active_loops is only populated once construction finishes, so a run that+ hangs earlier (e.g. MCP discovery) previously held the claim forever.+ """++ async def scenario() -> None:+ service = _service(tmp_path, monkeypatch)+ session = service.create_session(title="hung")+ never = asyncio.Event()+ _stub_agent(service, monkeypatch, {"status": "success"}, gate=never)++ await service.send_message(session.session_id, "one")+ await asyncio.sleep(0.02)+ assert session.session_id in service._inflight+ assert service.cancel_current(session.session_id) is True++ for _ in range(100):+ await asyncio.sleep(0.01)+ if session.session_id not in service._inflight:+ break+ assert session.session_id not in service._inflight++ stored = service.store.get_session(session.session_id)+ attempt = service.store.get_attempt(session.session_id, stored.last_attempt_id)+ assert attempt.status == AttemptStatus.CANCELLED++ asyncio.run(scenario())diff --git a/agent/tests/test_trace_writer.py b/agent/tests/test_trace_writer.pyindex c524c87eb..64e576bc9 100644--- a/agent/tests/test_trace_writer.py+++ b/agent/tests/test_trace_writer.py@@ -265,3 +265,45 @@ def test_record_never_references_missing_sidecar_on_crash(assert _raw_entries(tmp_path) == []assert list((tmp_path / "tool-results").glob("*.txt")) == []+++def test_sidecar_survives_a_partial_write(tmp_path, monkeypatch):+ """os.write can write fewer bytes than requested; the blob must still be whole."""+ import os as _os++ real_write = _os.write+ state = {"first": True}++ def _short_write(fd, data):+ if state["first"] and len(data) > 16:+ state["first"] = False+ return real_write(fd, data[:16])+ return real_write(fd, data)++ monkeypatch.setattr(trace_mod.os, "write", _short_write)++ writer = TraceWriter(tmp_path)+ body = "x" * 5000+ entry: dict = {}+ writer._attach_text_field(entry, field="result", value=body, offload_kind="result",+ threshold=10, offload_dir_name="results")+ writer.write(entry)++ sidecar = tmp_path / entry["result_path"]+ assert sidecar.read_text(encoding="utf-8") == body+++def test_failed_sidecar_write_leaves_no_temp_file(tmp_path, monkeypatch):+ """A write error must not strand a half-written temp blob."""++ def _boom(fd, data):+ raise OSError("disk exploded")++ monkeypatch.setattr(trace_mod.os, "write", _boom)+ writer = TraceWriter(tmp_path)+ with pytest.raises(OSError):+ writer._attach_text_field({}, field="result", value="y" * 5000,+ offload_kind="result", threshold=10,+ offload_dir_name="results")+ leftovers = list((tmp_path / "results").glob(".*tmp"))+ assert leftovers == []diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsxindex ef43e3223..33b10b9b5 100644--- a/frontend/src/pages/RunDetail.tsx+++ b/frontend/src/pages/RunDetail.tsx@@ -18,6 +18,7 @@ import {Loader2,ShieldCheck,XCircle,+ CircleSlash,} from "lucide-react";import { toast } from "sonner";import { cn } from "@/lib/utils";@@ -196,6 +197,7 @@ export function RunDetail() {);const ok = run.status === "success";+ const cancelled = run.status === "cancelled";async function loadChartSymbol(symbol: string,@@ -301,6 +303,11 @@ export function RunDetail() {<CheckCircle2 className="h-5 w-5 text-success" aria-hidden="true" /><span className="sr-only">{t("swarm.status.completed")}</span></>+ ) : cancelled ? (+ <>+ <CircleSlash className="h-5 w-5 text-muted-foreground" aria-hidden="true" />+ <span className="sr-only">{t("swarm.status.cancelled")}</span>+ </>) : (<><XCircle className="h-5 w-5 text-danger" aria-hidden="true" />