Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(agent): let screening runs reach a grounded answer

Haozhe Wu011faeea5a83
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.py
index 8006e5bca..ced552f70 100644
--- a/agent/src/agent/grounding.py
+++ b/agent/src/agent/grounding.py
@@ -18,7 +18,7 @@ import hashlib
import json
import math
import re
-from dataclasses import asdict, dataclass, field
+from dataclasses import asdict, dataclass, field, replace
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable, Mapping, Sequence
@@ -56,6 +56,12 @@ _SYMBOL_ARGUMENT_KEYS = {
"underlying",
"underlyings",
}
+# Workflow selection must not race an in-flight resolution or proceed on
+# contradicted identity. It may proceed once the resolver has answered — and
+# ``ambiguous`` is an answer: a screening request ("推荐低价高增长股票") resolves to
+# 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"}
_PRICE_FIELDS = {"open", "high", "low", "close", "adj_close", "price"}
_TIMESTAMP_FIELDS = ("trade_date", "date", "datetime", "timestamp", "time", "index")
_MAX_GENERIC_EVIDENCE = 2_000
@@ -103,6 +109,32 @@ _NUMBER_RE = re.compile(
r"(?![A-Za-z0-9_])"
)
_DATE_RE = re.compile(r"\b(?:19|20)\d{2}[-/]\d{1,2}[-/]\d{1,2}\b")
+# Localized calendar text carries digits that the ISO pattern above leaves
+# behind: "8 月 3 日" otherwise contributes 8 and 3 as candidate prices.
+_LOCALIZED_DATE_RE = re.compile(
+ r"(?:(?:19|20)\d{2}\s*年\s*)?\d{1,2}\s*月(?:\s*\d{1,2}\s*[日号])?|(?:19|20)\d{2}\s*年"
+)
+# An aggregate amount is not a quoted price. "100 股成本 820 CNY" states a
+# position cost; comparing 820 against a per-share OHLC range is a category
+# error. The tradeoff is that a per-share figure written only as "成本 8.20"
+# goes unchecked — provenance still requires symbol, source, and currency.
+_AGGREGATE_AMOUNT_RE = re.compile(
+ r"(?:成本|总额|总价|总市值|市值|合计|金额|cost|total|notional|market value)"
+ r"\s*(?:为|是|约)?\s*[::]?\s*[-+]?\d[\d,]*(?:\.\d+)?",
+ re.IGNORECASE,
+)
+# Quantities, horizons, and lot sizes are unit-bearing: "100 股", "1–4 周",
+# "3 个月". None of them are prices.
+_QUANTITY_WITH_UNIT_RE = re.compile(
+ r"\d[\d,]*(?:\.\d+)?(?:\s*[-–—~至]\s*\d[\d,]*(?:\.\d+)?)?\s*"
+ r"(?:股|手|张|份|口|笔|倍|个月|周|天|日|年|次|"
+ r"shares?|contracts?|lots?|units?|weeks?|months?|days?|years?)",
+ re.IGNORECASE,
+)
+# Full-width brackets and enumeration commas delimit prose clauses. ASCII
+# 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()【】]")
_TABLE_SEPARATOR_RE = re.compile(r"^:?-{3,}:?$")
_TABLE_FIELD_ALIASES = {
@@ -436,17 +468,15 @@ class GroundingLedger:
return self._authorize_private_company_skill()
if tool_name == "load_skill" and self._identity_required:
- authorized = {
- _normalize_symbol(item) for item in batch_authorized_symbols
- }
frozen_status = batch_identity_status or self.identity_status
- if frozen_status != "locked" or not authorized:
+ if frozen_status in _RESOLUTION_INCOMPLETE_STATUSES:
return ToolAuthorization(
allowed=False,
error_code="identity_required",
message=(
- "Market-sensitive workflow selection is blocked until identity "
- "was locked in an earlier assistant tool turn."
+ "Market-sensitive workflow selection is blocked while instrument "
+ "resolution is in flight or contradicted; a resolver result from "
+ "this same batch cannot be consumed."
),
)
return ToolAuthorization(allowed=True)
@@ -834,6 +864,29 @@ class GroundingLedger:
candidates=candidates,
version=version,
)
+ self._supersede_shortlists(symbol)
+
+ def _supersede_shortlists(self, symbol: str) -> None:
+ """Retire ambiguous shortlists that this lock has just answered.
+
+ A screening query resolves to many candidates by design. Once one of
+ them is locked by a later, narrower resolution, the earlier shortlist is
+ answered rather than unresolved — leaving it ``ambiguous`` blocks every
+ final answer in the run for the rest of the session (#955).
+
+ Args:
+ symbol: Canonical symbol locked by the current resolution.
+ """
+ for key, record in self._identities.items():
+ if record.status != "ambiguous":
+ continue
+ offered = {
+ _normalize_symbol(candidate.get("symbol")) for candidate in record.candidates
+ }
+ if symbol in offered:
+ self._identities[key] = replace(
+ record, status="superseded", updated_at=_utc_now()
+ )
@staticmethod
def _choose_candidate(
@@ -1115,7 +1168,7 @@ class GroundingLedger:
if index in table_lines or "|" in line:
continue
line_symbol = self._symbol_for_claim(line, records)
- for segment in re.split(r"[,,;;。\n]", line):
+ for segment in _CLAUSE_SEPARATOR_RE.split(line):
if not _PRICE_CONTEXT_RE.search(segment):
continue
values = self._numbers_without_dates_or_percent(segment)
@@ -1389,8 +1442,24 @@ class GroundingLedger:
@staticmethod
def _numbers_without_dates_or_percent(text: str) -> list[float]:
- """Extract numbers while excluding dates and percentages."""
- without_dates = _DATE_RE.sub(" ", text)
+ """Extract the numbers in a claim that could plausibly be prices.
+
+ Digits that belong to a canonical symbol, a calendar date, an aggregate
+ amount, a unit-bearing quantity, or a percentage are masked first. Left
+ unmasked they are compared against observed OHLC ranges and reject a
+ correct draft: ``000543.SZ`` alone contributes 543.
+
+ Args:
+ text: One claim segment or table cell.
+
+ Returns:
+ Candidate price values, in order of appearance.
+ """
+ masked = _CANONICAL_SYMBOL_RE.sub(" ", text)
+ masked = _LOCALIZED_DATE_RE.sub(" ", masked)
+ masked = _DATE_RE.sub(" ", masked)
+ masked = _AGGREGATE_AMOUNT_RE.sub(" ", masked)
+ without_dates = _QUANTITY_WITH_UNIT_RE.sub(" ", masked)
values: list[float] = []
for match in _NUMBER_RE.finditer(without_dates):
tail = without_dates[match.end() :].lstrip()
diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.py
index 1542e6dbe..67316e0e9 100644
--- a/agent/tests/test_agent_grounding.py
+++ b/agent/tests/test_agent_grounding.py
@@ -731,3 +731,183 @@ def test_agent_loop_rejects_then_corrects_ungrounded_final_answer(
)
assert artifact["validations"][0]["valid"] is False
assert artifact["validations"][-1]["valid"] is True
+
+
+_SHORTLIST_QUERY = "A股低价高增长股票"
+_SHORTLIST_PAYLOAD = _resolver_payload(
+ candidates=[
+ {"symbol": "000543.SZ", "name": "皖能电力", "market": "cn", "source": "eastmoney"},
+ {"symbol": "000727.SZ", "name": "冠捷科技", "market": "cn", "source": "eastmoney"},
+ ],
+ query=_SHORTLIST_QUERY,
+)
+_NARROWED_PAYLOAD = _resolver_payload(
+ candidates=[
+ {"symbol": "000543.SZ", "name": "皖能电力", "market": "cn", "source": "eastmoney"},
+ ],
+ query="000543.SZ",
+)
+_SCREENED_MARKET_PAYLOAD = json.dumps(
+ {
+ "000543.SZ": [
+ {
+ "trade_date": "2026-08-01",
+ "open": 7.9,
+ "high": 8.5,
+ "low": 7.9,
+ "close": 8.2,
+ "volume": 100000,
+ }
+ ],
+ "_provenance": {
+ "000543.SZ": {
+ "source": "tencent",
+ "requested_source": "auto",
+ "detected_source": "tencent",
+ "fallback_used": False,
+ "currency_conversion": "none",
+ }
+ },
+ }
+)
+
+
+def _screened_ledger(tmp_path: Path) -> GroundingLedger:
+ """Return a ledger that screened broadly, then locked one candidate."""
+ ledger = GroundingLedger(
+ run_dir=tmp_path,
+ user_message="推荐A股低价高增长股票并给出买入价",
+ )
+ for call_id, query, payload in (
+ ("shortlist", _SHORTLIST_QUERY, _SHORTLIST_PAYLOAD),
+ ("narrow", "000543.SZ", _NARROWED_PAYLOAD),
+ ):
+ ledger.authorize_tool_call(
+ "search_symbol",
+ {"query": query},
+ batch_authorized_symbols=ledger.authorized_symbols,
+ call_id=call_id,
+ )
+ ledger.ingest_tool_result(
+ tool_name="search_symbol",
+ arguments={"query": query},
+ result=payload,
+ call_id=call_id,
+ success=True,
+ )
+ ledger.ingest_tool_result(
+ tool_name="get_market_data",
+ arguments={"codes": ["000543.SZ"]},
+ result=_SCREENED_MARKET_PAYLOAD,
+ call_id="prices",
+ success=True,
+ )
+ return ledger
+
+
+def test_screening_shortlist_does_not_block_workflow_selection(tmp_path: Path) -> None:
+ """A many-candidate screening result is an answer, not a stalled resolution (#955)."""
+ ledger = GroundingLedger(
+ run_dir=tmp_path,
+ user_message="推荐A股低价高增长股票并给出买入价",
+ )
+ ledger.authorize_tool_call(
+ "search_symbol",
+ {"query": _SHORTLIST_QUERY},
+ batch_authorized_symbols=ledger.authorized_symbols,
+ call_id="shortlist",
+ )
+ ledger.ingest_tool_result(
+ tool_name="search_symbol",
+ arguments={"query": _SHORTLIST_QUERY},
+ result=_SHORTLIST_PAYLOAD,
+ call_id="shortlist",
+ success=True,
+ )
+
+ assert ledger.identity_status == "ambiguous"
+ skill = ledger.authorize_tool_call(
+ "load_skill",
+ {"name": "stock-selection"},
+ batch_authorized_symbols=ledger.authorized_symbols,
+ call_id="skill",
+ batch_identity_status=ledger.identity_status,
+ )
+
+ assert skill.allowed is True
+
+
+def test_narrowed_lock_retires_the_screening_shortlist(tmp_path: Path) -> None:
+ """Locking a shortlisted candidate must unblock the run's final answer (#955)."""
+ ledger = _screened_ledger(tmp_path)
+
+ assert ledger.identity_status == "locked"
+ assert ledger.authorized_symbols == {"000543.SZ"}
+ prices = ledger.authorize_tool_call(
+ "get_market_data",
+ {"codes": ["000543.SZ"]},
+ batch_authorized_symbols=ledger.authorized_symbols,
+ call_id="prices",
+ batch_identity_status=ledger.identity_status,
+ )
+
+ assert prices.allowed is True
+
+
+def test_price_validation_ignores_symbol_date_and_quantity_digits(tmp_path: Path) -> None:
+ """Ticker, calendar, holding-period, and position-cost digits are not prices (#955)."""
+ ledger = _screened_ledger(tmp_path)
+
+ for draft in (
+ "000543.SZ 截至 8 月 3 日收盘价 8.20 CNY(source: tencent)",
+ "000543.SZ 买入价 8.20 CNY(100 股成本 820 CNY;source: tencent)",
+ "000543.SZ 建议持有 1–4 周,买入价 8.20 CNY(source: tencent)",
+ ):
+ result = ledger.validate_final_answer(draft)
+ assert result.valid is True, (draft, result.issues)
+
+
+def test_price_validation_still_rejects_a_quote_outside_observed_range(
+ tmp_path: Path,
+) -> None:
+ """Masking non-price digits must not weaken the contradiction check (#955)."""
+ ledger = _screened_ledger(tmp_path)
+
+ result = ledger.validate_final_answer("000543.SZ 收盘价 42.00 CNY(source: tencent)")
+
+ assert result.valid is False
+ assert [issue["code"] for issue in result.issues] == ["numeric_claim_conflict"]
+
+
+def test_screening_run_reaches_a_final_answer_through_the_agent_loop(
+ tmp_path: Path,
+) -> None:
+ """End-to-end: screen, load a workflow skill, narrow, quote, and answer (#955)."""
+ agent, resolver, market, skill, trace = _build_direct_agent(tmp_path, _SHORTLIST_PAYLOAD)
+ market.result = _SCREENED_MARKET_PAYLOAD
+ agent._grounding = GroundingLedger(
+ run_dir=Path(agent.memory.run_dir),
+ user_message="推荐A股低价高增长股票并给出买入价",
+ )
+ messages: list[dict[str, Any]] = []
+ react_trace: list[dict[str, Any]] = []
+
+ def batch(*calls: SimpleNamespace, iteration: int) -> None:
+ agent._process_tool_calls(
+ list(calls), ContextBuilder, messages, trace, react_trace, iteration
+ )
+
+ batch(_tool_call("shortlist", "search_symbol", query=_SHORTLIST_QUERY), iteration=1)
+ batch(_tool_call("workflow", "load_skill", name="stock-selection"), iteration=2)
+ assert skill.calls == 1
+
+ resolver.result = _NARROWED_PAYLOAD
+ batch(_tool_call("narrow", "search_symbol", query="000543.SZ"), iteration=3)
+ batch(_tool_call("prices", "get_market_data", codes=["000543.SZ"]), iteration=4)
+ trace.close()
+
+ assert market.calls == 1
+ validation = agent._grounding.validate_final_answer(
+ "000543.SZ 买入价 8.20 CNY(100 股成本 820 CNY;source: tencent)"
+ )
+ assert validation.valid is True, validation.issues