"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(grounding): auto-recover identity and price evidence with bounded budget
Lanre Shittu785b212c8a9f
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.pyindex 8b695207d..6f5ca49d3 100644--- a/agent/src/agent/grounding.py+++ b/agent/src/agent/grounding.py@@ -59,6 +59,15 @@ _SYMBOL_ARGUMENT_KEYS = {# many candidates by design. Requiring a locked identity there stalls every# discovery task before it can load a screening skill, which is #955._RESOLUTION_INCOMPLETE_STATUSES = {"unresolved", "conflicting", "invalidated"}+# Bounded read-only recovery (#1081): a missing instrument identity or price+# evidence is often recoverable deterministically, so the loop should keep+# driving the original task through `search_symbol` and `get_market_data`+# instead of handing the user a terminal "confirm and continue" fallback.+# These budgets are separate from the rejected-draft count so real recovery+# progress is never cut off at the three-draft retry cap.+MAX_GROUNDING_RECOVERY_ROUNDS = 6+MAX_SYMBOL_RESOLUTION_ATTEMPTS = 2+MAX_PRICE_EVIDENCE_ATTEMPTS = 3_PRICE_FIELDS = {"open", "high", "low", "close", "adj_close", "price"}_TIMESTAMP_FIELDS = ("trade_date", "date", "datetime", "timestamp", "time", "index")_MAX_GENERIC_EVIDENCE = 2_000@@ -825,6 +834,9 @@ class GroundingLedger:self._evidence: list[EvidenceRecord] = []self._tool_failures: list[dict[str, Any]] = []self._validations: list[dict[str, Any]] = []+ self._recovery_rounds = 0+ self._symbol_resolution_attempts = 0+ self._price_evidence_attempts = 0self._ingested_csvs: set[str] = set()self._identity_required = bool(_ACTIONABLE_MARKET_RE.search(user_message))self._buffer_output = self._identity_required@@ -893,6 +905,18 @@ class GroundingLedger:"status": self.identity_status,"authorized_symbols": sorted(self.authorized_symbols),"records": [asdict(record) for record in self._identities.values()],+ "recovery": self.recovery_summary(),+ }++ def recovery_summary(self) -> dict[str, Any]:+ """Return bounded-recovery budget state for traces and the artifact."""+ return {+ "rounds": self._recovery_rounds,+ "max_rounds": MAX_GROUNDING_RECOVERY_ROUNDS,+ "symbol_resolution_attempts": self._symbol_resolution_attempts,+ "max_symbol_resolution_attempts": MAX_SYMBOL_RESOLUTION_ATTEMPTS,+ "price_evidence_attempts": self._price_evidence_attempts,+ "max_price_evidence_attempts": MAX_PRICE_EVIDENCE_ATTEMPTS,}def authorize_tool_call(@@ -1149,11 +1173,93 @@ class GroundingLedger:"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; ""report it as not retrieved instead.",- "If evidence is unavailable or conflicting, say so and ask for clarification; do not guess.",])+ recovery = self.recovery_action(validation)+ if recovery == _RESOLVER_TOOL:+ lines.extend(+ [+ "Instrument identity is unresolved. Call `search_symbol` for the "+ "candidate name in a separate tool-call turn, lock the exact canonical "+ "symbol and venue it returns, then call `get_market_data` before finalizing.",+ "Do NOT ask the user to confirm or continue while this read-only recovery "+ "remains available.",+ ]+ )+ elif recovery == "get_market_data":+ lines.extend(+ [+ "Identity is locked but price evidence is missing. Call `get_market_data` "+ "for the locked canonical symbol and venue in a separate tool-call turn, "+ "then regenerate and re-validate the final answer.",+ "Do NOT ask the user to confirm or continue while this read-only recovery "+ "remains available.",+ ]+ )+ else:+ lines.append(+ "If evidence is genuinely unavailable or conflicting and recovery is "+ "exhausted, say so and ask for clarification; do not guess."+ )return "\n".join(lines)+ def recovery_action(self, validation: ValidationResult) -> str | None:+ """Decide the next safe read-only recovery step for a rejected draft.++ Returns ``search_symbol`` when instrument identity is unresolved and+ resolution attempts remain; ``get_market_data`` when identity is locked+ but a price claim has no observed evidence and fetch attempts remain;+ otherwise ``None`` (genuinely ambiguous, conflicting, or exhausted —+ the loop must then ask the user or fail closed).++ This is the deterministic half of #1081: recoverable missing evidence is+ often obtainable through read-only tools, so a rejected draft should+ drive the original task forward instead of stopping.+ """+ if self._recovery_rounds >= MAX_GROUNDING_RECOVERY_ROUNDS:+ return None+ if self._identity_required and self.identity_status == "unresolved":+ if self._symbol_resolution_attempts < MAX_SYMBOL_RESOLUTION_ATTEMPTS:+ return _RESOLVER_TOOL+ return None+ if self.identity_status == "locked" and any(+ issue.get("code") in {"numeric_claim_unavailable", "unsourced_symbol_figures"}+ for issue in validation.issues+ ):+ if self._price_evidence_attempts < MAX_PRICE_EVIDENCE_ATTEMPTS:+ return "get_market_data"+ return None++ def record_recovery(self, action: str) -> None:+ """Account one bounded recovery attempt against its budget."""+ self._recovery_rounds += 1+ if action == _RESOLVER_TOOL:+ self._symbol_resolution_attempts += 1+ elif action == "get_market_data":+ self._price_evidence_attempts += 1++ def recovery_prompt(self, action: str, validation: ValidationResult) -> str:+ """Build an executable next-step message for one bounded recovery turn."""+ if action == _RESOLVER_TOOL:+ return (+ "[GROUNDING RECOVERY] Instrument identity is not yet locked and is "+ "recoverable with read-only tools. Call `search_symbol` for the candidate "+ "name in a separate assistant tool-call turn, lock and reuse the exact "+ "canonical symbol and venue it returns, then call `get_market_data`. "+ "Do NOT ask the user to confirm or continue while this read-only recovery "+ "remains available, and do NOT finalize yet."+ )+ if action == "get_market_data":+ return (+ "[GROUNDING RECOVERY] Identity is locked but price evidence is missing. "+ "Call `get_market_data` for the locked canonical symbol and venue in a "+ "separate tool-call turn and use its existing bounded provider fallback, "+ "then regenerate and re-validate the final answer. Do NOT ask the user to "+ "confirm or continue while this read-only recovery remains available, and "+ "do NOT finalize yet."+ )+ return self.correction_prompt(validation)+def safe_fallback(self) -> str:"""Return a deterministic fail-closed answer after repeated rejection."""is_zh = bool(re.search(r"[\u3400-\u9fff]", self.user_message))diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 15181811c..9489e4333 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -1056,6 +1056,29 @@ class AgentLoop:messages.append({"role": "assistant", "content": final_content})+ recovery = self._grounding.recovery_action(validation)+ if recovery is not None and iteration < self.max_iterations:+ self._grounding.record_recovery(recovery)+ trace.write(+ {+ "type": "grounding_recovery",+ "iter": current_iter,+ "action": recovery,+ }+ )+ react_trace.append(+ {"type": "grounding_recovery", "action": recovery}+ )+ messages.append(+ {+ "role": "system",+ "content": self._grounding.recovery_prompt(+ recovery, validation+ ),+ }+ )+ final_content = ""+ continuemessages.append({"role": "system",diff --git a/agent/tests/test_grounding_recovery.py b/agent/tests/test_grounding_recovery.pynew file mode 100644index 000000000..05c083665--- /dev/null+++ b/agent/tests/test_grounding_recovery.py@@ -0,0 +1,327 @@+"""Bounded grounding recovery (#1081): recoverable missing evidence.++When identity is unresolved or price evidence is missing, the loop must+keep driving the original task through read-only tool turns+(``search_symbol`` -> ``get_market_data``) instead of stopping at the+three-draft cap with the "confirm and continue" safe fallback. Recovery+has its own budgets, separate from the rejected-draft count, and the user+is only involved when state is genuinely ambiguous, conflicting, or+exhausted.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any, Callable++import pytest++from src.agent.grounding import (+ MAX_GROUNDING_RECOVERY_ROUNDS,+ MAX_PRICE_EVIDENCE_ATTEMPTS,+ MAX_SYMBOL_RESOLUTION_ATTEMPTS,+ GroundingLedger,+)+from src.providers.chat import LLMResponse++pytestmark = pytest.mark.unit+++def _ledger(+ tmp_path: Path,+ *,+ message: str = "分析机器人ETF并给出买入价",+) -> GroundingLedger:+ return GroundingLedger(run_dir=tmp_path, user_message=message)+++def _resolver_payload(symbol: str = "562500.SS") -> str:+ return json.dumps(+ {+ "ok": True,+ "source": "symbol_search",+ "data": {+ "query": "机器人ETF",+ "count": 1,+ "candidates": [+ {+ "symbol": symbol,+ "name": "机器人ETF",+ "market": "cn",+ "type": "ETF",+ "source": "yahoo",+ "also_from": ["eastmoney"],+ }+ ],+ "sources": {"eastmoney": "ok", "yahoo": "ok"},+ },+ },+ ensure_ascii=False,+ )+++def _market_payload(symbol: str = "562500.SS") -> str:+ return json.dumps(+ {+ symbol: [+ {+ "trade_date": "2026-06-23",+ "open": 1.141,+ "high": 1.164,+ "low": 1.121,+ "close": 1.137,+ "volume": 123456,+ }+ ],+ "_provenance": {+ symbol: {+ "source": "yahoo",+ "requested_source": "auto",+ "detected_source": "yahoo",+ "fallback_used": False,+ "currency_conversion": "none",+ }+ },+ }+ )+++class TestRecoveryAction:+ def test_unresolved_identity_instructs_symbol_search(self, tmp_path: Path) -> None:+ ledger = _ledger(tmp_path)+ validation = ledger.validate_final_answer("机器人ETF 现价 1.171。")++ assert ledger.identity_status == "unresolved"+ assert ledger.recovery_action(validation) == "search_symbol"++ def test_locked_identity_with_missing_price_instructs_market_data(+ self, tmp_path: Path+ ) -> None:+ ledger = _ledger(tmp_path)+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "机器人ETF"},+ result=_resolver_payload(),+ call_id="resolve",+ success=True,+ )+ validation = ledger.validate_final_answer("562500.SS 现价 9.999。")++ assert ledger.identity_status == "locked"+ assert ledger.recovery_action(validation) == "get_market_data"++ def test_grounded_answer_offers_no_recovery(self, tmp_path: Path) -> None:+ ledger = _ledger(tmp_path)+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "机器人ETF"},+ result=_resolver_payload(),+ call_id="resolve",+ success=True,+ )+ ledger.ingest_tool_result(+ tool_name="get_market_data",+ arguments={"codes": ["562500.SS"]},+ result=_market_payload(),+ call_id="market",+ success=True,+ )+ validation = ledger.validate_final_answer(+ "562500.SS(yahoo,CNY)2026-06-23 收盘价 1.137。"+ )++ assert validation.valid is True+ assert ledger.recovery_action(validation) is None++ def test_ambiguous_identity_offers_no_recovery(self, tmp_path: Path) -> None:+ candidates = [+ {"symbol": "ABC.US", "name": "ABC Holdings", "source": "yahoo"},+ {"symbol": "ABC.HK", "name": "ABC Group", "source": "eastmoney"},+ ]+ payload = json.dumps(+ {+ "ok": True,+ "data": {+ "query": "ABC",+ "candidates": candidates,+ "sources": {"yahoo": "ok", "eastmoney": "ok"},+ },+ }+ )+ ledger = _ledger(tmp_path, message="分析 ABC 并给出买入价")+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "ABC"},+ result=payload,+ call_id="resolve",+ success=True,+ )+ validation = ledger.validate_final_answer("ABC 现价 5.0。")++ assert ledger.identity_status == "ambiguous"+ assert ledger.recovery_action(validation) is None++ def test_conflicting_identity_offers_no_recovery(self, tmp_path: Path) -> None:+ ledger = _ledger(tmp_path)+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "机器人ETF"},+ result=_resolver_payload(symbol="562500.SS"),+ call_id="resolve-1",+ success=True,+ )+ # A later resolution of the same query contradicts the lock.+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "机器人ETF"},+ result=_resolver_payload(symbol="000300.SH"),+ call_id="resolve-2",+ success=True,+ )+ validation = ledger.validate_final_answer("000300.SH 现价 5.0。")++ assert ledger.identity_status == "conflicting"+ assert ledger.recovery_action(validation) is None++ def test_symbol_resolution_budget_is_bounded(self, tmp_path: Path) -> None:+ ledger = _ledger(tmp_path)+ broken = ledger.validate_final_answer("机器人ETF 现价 1.171。")++ for _ in range(MAX_SYMBOL_RESOLUTION_ATTEMPTS):+ assert ledger.recovery_action(broken) == "search_symbol"+ ledger.record_recovery("search_symbol")++ assert ledger.recovery_action(broken) is None++ def test_price_evidence_budget_is_bounded(self, tmp_path: Path) -> None:+ ledger = _ledger(tmp_path)+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "机器人ETF"},+ result=_resolver_payload(),+ call_id="resolve",+ success=True,+ )+ validation = ledger.validate_final_answer("562500.SS 现价 9.999。")++ for _ in range(MAX_PRICE_EVIDENCE_ATTEMPTS):+ assert ledger.recovery_action(validation) == "get_market_data"+ ledger.record_recovery("get_market_data")++ assert ledger.recovery_action(validation) is None++ def test_total_recovery_rounds_are_bounded(self, tmp_path: Path) -> None:+ ledger = _ledger(tmp_path)+ validation = ledger.validate_final_answer("机器人ETF 现价 1.171。")++ for _ in range(MAX_GROUNDING_RECOVERY_ROUNDS):+ ledger.record_recovery("search_symbol")++ assert ledger.recovery_action(validation) is None+++class TestRecoveryPrompts:+ def test_correction_names_symbol_search_when_identity_unresolved(+ self, tmp_path: Path+ ) -> None:+ ledger = _ledger(tmp_path)+ validation = ledger.validate_final_answer("机器人ETF 现价 1.171。")++ prompt = ledger.correction_prompt(validation)++ assert "search_symbol" in prompt+ assert "get_market_data" in prompt+ assert "Do NOT ask the user to confirm or continue" in prompt++ def test_correction_asks_when_recovery_exhausted(self, tmp_path: Path) -> None:+ ledger = _ledger(tmp_path)+ validation = ledger.validate_final_answer("机器人ETF 现价 1.171。")+ for _ in range(MAX_GROUNDING_RECOVERY_ROUNDS):+ ledger.record_recovery("search_symbol")++ prompt = ledger.correction_prompt(validation)++ assert "Do NOT ask the user" not in prompt+ assert "ask for clarification" in prompt++ def test_recovery_prompt_points_at_the_tool(self, tmp_path: Path) -> None:+ ledger = _ledger(tmp_path)+ validation = ledger.validate_final_answer("机器人ETF 现价 1.171。")++ prompt = ledger.recovery_prompt("search_symbol", validation)++ assert "search_symbol" in prompt+ assert "Do NOT ask the user to confirm or continue" in prompt++ def test_recovery_summary_reflects_budget_state(self, tmp_path: Path) -> None:+ ledger = _ledger(tmp_path)+ ledger.record_recovery("search_symbol")++ summary = ledger.recovery_summary()++ assert summary["rounds"] == 1+ assert summary["max_rounds"] == MAX_GROUNDING_RECOVERY_ROUNDS+ assert summary["symbol_resolution_attempts"] == 1+ assert summary["price_evidence_attempts"] == 0+++class _FailingDraftLLM:+ """Always produces an ungrounded premium conclusion with no tool calls."""++ def __init__(self) -> None:+ self.calls = 0++ 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+ draft = "机器人ETF 现价 1.171,建议买入。"+ if on_text_chunk:+ on_text_chunk(draft)+ return LLMResponse(content=draft)++ def chat(self, messages: list[dict[str, Any]], **_: Any) -> LLMResponse:+ return LLMResponse(content="")+++def _run_direct_loop(tmp_path: Path, llm: Any, max_iterations: int = 8) -> dict[str, Any]:+ from src.agent.loop import AgentLoop+ from src.memory.persistent import PersistentMemory+ from src.tools import build_registry++ pm = PersistentMemory()+ agent = AgentLoop(+ registry=build_registry(persistent_memory=pm, include_shell_tools=False),+ llm=llm,+ max_iterations=max_iterations,+ persistent_memory=pm,+ )+ run_dir = tmp_path / "run"+ run_dir.mkdir(parents=True, exist_ok=True)+ agent.memory.run_dir = str(run_dir)+ return agent.run(user_message="分析机器人ETF并给出买入价")+++def test_loop_runs_recovery_before_fallback(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """A rejected draft must drive search_symbol recovery before falling back."""+ from src.agent.trace import TraceWriter++ llm = _FailingDraftLLM()++ result = _run_direct_loop(tmp_path, llm, max_iterations=6)++ trace = TraceWriter.read(tmp_path / "run")+ recovery_entries = [e for e in trace if e.get("type") == "grounding_recovery"]+ # Symbol resolution budget is two: two recovery turns, then fallback.+ assert [e.get("action") for e in recovery_entries] == ["search_symbol", "search_symbol"]+ assert llm.calls >= 3+ # The run still terminates fail-closed once recovery is exhausted.+ assert result["content"]