"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(grounding): close the review's remaining residuals and a double-streamed fallback
Haozhe Wuc9eaff1ea6f0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7a12385eb..9b6a6307f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -110,6 +110,10 @@ This project adheres to [Semantic Versioning](https://semver.org/).about prices it never mentioned; a market answer that observed no pricestill falls back. A malformed figures block no longer forces the fallbackeither: the block is dropped and the draft is checked as written.+- **The tool-call-syntax fallback reaches the chat once.** When a model answered+ the forced-text iteration with tool-call markup in a run whose output is+ buffered, the replacement message was streamed by its own branch and again as+ the released answer, so the chat and the CLI showed it twice.- **A redaction footnote the model wrote itself is removed** before the realcuts, so a released answer never carries two contradictory footnotes or amarker for a cut that did not happen.diff --git a/agent/src/agent/grounding/evidence.py b/agent/src/agent/grounding/evidence.pyindex 2c341c29a..e562adc37 100644--- a/agent/src/agent/grounding/evidence.py+++ b/agent/src/agent/grounding/evidence.py@@ -346,6 +346,11 @@ def _is_registered_price_indicator(tool: str, path: str) -> bool:return False+# Tail-risk names short enough to be a fragment of an unrelated leaf count only+# as the whole leaf: "var_explained" and "sales_es" are not a VaR.+_EXACT_ONLY_ALIASES = frozenset({"var", "es"})++def _metric_kind_for_path(path: str) -> str | None:"""Map an evidence JSON path to an analysis metric kind.@@ -362,7 +367,8 @@ def _metric_kind_for_path(path: str) -> str | None:tokens = [token for token in re.split(r"[_.]", leaf) if token]for size in (2, 1):for start in range(len(tokens) - size, -1, -1):- kind = _ANALYSIS_KIND_ALIASES.get("_".join(tokens[start : start + size]))+ key = "_".join(tokens[start : start + size])+ kind = None if key in _EXACT_ONLY_ALIASES else _ANALYSIS_KIND_ALIASES.get(key)if kind is not None:return kindreturn Nonediff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.pyindex e98d0389e..4b7658110 100644--- a/agent/src/agent/grounding/policies.py+++ b/agent/src/agent/grounding/policies.py@@ -655,6 +655,10 @@ class _PolicyMixin:records = [record for record in records if not record.symbol or record.symbol == symbol]+ if figure is not None and figure.column:+ # A table cell quotes its own column, not whatever else the call returned.+ records = [record for record in records if record.field == figure.column]+ metrics = []if figure is not None and figure.percent:records = [recorddiff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 45cf20d70..ad7efedb5 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -1591,7 +1591,14 @@ class AgentLoop:if not buffer_text_output:self._emit("thinking_done",- {"iter": current_iter, "content": thinking_text[:500]},+ {+ "iter": current_iter,+ "content": (+ thinking_text[: self._grounding.streamable_length(thinking_text)]+ if self._grounding is not None+ else thinking_text+ )[:500],+ },)# Content-filter skip: provider blocked the response — continue@@ -1622,6 +1629,7 @@ class AgentLoop:if not response.has_tool_calls:final_content = response.content or ""+ syntax_fallback_emitted = Falseif not final_content:empty_model_response_iter = iterationtrace.write(@@ -1698,6 +1706,7 @@ class AgentLoop:"text_delta",{"delta": final_content, "iter": current_iter},)+ syntax_fallback_emitted = Trueif self._grounding is not None:validation = self._grounding.validate_final_answer(final_content)if not validation.valid:@@ -1862,12 +1871,12 @@ class AgentLoop:"text_delta",{"delta": final_content, "iter": current_iter},)- elif buffer_text_output:+ elif buffer_text_output and not syntax_fallback_emitted:self._emit("text_delta",{"delta": final_content, "iter": current_iter},)- elif not self._released_fallback:+ elif not self._released_fallback and not syntax_fallback_emitted:# Flush a held-back last line that never became a# figures fence; a stripped block leaves nothing.shown = "".join(thinking_chunks)[:streamed_chars]@@ -1965,6 +1974,17 @@ class AgentLoop:react_trace.append({"type": "answer", "content": final_content[:500]})break+ if not buffer_text_output and self._grounding is not None:+ # The turn is over, so a held-back last line is complete: it is+ # shown unless it opens a figures block.+ turn_text = "".join(thinking_chunks)+ safe = min(len(turn_text), self._grounding.streamable_length(turn_text + "\n"))+ if safe > streamed_chars:+ self._emit(+ "text_delta",+ {"delta": turn_text[streamed_chars:safe], "iter": current_iter},+ )+ streamed_chars = safeassistant_message = context.format_assistant_tool_calls(response.tool_calls,content=response.content,diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.pyindex 0659873f3..d90864fb5 100644--- a/agent/tests/test_agent_grounding.py+++ b/agent/tests/test_agent_grounding.py@@ -144,12 +144,15 @@ class _PrivateCompanySkillTool(BaseTool):}repeatable = True- def __init__(self) -> None:+ def __init__(self, content: str) -> None:+ # A required argument keeps registry discovery from instantiating this+ # stub as the real load_skill for later tests (see CLAUDE.md).+ self.content = contentself.calls = 0def execute(self, **kwargs: Any) -> str:self.calls += 1- return json.dumps({"status": "ok", "content": "private company workflow"})+ return json.dumps({"status": "ok", "content": self.content})def _tool_call(call_id: str, tool_name: str, **arguments: Any) -> SimpleNamespace:@@ -162,7 +165,7 @@ def _build_direct_agent() -> tuple[AgentLoop, _ResolverTool, _MarketTool, _PrivateCompanySkillTool, TraceWriter]:resolver = _ResolverTool(resolver_result)market = _MarketTool(_market_payload())- private_skill = _PrivateCompanySkillTool()+ private_skill = _PrivateCompanySkillTool("private company workflow")registry = ToolRegistry()for tool in (resolver, market, private_skill):registry.register(tool)diff --git a/agent/tests/test_grounding_release.py b/agent/tests/test_grounding_release.pyindex 923e6b362..c8ce0791a 100644--- a/agent/tests/test_grounding_release.py+++ b/agent/tests/test_grounding_release.py@@ -1968,3 +1968,106 @@ def test_prose_after_the_figures_block_still_reaches_the_stream(tmp_path: Path)assert "figures" not in streamedassert "补充:先写结论。" in result["content"]assert streamed.rstrip().endswith("补充:先写结论。")+++def test_the_tool_call_syntax_fallback_reaches_the_stream_once(tmp_path: Path) -> None:+ """A buffered run released the fallback in its own branch and again as the answer."""+ llm = _ScriptedLLM([_Response(content='<invoke name="get_market_data">')])++ result, events, _ = _run(tmp_path, llm, max_iterations=1)++ deltas = [data.get("delta", "") for event, data in events if event == "text_delta"]+ assert len(deltas) == 1, deltas+ assert "tool-call syntax" in deltas[0]+ assert result["content"] == deltas[0]+++def test_thinking_done_never_carries_the_figures_block(tmp_path: Path) -> None:+ content = "建议每周复盘 3 次。\n\n```figures\n3 | count | 次/周\n```"+ events: list[tuple[str, dict[str, Any]]] = []+ agent = AgentLoop(+ registry=ToolRegistry(),+ llm=_ChunkedLLM(content),+ max_iterations=3,+ event_callback=lambda event, data: events.append((event, data)),+ )+ run_dir = tmp_path / "run"+ run_dir.mkdir()+ agent.memory.run_dir = str(run_dir)++ agent.run("总结一下这周的复盘心得")++ thoughts = [data.get("content", "") for event, data in events if event == "thinking_done"]+ assert thoughts+ assert all("figures" not in thought for thought in thoughts)+++class _NoteTool(BaseTool):+ name = "note_progress"+ description = "Record a note."+ parameters = {"type": "object", "properties": {}}+ repeatable = True++ def __init__(self, reply: str) -> None:+ self.reply = reply++ def execute(self, **kwargs: Any) -> str:+ return json.dumps({"status": "ok", "note": self.reply})+++def test_a_held_back_line_in_a_tool_call_turn_is_shown(tmp_path: Path) -> None:+ """The last line could only have become a fence while the turn was streaming."""+ registry = ToolRegistry()+ registry.register(_NoteTool("ok"))+ llm = _ScriptedLLM(+ [+ _Response(content="先记一笔:\n`先写结论`", tool_calls=[_tool_call("n1", "note_progress")]),+ _Response(content="记好了。"),+ ]+ )+ events: list[tuple[str, dict[str, Any]]] = []+ agent = AgentLoop(+ registry=registry,+ llm=llm,+ max_iterations=4,+ event_callback=lambda event, data: events.append((event, data)),+ )+ run_dir = tmp_path / "run"+ run_dir.mkdir()+ agent.memory.run_dir = str(run_dir)++ agent.run("总结一下这周的复盘心得")++ streamed = "".join(data.get("delta", "") for event, data in events if event == "text_delta")+ assert "`先写结论`" in streamed+++def test_a_figures_block_ending_a_tool_call_turn_is_not_shown(tmp_path: Path) -> None:+ """Completing the last line reveals a fence; the block after it stays held."""+ registry = ToolRegistry()+ registry.register(_NoteTool("ok"))+ llm = _ScriptedLLM(+ [+ _Response(+ content="先记一笔。\n\n```figures\n3 | count | 次\n```",+ tool_calls=[_tool_call("n1", "note_progress")],+ ),+ _Response(content="记好了。"),+ ]+ )+ events: list[tuple[str, dict[str, Any]]] = []+ agent = AgentLoop(+ registry=registry,+ llm=llm,+ max_iterations=4,+ event_callback=lambda event, data: events.append((event, data)),+ )+ run_dir = tmp_path / "run"+ run_dir.mkdir()+ agent.memory.run_dir = str(run_dir)++ agent.run("总结一下这周的复盘心得")++ streamed = "".join(data.get("delta", "") for event, data in events if event == "text_delta")+ assert "先记一笔。" in streamed+ assert "figures" not in streameddiff --git a/agent/tests/test_grounding_role_hardening.py b/agent/tests/test_grounding_role_hardening.pyindex 3a382717d..cc05191ed 100644--- a/agent/tests/test_grounding_role_hardening.py+++ b/agent/tests/test_grounding_role_hardening.py@@ -654,3 +654,34 @@ def test_a_formula_may_be_followed_by_its_explanation(tmp_path: Path) -> None:assert explained.valid is True, explained.issuesassert "derivation_result_mismatch" in _reasons(wrong)+++def test_a_referenced_table_cell_is_checked_against_its_own_column(tmp_path: Path) -> None:+ """A close cell declared with the call's ref may not borrow that call's high."""+ table = "\n\n| 日期 | 收盘 |\n|---|---|\n| 2026-09-09 | {} |\n"++ high_as_close = _ledger(tmp_path / "high", MARKET_A).validate_final_answer(+ HDR + table.format("0.681") + _block("0.681 | observed | close | c1")+ )+ close = _ledger(tmp_path / "close", MARKET_A).validate_final_answer(+ HDR + table.format("0.666") + _block("0.666 | observed | close | c1")+ )++ assert high_as_close.valid is False+ assert close.valid is True, close.issues+++ ("leaf", "kind"),+ [+ ("var", "tail_risk"),+ ("var_95", "tail_risk"),+ ("strategy_var_95", "tail_risk"),+ ("cvar", "tail_risk"),+ ("es", "tail_risk"),+ ("var_explained", None),+ ("sales_es", None),+ ],+)+def test_short_tail_risk_names_count_only_as_the_whole_leaf(leaf: str, kind: str | None) -> None:+ assert _metric_kind_for_path(leaf) == kind