"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(agent): harden agent run reliability
Will Liaofc2700f03b96
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.pyindex 8b695207d..959c9224d 100644--- a/agent/src/agent/grounding.py+++ b/agent/src/agent/grounding.py@@ -79,7 +79,7 @@ _CSV_DATE_COLUMNS = {"date", "datetime", "trade_date", "timestamp", "index"}# Filename -> symbol mapping for run-dir CSVs. The bash workaround writes each# series with a filesystem-safe stem: ``BYN_V.csv`` for ``BYN.V``, ``PDI_TO.csv``# for ``PDI.TO``, ``GC_F.csv`` for ``GC=F``.-_CSV_FILENAME_SUFFIX_MAP = (("_V", ".V"), ("_TO", ".TO"), ("_F", "=F"))+_CSV_FILENAME_SUFFIX_MAP = (("_V", ".V"), ("_TO", ".TO"), ("_F", "=F"), ("_US", ".US"))# Only ``get_market_data`` returns bars whose columns are already the canonical# OHLC field names. Every other market-sensitive tool nests its quote somewhere,@@ -196,9 +196,12 @@ _DATE_RE = re.compile(r"\b(?:19|20)\d{2}[-/]\d{1,2}[-/]\d{1,2}\b")# A year-less "8/5" is how a trading day is written in running prose, and it# contributed 8 and 5 as candidate prices (#983). The month and day ranges are# bounded, and both sides are fenced off from a longer slash run, so the window-# enumeration "20/50/200-day" cannot be mistaken for a date.+# enumeration "20/50/200-day" cannot be mistaken for a date. Reports also write+# the same day as "08-10(一)" or "08-10盘中", so the dash form is masked with+# the same bounds and fencing; a dash is never part of a longer digit run._SHORT_DATE_RE = re.compile(r"(?<![\d/])(?:0?[1-9]|1[0-2])/(?:0?[1-9]|[12]\d|3[01])(?![\d/])"+ r"|(?<![\d-])(?:0?[1-9]|1[0-2])-(?:0?[1-9]|[12]\d|3[01])(?![\d-])")# A percentage range masks only its upper bound through the "%" tail check# below, because the sign touches the second number: "1–2%" left 1 behind@@ -378,6 +381,28 @@ _PROSPECTIVE_LEVEL_RE = re.compile(# parentheses are deliberately not separators: an explicit derivation such as# "(8.5 - 7.9) / 2" must stay in one segment for the formula check._CLAUSE_SEPARATOR_RE = re.compile(r"[,,;;。、\n()【】]")+++# An order-level claim names a resting or desired order, not an observed+# quote: "两档 GTC (100 @ $3.50 / 100 @ $4.00) 均未触发 (周高 $3.42 < $3.50)"+# asserts nothing about what the instrument traded at - the limit prices are+# prospective levels (like targets/stops) and the share counts are quantities.+# Without this mask the gate reported 100, 3.5 and 4.0 as price claims+# conflicting with the observed OHLC range and rejected a correct draft.+# The @-price branch requires a leading quantity so a bare "@" (rare in+# trading reports) stays checked; the keyword branch covers labelled orders.+_ORDER_LEVEL_RE = re.compile(+ r"(?:"+ # (a) quantity (optional unit) @ price: "100 @ $3.50", "100 股 @ 4.00"+ r"(?:\d[\d,]*(?:\.\d+)?)\s*(?:股|手|张|份|shares?|units?)?\s*@\s*"+ + _CURRENCY_TOKEN + r"\s*[-+]?\d[\d,]*(?:\.\d+)?"+ r"|"+ # (b) order keyword + price: 挂单/限价单/限价/委托/订单/买入价/卖出价/GTC+ r"(?:挂单|限价单|限价|委托|订单|买入价|卖出价|GTC(?:单)?)\s*(?:为|是|至|到|on|at|=)?\s*[::]?\s*"+ + _CURRENCY_TOKEN + r"\s*[-+]?\d[\d,]*(?:\.\d+)?"+ r")",+ re.IGNORECASE,+)# The ASCII comma both separates clauses and groups thousands, and the clause# split ran first: "收盘价 ¥1,309.22" became a clause ending in "¥1", whose 1 was# compared against the observed 1300.01–1363.35 range and rejected as a@@ -513,9 +538,10 @@ def _symbol_from_csv_filename(stem: str) -> str | None:"""Map a run-dir CSV stem back to a canonical project symbol.The bash workaround writes filesystem-safe stems: ``BYN_V.csv`` -> ``BYN.V``,- ``PDI_TO.csv`` -> ``PDI.TO``, ``GC_F.csv`` -> ``GC=F``. A stem without a- recognized suffix (e.g. a bare US name ``AAPL``) maps to None because the- project convention requires an explicit venue suffix.+ ``PDI_TO.csv`` -> ``PDI.TO``, ``GC_F.csv`` -> ``GC=F``, ``INTC_US.csv`` ->+ ``INTC.US``. A stem without a recognized suffix (e.g. a bare US name+ ``AAPL``) maps to None because the project convention requires an explicit+ venue suffix.Args:stem: CSV filename without the ``.csv`` extension.@@ -584,9 +610,47 @@ def _coerce_csv_number(value: Any) -> int | float | None:_YEARLESS_CLAIM_DATE_RE = re.compile(r"^(0?[1-9]|1[0-2])\s*[-/月]\s*(0?[1-9]|[12]\d|3[01])\s*[日号]?$")+# Two-digit day alternatives are tried before a bare digit so an+# unanchored prefix match consumes the full day ("10" of "08-10(一)")+# instead of stopping at "1".+_ISO_CLAIM_DATE_PREFIX_RE = re.compile(+ r"^\s*((?:19|20)\d{2})\s*[-/]\s*(0?[1-9]|1[0-2])\s*[-/]\s*([12]\d|3[01]|0?[1-9])"+)+_YEARLESS_CLAIM_DATE_PREFIX_RE = re.compile(+ r"^\s*(0?[1-9]|1[0-2])\s*[-/月]\s*([12]\d|3[01]|0?[1-9])"+)_ISO_TIMESTAMP_RE = re.compile(r"^(\d{4})-(\d{1,2})-(\d{1,2})")+def _claim_date_tuple(date_value: str) -> tuple[int, int] | None:+ """Extract the (month, day) named by a report-style date cell.++ Reports routinely annotate a trading day: the date column reads+ ``08-10(一)``, ``08-10(周一)盘中`` or ``08-10盘中`` rather than the bare+ ``08-10`` the strict full-cell matchers accept. Any leading month-day (or+ full ISO date) prefix is therefore accepted so such a claim still compares+ against the matching evidence row instead of being reported as+ unevidenced.++ Args:+ date_value: Date cell as written in the answer.++ Returns:+ The (month, day) tuple, or None when no date prefix is present.+ """+ claim = (date_value or "").strip()+ match = _YEARLESS_CLAIM_DATE_RE.match(claim)+ if match:+ return (int(match.group(1)), int(match.group(2)))+ match = _ISO_CLAIM_DATE_PREFIX_RE.match(claim)+ if match:+ return (int(match.group(2)), int(match.group(3)))+ match = _YEARLESS_CLAIM_DATE_PREFIX_RE.match(claim)+ if match:+ return (int(match.group(1)), int(match.group(2)))+ return None++def _timestamp_matches_claim_date(timestamp: str, date_value: str) -> bool:"""Match an evidence timestamp against the date cell of a claim.@@ -597,11 +661,12 @@ def _timestamp_matches_claim_date(timestamp: str, date_value: str) -> bool:evidence while that evidence sat right there (#983: 79 such rejections inone run, every value inside the observed range).- A year-less date is matched on month and day. That is deliberately looser:- where the evidence spans more than one year, such a claim matches the same- calendar day in either. Matching the wrong year is a smaller failure than- matching nothing, but it is a real one, so the caller still compares the- value against every record that matched rather than trusting the date.+ A year-less date is matched on month and day, and a date cell may carry+ weekday or intraday annotations (``08-10(一)``, ``08-10盘中``) whose+ leading month-day is still recognized. Matching the wrong year is a+ smaller failure than matching nothing, but it is a real one, so the+ caller still compares the value against every record that matched rather+ than trusting the date.Args:timestamp: Evidence timestamp, normally ISO ``YYYY-MM-DD``.@@ -616,14 +681,11 @@ def _timestamp_matches_claim_date(timestamp: str, date_value: str) -> bool:return Falseif stamp.startswith(claim):return True- yearless = _YEARLESS_CLAIM_DATE_RE.match(claim)+ claim_tuple = _claim_date_tuple(claim)iso = _ISO_TIMESTAMP_RE.match(stamp)- if not yearless or not iso:+ if claim_tuple is None or not iso:return False- return (int(iso.group(2)), int(iso.group(3))) == (- int(yearless.group(1)),- int(yearless.group(2)),- )+ return (int(iso.group(2)), int(iso.group(3))) == claim_tupledef _price_field_for_path(path: str) -> str | None:@@ -1145,6 +1207,8 @@ class GroundingLedger:lines.append(f"- {issue.get('message', issue.get('code', 'grounding error'))}")lines.extend([+ "Remove or reword every rejected claim above instead of repeating it; an",+ "unsupported figure in a table row invalidates the whole draft.","Reuse the exact locked symbol and venue.","For every derived number, label it as derived and show the source inputs and formula.","Do not attach figures to a symbol no tool call in this session handled; "@@ -2236,6 +2300,7 @@ class GroundingLedger:masked = _LABELLED_SCORE_RE.sub(" ", masked)masked = _INDICATOR_VALUE_RE.sub(" ", masked)masked = _PROSPECTIVE_LEVEL_RE.sub(" ", masked)+ masked = _ORDER_LEVEL_RE.sub(" ", masked)masked = _REFERENCE_LEVEL_RE.sub(" ", masked)masked = _SINCE_REFERENCE_RE.sub(" ", masked)masked = _LINE_REFERENCE_RE.sub(" ", masked)diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex ffe9cfb0a..0c43f2892 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -18,6 +18,7 @@ import copyimport jsonimport loggingimport queue+import reimport shutilimport sysimport threading@@ -65,6 +66,10 @@ COLLAPSE_TAIL = 500TAIL_TOKEN_BUDGET = 20_000SUMMARY_CHUNK_CHARS = 80_000+# An LLM may return a transient empty completion (no text, no tool calls);+# retry once with a nudge before failing the run on a second consecutive one.+MAX_CONSECUTIVE_EMPTY_RESPONSE_SKIPS = 1+def _override(name: str):"""Return a monkeypatched module-level override if present."""@@ -114,6 +119,21 @@ def _tool_timeout_seconds() -> float:return get_env_config().agent_tuning.vibe_trading_tool_timeout_seconds+def _llm_timeout_seconds() -> float:+ """Return the per-call LLM timeout in seconds (0/negative disables).++ A silent provider stall otherwise hangs the ReAct loop or the+ auto-compact summary call indefinitely - no chunk arrives, so the+ per-chunk cancel check never runs. Bounding the call lets the run fail+ (or degrade compaction) instead of freezing mid-task.+ """+ ov = _override("LLM_TIMEOUT_SECONDS")+ if ov is not None:+ return ov+ from src.config.accessor import get_env_config+ return get_env_config().agent_tuning.vibe_trading_llm_timeout_seconds++def _goal_max_continuations() -> int:ov = _override("GOAL_MAX_CONTINUATIONS")if ov is not None:@@ -554,6 +574,36 @@ def _is_tool_success(result: str) -> bool:return True+# Provider tool-call markup that a model can emit as plain text on the+# forced-text final iteration, where tool definitions are withheld. Releasing+# it verbatim hands the user mojibake instead of an answer. Both DSML bar+# spellings are covered: ASCII double bars and fullwidth double bars.+_FORCED_TEXT_TOOL_CALL_RE = re.compile(+ r"<\s*/?\s*(?:invoke|parameter|tool_calls|dsml)\b",+ re.IGNORECASE,+)+_DSML_BAR_TOOL_CALL_RE = re.compile(+ r"<\s*[|│]{2}\s*(?:dsml|tool_calls|invoke)\b",+ re.IGNORECASE,+)+++def _looks_like_tool_call_syntax(content: str) -> bool:+ """Return whether final text still contains provider tool-call DSL.++ When tool calling is unavailable, a model may nonetheless answer with its+ native tool-call markup as prose - ``<DSML>tool_calls>``, ``<invoke+ name=...>``, or the fullwidth-vbar mojibake of the same. Such content is+ not an answer and must not be released to the user as one.+ """+ if not content:+ return False+ return bool(+ _FORCED_TEXT_TOOL_CALL_RE.search(content)+ or _DSML_BAR_TOOL_CALL_RE.search(content)+ )++def _normalize_tool_run_dir(args: dict[str, Any], memory_run_dir: str | None) -> dict[str, Any]:"""Normalize ``run_dir`` in tool args to an absolute path when possible.@@ -690,6 +740,7 @@ class AgentLoop:self._run_iteration: int = 0self._has_run = Falseself._grounding: GroundingLedger | None = None+ self._released_fallback = Falsedef cancel(self) -> None:"""Cancel the current loop.@@ -777,6 +828,7 @@ class AgentLoop:self._has_run = Trueself._called_ok = set()self._previous_summary = ""+ self._released_fallback = Falsestate_store = RunStateStore()RUNS_DIR.mkdir(parents=True, exist_ok=True)@@ -836,6 +888,7 @@ class AgentLoop:consecutive_content_filter_count = 0content_filter_circuit_breaker = Falseempty_model_response_iter: int | None = None+ consecutive_empty_responses = 0llm_usage_summary = _new_llm_usage_summary(self.llm)last_response_model: str | None = Nonegoal_continuations = 0@@ -896,9 +949,12 @@ class AgentLoop:"role": "user","content": (f"[SYSTEM] You have {remaining} iterations remaining out of "- f"{self.max_iterations}. Please wrap up your work. "- "Stop calling tools and provide your final answer as plain text. "- "If you have partial results, summarize what you have so far."+ f"{self.max_iterations}. Wrap up your work now: finish any "+ "outstanding file writes or data updates that are part of your "+ "task FIRST, while tools are still available for a few more "+ "iterations. Do not start new analysis or re-verify data you "+ "already hold. Then provide your final answer as plain text; "+ "if your task was to update a file, state that it is done and where."),})@@ -949,12 +1005,17 @@ class AgentLoop:if is_last_iteration:trace.write({"type": "forced_text_only", "iter": current_iter})+ _llm_timeout_s = _llm_timeout_seconds()+ llm_timeout = _llm_timeout_s if _llm_timeout_s > 0 else None+try:response = self.llm.stream_chat(messages,tools=tool_defs,on_text_chunk=_on_text_chunk,on_reasoning_chunk=_on_reasoning_chunk,+ timeout=llm_timeout,+ idle_timeout_s=llm_timeout,should_cancel=self._cancel_event.is_set,)except ProviderStreamError as exc:@@ -988,6 +1049,8 @@ class AgentLoop:tools=tool_defs,on_text_chunk=_on_text_chunk,on_reasoning_chunk=_on_reasoning_chunk,+ timeout=llm_timeout,+ idle_timeout_s=llm_timeout,should_cancel=self._cancel_event.is_set,)@@ -1091,7 +1154,68 @@ class AgentLoop:"model": getattr(self.llm, "model_name", None) or get_env_config().llm.langchain_model_name,})- break+ # A transient empty completion (no text, no tool calls)+ # must not kill a run that has already done its work:+ # nudge once and retry, failing only on a second+ # consecutive empty response.+ if consecutive_empty_responses >= MAX_CONSECUTIVE_EMPTY_RESPONSE_SKIPS:+ break+ consecutive_empty_responses += 1+ messages.append(+ {+ "role": "system",+ "content": (+ "[SYSTEM] Your previous response was empty (no text, no tool "+ "calls). Respond again with either your next tool call or "+ "your final plain-text answer."+ ),+ }+ )+ continue+ # A real response resets the consecutive-empty counter.+ consecutive_empty_responses = 0+ # A model can answer the forced-text final iteration with its+ # native tool-call DSL as prose (see _looks_like_tool_call_syntax).+ # That is not an answer: retry once with a plain-text instruction,+ # and if no budget remains release a deterministic fallback instead+ # of leaking the raw markup to the user.+ if _looks_like_tool_call_syntax(final_content):+ trace.write(+ {+ "type": "tool_call_syntax_in_answer",+ "iter": current_iter,+ }+ )+ messages.append(+ {"role": "assistant", "content": final_content}+ )+ messages.append(+ {+ "role": "system",+ "content": (+ "[SYSTEM] Your previous response was not released: it contained "+ "tool-call syntax even though tool calling is unavailable now. "+ "Provide the final answer as plain prose only, with no XML/DSML tags."+ ),+ }+ )+ final_content = ""+ if iteration < self.max_iterations:+ continue+ # No budget left: never leak the raw markup. The+ # grounding safe-fallback talks about instrument identity,+ # which is wrong for non-market tasks, so use a neutral+ # message here instead.+ final_content = (+ "My final response could not be delivered: it contained "+ "tool-call syntax instead of a plain-text answer. "+ "Please ask me to continue."+ )+ self._released_fallback = True+ self._emit(+ "text_delta",+ {"delta": final_content, "iter": current_iter},+ )if self._grounding is not None:validation = self._grounding.validate_final_answer(final_content)if not validation.valid:@@ -1121,12 +1245,17 @@ class AgentLoop:})final_content = ""+ # One extra revision when real iteration budget remains;+ # each revision costs one iteration, so without budget the+ # run must stop revising and release the safe fallback.+ revision_cap = 4 if self.max_iterations - iteration >= 3 else 3if (iteration < self.max_iterations- and self._grounding.validation_count < 3+ and self._grounding.validation_count < revision_cap):continuefinal_content = self._grounding.safe_fallback()+ self._released_fallback = Trueself._emit("text_delta",{"delta": final_content, "iter": current_iter},@@ -1280,6 +1409,12 @@ class AgentLoop:elif (run_dir / "artifacts" / "metrics.csv").exists() or final_content:state_store.mark_success(run_dir)final_status = "success"+ if self._released_fallback:+ final_reason = (+ "final answer degraded to the deterministic fallback after "+ f"{self._grounding.validation_count if self._grounding else 0} "+ "rejected drafts could not be corrected within the iteration budget"+ )elif empty_model_response_iter is not None:provider = self._llm_runtime.providermodel = self._llm_runtime.configured_model or "(unset)"@@ -1303,6 +1438,8 @@ class AgentLoop:"status": final_status,"iterations": iteration,}+ if self._released_fallback:+ end_event["degraded"] = Trueif final_reason is not None:end_event["reason"] = final_reasontrace.write(end_event)@@ -1317,6 +1454,8 @@ class AgentLoop:"iterations": iteration,"max_iterations": self.max_iterations,}+ if self._released_fallback:+ result["degraded"] = Trueconfigured_model = self._llm_runtime.configured_modelresult.update({@@ -2006,6 +2145,8 @@ class AgentLoop:chunks = _summary_chunks(head)logger.info("Auto compact: folding %d summary chunks", len(chunks))summary = self._previous_summary or ""+ degraded_compact = False+ _compact_timeout = _llm_timeout_seconds()for conv_text in chunks:# Structured template while there is still nothing to update — that# covers a fresh session's first chunk and the corner case where@@ -2019,9 +2160,26 @@ class AgentLoop:focus_section=focus_section,)- summary_resp = self.llm.chat([{"role": "user", "content": prompt}])- if summary_resp.content:- summary = summary_resp.content+ # A silent provider stall on the summary call used to freeze the+ # whole run (no chunk arrives, so nothing aborts it). Bound the+ # call and fall back to hard truncation so the loop continues.+ try:+ summary_resp = self.llm.chat(+ [{"role": "user", "content": prompt}],+ timeout=_compact_timeout if _compact_timeout > 0 else None,+ )+ if summary_resp.content:+ summary = summary_resp.content+ except Exception as exc: # noqa: BLE001 - compaction must not crash the run+ logger.warning("Auto compact LLM call failed (%s); degrading compaction", exc)+ degraded_compact = True+ break+ if degraded_compact and not summary:+ summary = (+ "[compaction degraded: LLM summarization timed out or failed; "+ "earlier tool results were truncated. "+ f"Full transcript: {transcript_path}]"+ )self._previous_summary = summarytokens_before = estimate_tokens(messages)diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.pyindex d371e32fd..3839c69fa 100644--- a/agent/src/config/env_schema.py+++ b/agent/src/config/env_schema.py@@ -338,6 +338,9 @@ class AgentTuningConfig(_EnvBase):vibe_trading_tool_timeout_seconds: float = Field(alias="VIBE_TRADING_TOOL_TIMEOUT_SECONDS", default=1800.0,)+ vibe_trading_llm_timeout_seconds: float = Field(+ alias="VIBE_TRADING_LLM_TIMEOUT_SECONDS", default=300.0,+ )vibe_trading_goal_max_continuations: int = Field(alias="VIBE_TRADING_GOAL_MAX_CONTINUATIONS", default=3,)diff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.pyindex dd6356810..72ba1a1b5 100644--- a/agent/src/providers/chat.py+++ b/agent/src/providers/chat.py@@ -9,6 +9,7 @@ import htmlimport loggingimport osimport re+import time as _timefrom dataclasses import dataclass, fieldfrom typing import Any, Callable, Dict, List, Optional@@ -319,6 +320,7 @@ class ChatLLM:on_text_chunk: Optional[Any] = None,on_reasoning_chunk: Optional[Any] = None,timeout: Optional[int] = None,+ idle_timeout_s: Optional[float] = None,should_cancel: Optional[Callable[[], bool]] = None,) -> LLMResponse:"""Stream the LLM and optionally forward text deltas (e.g. thinking).@@ -333,6 +335,9 @@ class ChatLLM:on_text_chunk: Optional callback ``(delta: str) -> None``.on_reasoning_chunk: Optional callback ``(delta: str) -> None``.timeout: Optional per-call timeout in seconds.+ idle_timeout_s: Optional per-chunk idle timeout; when no stream+ delta arrives for this long the call fails as a retryable+ timeout instead of hanging the loop silently.should_cancel: Optional predicate polled per chunk; when it returnsTrue the stream stops early and the partial response is returned.Lets a caller abort a live stream promptly (cooperative cancel).@@ -347,7 +352,17 @@ class ChatLLM:pending_text = ""possible_dsml_text = Truecancelled = False+ last_chunk_ts = _time.monotonic()for chunk in llm.stream(messages, config=config):+ now = _time.monotonic()+ if idle_timeout_s and now - last_chunk_ts > idle_timeout_s:+ # No delta for too long: the provider is stalled, not+ # thinking. Raising a bare TimeoutError lets the wrapper+ # below convert it into a retryable ProviderStreamError.+ raise TimeoutError(+ f"no stream delta for {idle_timeout_s:.0f}s"+ )+ last_chunk_ts = nowif should_cancel and should_cancel():cancelled = Truebreakdiff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.pyindex 6f4539865..b06e5a843 100644--- a/agent/tests/test_agent_grounding.py+++ b/agent/tests/test_agent_grounding.py@@ -15,6 +15,8 @@ from src.agent.grounding import (_infer_currency,_infer_venue,_scan_symbols,+ _symbol_from_csv_filename,+ _timestamp_matches_claim_date,)from src.agent.loop import AgentLoop, _is_tool_successfrom src.agent.tools import BaseTool, ToolRegistry@@ -745,6 +747,85 @@ def test_run_dir_ohlc_csv_tsx_filename_maps_symbol(tmp_path: Path) -> None:assert good.valid is True, good.issues+def test_weekday_suffixed_claim_dates_match_evidence() -> None:+ """Yearless dates with weekday/intraday annotations still match evidence.++ Reports write a trading day as ``08-10(一)``, ``08-10(周一)盘中`` or+ ``08-10盘中`` rather than bare ``08-10``. Before the prefix matcher, such+ a date cell matched no evidence row and every correct price in the row+ was rejected as ``numeric_claim_unavailable`` (#1015 session regression).+ """+ assert _timestamp_matches_claim_date("2026-08-10T00:00:00", "08-10(一)") is True+ assert _timestamp_matches_claim_date("2026-08-10T00:00:00", "08-10(周一)盘中") is True+ assert _timestamp_matches_claim_date("2026-08-10T00:00:00", "08-10盘中") is True+ assert _timestamp_matches_claim_date("2026-08-10T00:00:00", "08-10") is True+ assert _timestamp_matches_claim_date("2026-08-10T00:00:00", "2026-08-10") is True+ assert _timestamp_matches_claim_date("2026-08-10T00:00:00", "2026-08-10(一)") is True+ assert _timestamp_matches_claim_date("2026-08-10T00:00:00", "08-11") is False+ assert _timestamp_matches_claim_date("2026-08-10T00:00:00", "no-date") is False+++def test_run_dir_ohlc_csv_us_filename_maps_symbol(tmp_path: Path) -> None:+ """INTC_US.csv maps to INTC.US and grounds weekday-suffixed date rows.++ Regression for a real session: the agent wrote ``data/raw/INTC_US.csv``+ and drafted the report in the file's own date format (``08-10(一)``).+ The filename used to map to None (no ``_US`` rule), so the CSV was never+ ingested; combined with the weekday-suffixed date cell, every correct+ price in the draft was rejected and the run surrendered after three+ failed drafts without updating the report.+ """+ raw = tmp_path / "data" / "raw"+ raw.mkdir(parents=True)+ (raw / "INTC_US.csv").write_text(+ "Date,Open,High,Low,Close,Adj Close,Volume\n"+ "2026-08-07,102.33,103.66,98.03,101.65,101.65,76760600\n"+ "2026-08-10,98.26,100.03,96.30,97.52,97.52,101153400\n",+ encoding="utf-8",+ )++ assert _symbol_from_csv_filename("INTC_US") == "INTC.US"++ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="please update intel-tech-trend-6-months.md",+ )+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "INTC"},+ result=json.dumps({+ "ok": True,+ "data": {+ "candidates": [+ {"symbol": "INTC.US", "name": "Intel Corporation", "market": "us",+ "type": "equity", "exchange": "NMS", "source": "yahoo"},+ ]+ },+ }),+ call_id="lock1",+ success=True,+ )++ table = (+ "INTC.US(yfinance,USD)日线如下:\n"+ "| 日期 | 开盘 | 最高 | 最低 | 收盘 |\n"+ "| --- | --- | --- | --- | --- |\n"+ "| 08-07(五) | 102.33 | 103.66 | 98.03 | 101.65 |\n"+ "| 08-10(一) | 98.26 | 100.03 | 96.30 | 97.52 |\n"+ )+ result = ledger.validate_final_answer(table)+ assert result.valid is True, result.issues++ # The date is masked in prose, but a fabricated price is still caught.+ fabricated = ledger.validate_final_answer(+ "INTC.US(yfinance,USD)08-10(一) 开盘价 88.88,收盘价 97.52,数据源 yahoo。"+ )+ assert fabricated.valid is False+ assert any(+ issue["code"] == "numeric_claim_conflict" for issue in fabricated.issues+ )++def test_run_dir_ohlc_csv_stray_symbol_is_ignored(tmp_path: Path) -> None:"""A CSV for a symbol the run never handled does not mint identity."""raw = tmp_path / "data" / "raw"@@ -2124,3 +2205,58 @@ def test_in_text_decimal_survives_list_marker_mask():result = ledger.validate_final_answer(draft)assert result.valid is True, (draft, result.issues)+++def test_order_level_prices_are_not_observed_quotes(tmp_path: Path) -> None:+ """GTC order limits (100 @ $3.50) are prospective, not observed prices.++ Regression for the RXRX run: the draft "两档 GTC (100 @ $3.50 / 100 @ $4.00)+ 凿œªè§¦å‘ (周高 $3.42 < $3.50)" was rejected with numeric_claim_conflict for+ 100, 3.5 and 4.0 against the observed OHLC range. Order levels are levels,+ like targets/stops, and share counts are quantities - neither is a claim+ about an observed quote.+ """+ raw = tmp_path / "data" / "raw"+ raw.mkdir(parents=True)+ (raw / "RXRX_US.csv").write_text(+ "Date,Open,High,Low,Close\n"+ "2026-08-07,3.25,3.26,3.18,3.20\n"+ "2026-08-08,3.10,3.42,3.05,3.35\n",+ encoding="utf-8",+ )+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="è¯·åˆ†æž RXRX.US 并更新周报",+ )+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "RXRX"},+ result=json.dumps({+ "ok": True,+ "data": {+ "candidates": [+ {"symbol": "RXRX.US", "name": "Recursion Pharmaceuticals", "market": "us",+ "type": "equity", "exchange": "NMS", "source": "yahoo"},+ ]+ },+ }),+ call_id="lock1",+ success=True,+ )++ answer = (+ "RXRX.US(yahoo,USD)本周高 $3.42。订å•: 两档 GTC (100 @ $3.50 / 100 @ $4.00) "+ "凿œªè§¦å‘ (周高 $3.42 < $3.50) — ä»·æ ¼æŽ¨æ–æœªæˆäº¤ã€‚"+ )+ result = ledger.validate_final_answer(answer)+ assert result.valid is True, result.issues++ # A genuinely fabricated close is still rejected.+ fabricated = ledger.validate_final_answer(+ "RXRX.US(yahoo,USD)本周高 $3.42。å¦: 收盘 2.50 已确认。"+ )+ assert fabricated.valid is False+ assert any(+ issue["code"] == "numeric_claim_conflict" for issue in fabricated.issues+ )+diff --git a/agent/tests/test_agent_loop_content_filter.py b/agent/tests/test_agent_loop_content_filter.pyindex 6a6407c0f..c6a05fbfd 100644--- a/agent/tests/test_agent_loop_content_filter.py+++ b/agent/tests/test_agent_loop_content_filter.py@@ -163,25 +163,72 @@ def test_multiple_content_filter_hits(assert len(filter_entries) == 3-def test_empty_content_no_filter_still_breaks(+def test_empty_content_no_filter_retries_once_then_breaks(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:- """Empty content with content_filter_triggered=False triggers existing break."""+ """A second consecutive empty response (no filter) still fails the run.++ The first empty completion is retried with a nudge; only a second+ consecutive empty response breaks the loop (transient provider empties+ must not kill a run that has already done its work).+ """llm = _EmptyResponseLoopLLM()result = _run(monkeypatch, tmp_path, llm)assert result["status"] == "failed"assert "empty_model_response" in result.get("reason", "")- assert llm.calls == 1+ assert llm.calls == 2trace = _read_trace(result["run_dir"])empty_entries = [e for e in trace if e.get("type") == "empty_model_response"]- assert len(empty_entries) == 1+ assert len(empty_entries) == 2filter_entries = [e for e in trace if e.get("type") == "content_filter_skipped"]assert len(filter_entries) == 0+def test_single_empty_response_recovers_with_nudge(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """One transient empty response is retried with a nudge; the run succeeds."""+ class _OneEmptyThenFinalLLM:+ def __init__(self) -> None:+ self.calls = 0+ self.messages_history: list[list[dict[str, Any]]] = []++ def stream_chat(+ self,+ messages: list[dict[str, Any]],+ tools: list[Any] | None = None,+ on_text_chunk: Callable[[str], None] | None = None,+ on_reasoning_chunk: Callable[[str], None] | None = None,+ should_cancel: Callable[[], bool] | None = None,+ ) -> LLMResponse:+ self.calls += 1+ self.messages_history.append(list(messages))+ if self.calls == 1:+ return LLMResponse(content="", content_filter_triggered=False)+ if on_text_chunk:+ on_text_chunk("Finally.")+ return LLMResponse(content="Finally.")++ def chat(self, messages: list[dict[str, Any]], **_: Any) -> LLMResponse:+ return LLMResponse(content="")++ llm = _OneEmptyThenFinalLLM()+ result = _run(monkeypatch, tmp_path, llm)++ assert result["status"] == "success"+ assert result["content"] == "Finally."+ assert llm.calls == 2+ system_msgs = [+ m for m in llm.messages_history[1]+ if "[SYSTEM]" in str(m.get("content", ""))+ and "empty" in str(m.get("content", "")).casefold()+ ]+ assert len(system_msgs) == 1++class _RatioFilterLoopLLM:"""LLM stub producing content_filter on first N calls, tool calls to keepthe loop going, then final content on the last call.diff --git a/agent/tests/test_agent_loop_dsml_tool_calls.py b/agent/tests/test_agent_loop_dsml_tool_calls.pyindex 5307eaae7..7ad1cc108 100644--- a/agent/tests/test_agent_loop_dsml_tool_calls.py+++ b/agent/tests/test_agent_loop_dsml_tool_calls.py@@ -128,3 +128,56 @@ def test_agent_loop_executes_dsml_textual_tool_call(assert {payload["tool"] for payload in tool_events.values()} == {"echo_probe"}++def test_agent_loop_never_releases_tool_call_syntax_as_a_final_answer(+ tmp_path: Path,+ monkeypatch,+) -> None:+ """Forced-text final answers containing tool-call DSL are not released raw.++ On the last iteration tools are withheld to guarantee a plain-text answer,+ but a model can still emit its native tool-call markup as prose (plain or+ fullwidth-vbar mojibake). That markup is not an answer: the loop must+ retry when budget remains, otherwise release a deterministic message and+ mark the run degraded instead of leaking ``<...tool_calls>`` to the user.+ """+ class _ImmediateHeartbeatTimer:+ def __init__(self, tool_name: str, interval: float, emit) -> None:+ del interval+ self._tool_name = tool_name+ self._emit = emit++ def __enter__(self):+ self._emit({"tool": self._tool_name, "elapsed_s": 0.01})+ return self++ def __exit__(self, exc_type, exc, tb) -> None:+ return None++ monkeypatch.setattr(+ "src.agent.loop.HeartbeatTimer", _ImmediateHeartbeatTimer+ )+ # The fullwidth-vbar form is what the real failure looked like; the+ # streaming DSML parser does not recognize it, so it arrives as text.+ garbage = "<││DSML││tool_calls><││invoke name=\"trading_quote\">"+ registry = ToolRegistry()+ events: list[tuple[str, dict[str, Any]]] = []+ agent = AgentLoop(+ registry=registry,+ llm=_chat_llm(_ScriptedStreamingLLM([garbage])),+ event_callback=lambda event_type, payload: events.append((event_type, payload)),+ max_iterations=1, # the single iteration is the forced-text last one+ persistent_memory=PersistentMemory(memory_dir=tmp_path / "memory"),+ )+ agent.memory.run_dir = str(tmp_path / "run")++ result = agent.run("hello")++ assert result["status"] == "success"+ assert result.get("degraded") is True+ assert "tool-call syntax" in result["content"]+ assert "<" not in result["content"]+ assert not any(+ event_type == "answer" and "<" in str(payload)+ for event_type, payload in events+ )diff --git a/agent/tests/test_agent_loop_terminal_state.py b/agent/tests/test_agent_loop_terminal_state.pyindex 2a47e945b..f18e6789c 100644--- a/agent/tests/test_agent_loop_terminal_state.py+++ b/agent/tests/test_agent_loop_terminal_state.py@@ -146,14 +146,18 @@ def _build_agent(llm: Any, max_iter: int = 3, tmp_run_dir: Path | None = None) -def test_empty_model_response_returns_specific_reason(tmp_path: Path,) -> None:- """Empty no-tool provider output is distinct from exhausting iterations."""+ """Two consecutive empty no-tool outputs fail with the specific reason.++ The first empty completion is retried with a nudge; the run fails on the+ second consecutive empty response, and the reason names that iteration.+ """agent = _build_agent(_StubLLMNoFinal(), max_iter=3, tmp_run_dir=tmp_path / "run")result = agent.run(user_message="anything")assert result["status"] == "failed"assert result["reason"].startswith("empty_model_response")- assert "iteration 1" in result["reason"]+ assert "iteration 2" in result["reason"]assert result["iterations"] >= 1assert result["max_iterations"] == 3diff --git a/agent/tests/test_chat_llm_streaming.py b/agent/tests/test_chat_llm_streaming.pyindex 01992ad87..f43dc95c1 100644--- a/agent/tests/test_chat_llm_streaming.py+++ b/agent/tests/test_chat_llm_streaming.py@@ -347,3 +347,46 @@ def test_provider_stream_error_hints_at_base_url_on_html_body() -> None:assert "HTML page" in messageassert "base URL" in messageassert "zai" in message+++def test_stream_idle_timeout_aborts_a_stalled_stream() -> None:+ """A stream whose deltas stall past the idle budget fails retryably.++ The loop passes idle_timeout_s so a provider that stops emitting+ chunks (silent stall) surfaces as a retryable ProviderStreamError+ instead of hanging the run indefinitely.+ """+ import time++ class _StallingLLM(_FakeStreamingLLM):+ def stream(self, messages, config=None):+ yield _FakeChunk(content="first")+ time.sleep(0.6) # longer than idle_timeout_s below+ yield _FakeChunk(content="second")++ client = _client(_StallingLLM())+ with pytest.raises(ProviderStreamError) as excinfo:+ client.stream_chat(+ [{"role": "user", "content": "hi"}],+ idle_timeout_s=0.2,+ )+ assert excinfo.value.retryable is True+++def test_stream_idle_timeout_allows_a_flowing_stream() -> None:+ """Chunks arriving within the idle budget are unaffected by the timeout."""+ import time++ class _FlowingLLM(_FakeStreamingLLM):+ def stream(self, messages, config=None):+ yield _FakeChunk(content="a")+ time.sleep(0.05)+ yield _FakeChunk(content="b")++ client = _client(_FlowingLLM())+ response = client.stream_chat(+ [{"role": "user", "content": "hi"}],+ idle_timeout_s=0.2,+ )+ assert response.content == "ab"+diff --git a/agent/tests/test_loop_helpers.py b/agent/tests/test_loop_helpers.pyindex dca845b16..170da3e0f 100644--- a/agent/tests/test_loop_helpers.py+++ b/agent/tests/test_loop_helpers.py@@ -18,6 +18,7 @@ from src.agent.loop import (_is_tool_success,_normalize_tool_run_dir,_archive_backtest_result,+ _llm_timeout_seconds,)@@ -392,3 +393,14 @@ class TestArchiveBacktestResult:assert archived is Falseassert not (active / "artifacts").exists()+++def test_llm_timeout_seconds_default_and_override(monkeypatch) -> None:+ """The LLM call timeout reads config and honors a module-level override."""+ import src.agent.loop as loop_module++ assert _llm_timeout_seconds() > 0+ monkeypatch.setattr(loop_module, "LLM_TIMEOUT_SECONDS", 42.0, raising=False)+ assert _llm_timeout_seconds() == 42.0+ monkeypatch.delattr(loop_module, "LLM_TIMEOUT_SECONDS", raising=False)+ assert _llm_timeout_seconds() > 0