"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(agent): gate market answers on verified evidence
Haozhe Wu93edbd70283a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5dbd769c8..faeecb8b3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,32 @@ This project adheres to [Semantic Versioning](https://semver.org/).- Lazy FTS5 auto-rebuild on first search when index is empty- 9 end-to-end integration tests + 23 benchmark tests against real production corpus+## [0.1.13] — 2026-08-01++### Added+- **Read-only sentiment tool** (#939): local lexicon scoring for arbitrary text+ plus the crypto Fear & Greed Index from Alternative.me's free, no-auth API.++### Fixed+- **Agent identity ordering and evidence grounding** (#887/#886): market-sensitive+ consumers now require a canonical symbol/venue locked before their assistant+ tool-call batch starts, so a resolver and its consumer cannot race in one+ parallel batch. Silent exchange-suffix rewrites are rejected, listed-company+ evidence cannot be overwritten by model memory, and ambiguous/not-found/+ conflicting/invalidated identities are persisted as first-class states.+- **Final numeric consistency gate** (#886): full untruncated OHLC tool results+ are recorded as structured evidence with symbol, venue, currency, actual data+ source, and explicit conversion status. Contradictory final prices are rejected+ before streaming; derived levels require a visible, arithmetically correct+ formula anchored to observed inputs, and repeated bad drafts fail closed to+ verified observations.+ Tool envelopes with `ok: false`, `success: false`, or failed status are no+ longer recorded as successful calls.+- **Robinhood Agentic MCP response serialization** (#922): nested FastMCP+ dataclasses containing `date`/`datetime` values serialize to JSON instead of+ surfacing the misleading `Circular reference detected` error. A representative+ Robinhood portfolio/account shape now has an end-to-end regression test.+## [0.1.12] — 2026-07-22### Addeddiff --git a/Dockerfile b/Dockerfileindex 0ce93e2b6..3c3a5337d 100644--- a/Dockerfile+++ b/Dockerfile@@ -50,7 +50,7 @@ FROM python:3.11-slim@sha256:e031123e3d85762b141ad1cbc56452ba69c6e722ebf2f042cc0LABEL org.opencontainers.image.title="Vibe-Trading" \org.opencontainers.image.description="Natural-language finance research AI agent with backtesting" \- org.opencontainers.image.version="0.1.12" \+ org.opencontainers.image.version="0.1.13" \org.opencontainers.image.source="https://github.com/HKUDS/Vibe-Trading" \org.opencontainers.image.licenses="MIT"diff --git a/agent/SKILL.md b/agent/SKILL.mdindex d3c1671c3..8c1e363cc 100644--- a/agent/SKILL.md+++ b/agent/SKILL.md@@ -1,6 +1,6 @@---name: vibe-trading-version: 0.1.12+version: 0.1.13description: Professional finance research toolkit — backtesting (9 engines + benchmark comparison panel), factor analysis, Alpha Zoo (462 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 88 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 24 market-data sources (tushare, yfinance, okx, binance, akshare, baostock, tencent, mootdx, ccxt, futu, mt5, local, eastmoney, sina, stooq, yahoo, pykrx, india_broker, qveris, longbridge, plus optional-key finnhub/alphavantage/tiingo/fmp).dependencies:python: ">=3.11"diff --git a/agent/src/agent/context.py b/agent/src/agent/context.pyindex 15e2f6132..767e213c4 100644--- a/agent/src/agent/context.py+++ b/agent/src/agent/context.py@@ -117,7 +117,27 @@ Decide which workflow to use based on the request:## Guidelines-- Load the relevant skill BEFORE starting any task. Skills contain the exact API contracts and examples.+- **Identity before market data:** when the request names a company, fund, or+ instrument without an already canonical symbol+venue, call `search_symbol`+ first and wait for its result. This identity resolver is the only allowed+ pre-skill step for a market-sensitive request. The resolver and a dependent+ market/news/fundamentals/trading consumer MUST be in separate assistant+ tool-call turns;+ calls from one parallel batch share the identity state that existed before+ the batch. Reuse the exact locked symbol and exchange suffix. Never silently+ rewrite `.SS` to `.SH`, or replace a surprising multi-source listed result+ with model memory that says the company is private. Ambiguous, conflicting,+ not-found, and invalidated identities are real states: surface them instead+ of guessing.+- **Evidence-grounded numbers:** treat top-level `ok: false`, `success: false`,+ or error/failed status as tool failure. Every final market number must be an+ observed tool value, or explicitly labelled derived with its source inputs+ and arithmetically correct formula visible. Price claims must surface the+ locked canonical symbol+venue suffix, actual data source, and quote currency.+ Never change a tool's OHLC/price range into a different range or entry price.+ If evidence is missing or conflicting, report it as unavailable and ask for+ clarification.+- Load the relevant skill BEFORE starting any task, after any required identity resolution. Skills contain the exact API contracts and examples.- Ask the user if critical info is missing (assets, dates, strategy type). Never guess.- Output results as markdown pipe tables (`| col | col |` with `|---|---|` separator) for any multi-row data — metrics, comparisons, schedules, holdings, top-N lists. Renderers upgrade these to native tables. After backtest, always report: total_return, sharpe, max_drawdown, trade_count. Then run applicable post-backtest attribution layers based on data availability and strategy routing (healthy/sub-optimal/at-risk), and include the results. Attribution is secondary — strategy correctness always comes first.- Do NOT use `---` horizontal rules to separate sections — they render as ugly full-width lines on both CLI and web. Use `##` / `###` markdown headings instead.diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.pynew file mode 100644index 000000000..8006e5bca--- /dev/null+++ b/agent/src/agent/grounding.py@@ -0,0 +1,1517 @@+"""Run-scoped identity and numeric evidence gates for the main agent loop.++The language model remains responsible for research and explanation, but two+facts are structural rather than advisory:++* a market-data consumer may only use an identity that was locked before the+ current assistant tool-call batch started; and+* a final price claim may not contradict the full, untruncated tool result.++This module deliberately contains no provider or tool-registry dependencies so+its state machine and final-answer checks remain deterministic and testable.+"""++from __future__ import annotations++import ast+import hashlib+import json+import math+import re+from dataclasses import asdict, dataclass, field+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Iterable, Mapping, Sequence+++GROUNDING_ARTIFACT = "grounding_evidence.json"++_RESOLVER_TOOL = "search_symbol"+_PRIVATE_COMPANY_SKILL_NAMES = {+ "private-company",+ "private-company-analysis",+ "private-company-research",+ "private_company",+ "private_company_analysis",+ "private_company_research",+}+_BARE_US_TICKER_TOOLS = {+ "cancel_equity_order",+ "get_equity_quotes",+ "get_options_chain",+ "get_sec_filings",+ "get_stock_profile",+ "place_equity_order",+ "trading_cancel_order",+ "trading_place_order",+ "trading_quote",+}+_SYMBOL_ARGUMENT_KEYS = {+ "code",+ "codes",+ "symbol",+ "symbols",+ "ticker",+ "tickers",+ "underlying",+ "underlyings",+}+_PRICE_FIELDS = {"open", "high", "low", "close", "adj_close", "price"}+_TIMESTAMP_FIELDS = ("trade_date", "date", "datetime", "timestamp", "time", "index")+_MAX_GENERIC_EVIDENCE = 2_000++# Project-style canonical symbols. A bare model-generated ticker is still+# checked when it appears under a symbol argument key, but it is not accepted+# as user-provided identity because it lacks venue information.+_CANONICAL_SYMBOL_RE = re.compile(+ r"(?<![A-Za-z0-9_])(?:"+ r"\d{3,6}\.(?:SH|SZ|BJ|SS|HK|KS|KQ)|"+ r"[A-Z][A-Z0-9&.-]{0,19}\.(?:US|NS|BO|FX)|"+ r"[A-Z0-9]{2,15}(?:-|/)(?:USDT|USDC|USD|BTC|ETH)|"+ r"[A-Z0-9]{2,15}=[FX]"+ r")(?![A-Za-z0-9_])",+ re.IGNORECASE,+)+_ACTIONABLE_MARKET_RE = re.compile(+ r"(?:\bbuy\b|\bsell\b|\bentry\b|\btarget price\b|\bcurrent price\b|"+ r"\blatest price\b|\bprice of\b|\btrade\b|"+ r"\bvaluation of\b|\bwhat (?:is|are) .{1,80} worth\b|"+ r"\bis .{1,80} (?:listed|publicly traded)\b|"+ r"买入|卖出|入场|目标价|现价|最新价|股价|交易价格|估值|值多少钱|"+ r".{1,40}(?:是否|有没有|已经|已)(?:在.{0,20})?上市)",+ re.IGNORECASE,+)+_PRIVATE_ASSERTION_RE = re.compile(+ r"(?:\b(?:is|remains|still)\s+(?:an?\s+)?(?:private company|privately held)\b|"+ r"\bnot publicly traded\b|\bunlisted company\b|"+ r"(?:是|仍是|属于)(?:一家)?(?:私人|私营|非上市)公司|未上市|没有上市)",+ re.IGNORECASE,+)+_PRICE_CONTEXT_RE = re.compile(+ r"(?:\b(?:opening|open|high|low|closing|close|price|quote)\b|"+ r"\b(?:entry|buy|target|support|resistance)\s+(?:price|level)\b|"+ r"开盘价?|最高价?|最低价?|收盘价?|买入价|入场价|目标价|支撑位?|阻力位?|"+ r"现价|报价|价格|价位)",+ re.IGNORECASE,+)+_DERIVATION_RE = re.compile(+ r"(?:\bderived\b|\bcalculated\b|\bformula\b|\bbased on\b|计算|推导|公式|基于)",+ re.IGNORECASE,+)+_NUMBER_RE = re.compile(+ r"(?<![A-Za-z0-9_])[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?"+ r"(?![A-Za-z0-9_])"+)+_DATE_RE = re.compile(r"\b(?:19|20)\d{2}[-/]\d{1,2}[-/]\d{1,2}\b")+_TABLE_SEPARATOR_RE = re.compile(r"^:?-{3,}:?$")++_TABLE_FIELD_ALIASES = {+ "open": "open",+ "opening": "open",+ "opening price": "open",+ "开盘": "open",+ "开盘价": "open",+ "high": "high",+ "highest": "high",+ "最高": "high",+ "最高价": "high",+ "low": "low",+ "lowest": "low",+ "最低": "low",+ "最低价": "low",+ "close": "close",+ "closing": "close",+ "closing price": "close",+ "收盘": "close",+ "收盘价": "close",+}+_DATE_HEADERS = {"date", "datetime", "trade date", "timestamp", "日期", "交易日", "时间"}+_SYMBOL_HEADERS = {"symbol", "ticker", "code", "标的", "代码", "证券代码"}+++def _utc_now() -> str:+ """Return an audit-friendly UTC timestamp."""+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+++def _normalize_symbol(value: Any) -> str:+ """Normalize a symbol for exact identity comparison."""+ return str(value or "").strip().upper()+++def _query_key(value: Any) -> str:+ """Normalize resolver queries into stable state-machine keys."""+ return " ".join(str(value or "").casefold().split())+++def _json_object(value: Any) -> dict[str, Any] | None:+ """Parse a JSON object from a tool result when possible."""+ if isinstance(value, dict):+ return value+ if not isinstance(value, str):+ return None+ try:+ parsed = json.loads(value)+ except (json.JSONDecodeError, TypeError):+ return None+ return parsed if isinstance(parsed, dict) else None+++def _is_number(value: Any) -> bool:+ """Return whether a value is a finite JSON-style number, excluding bool."""+ return (+ isinstance(value, (int, float))+ and not isinstance(value, bool)+ and math.isfinite(float(value))+ )+++def _infer_venue(symbol: str) -> str | None:+ """Infer a coarse venue from a project symbol."""+ upper = _normalize_symbol(symbol)+ suffixes = {+ ".US": "us",+ ".SH": "shanghai",+ ".SS": "shanghai",+ ".SZ": "shenzhen",+ ".BJ": "beijing",+ ".HK": "hong_kong",+ ".KS": "kospi",+ ".KQ": "kosdaq",+ ".NS": "nse",+ ".BO": "bse",+ ".FX": "forex",+ }+ for suffix, venue in suffixes.items():+ if upper.endswith(suffix):+ return venue+ if "-" in upper or "/" in upper:+ return "crypto_or_fx"+ if upper.endswith("=F"):+ return "futures"+ return None+++def _infer_currency(symbol: str) -> str | None:+ """Infer quote currency without performing an implicit conversion."""+ upper = _normalize_symbol(symbol)+ suffixes = {+ ".US": "USD",+ ".SH": "CNY",+ ".SS": "CNY",+ ".SZ": "CNY",+ ".BJ": "CNY",+ ".HK": "HKD",+ ".KS": "KRW",+ ".KQ": "KRW",+ ".NS": "INR",+ ".BO": "INR",+ }+ for suffix, currency in suffixes.items():+ if upper.endswith(suffix):+ return currency+ for separator in ("-", "/"):+ if separator in upper:+ quote = upper.rsplit(separator, 1)[-1]+ if 3 <= len(quote) <= 5:+ return quote+ return None+++def _infer_instrument_type(symbol: str, candidate_type: Any = None) -> str:+ """Normalize provider types into the identity contract."""+ raw = str(candidate_type or "").strip().casefold()+ if "fund" in raw or "etf" in raw or "trust" in raw:+ return "fund"+ if "crypto" in raw:+ return "crypto"+ if "future" in raw:+ return "future"+ if "option" in raw:+ return "option"+ if "forex" in raw or raw == "currency":+ return "forex"+ upper = _normalize_symbol(symbol)+ if upper.endswith("=F"):+ return "future"+ if upper.endswith(".FX"):+ return "forex"+ if "-" in upper or "/" in upper:+ return "crypto"+ return "listed_security"+++def _is_exchange_alias_conflict(left: str, right: str) -> bool:+ """Return whether two symbols silently switch Shanghai suffix conventions."""+ left_symbol = _normalize_symbol(left)+ right_symbol = _normalize_symbol(right)+ if left_symbol == right_symbol:+ return False+ left_base, _, left_suffix = left_symbol.rpartition(".")+ right_base, _, right_suffix = right_symbol.rpartition(".")+ return (+ bool(left_base)+ and left_base == right_base+ and {left_suffix, right_suffix} == {"SH", "SS"}+ )+++@dataclass(frozen=True)+class IdentityRecord:+ """One versioned entity-to-instrument resolution result."""++ query: str+ status: str+ symbol: str | None = None+ venue: str | None = None+ instrument_type: str | None = None+ currency: str | None = None+ source_tool_call_id: str | None = None+ source: list[str] = field(default_factory=list)+ candidates: list[dict[str, Any]] = field(default_factory=list)+ version: int = 1+ updated_at: str = field(default_factory=_utc_now)+++@dataclass(frozen=True)+class EvidenceRecord:+ """One observed, unavailable, or derived numeric evidence item."""++ call_id: str+ tool: str+ symbol: str | None+ source: str+ timestamp: str | None+ field: str+ value: int | float | None+ status: str+ currency: str | None = None+ venue: str | None = None+ currency_conversion: str | None = None+++@dataclass(frozen=True)+class ToolAuthorization:+ """Deterministic decision made before a tool starts."""++ allowed: bool+ error_code: str | None = None+ message: str | None = None+ symbols: tuple[str, ...] = ()++ def error_payload(self, tool_name: str, identity: Mapping[str, Any]) -> str:+ """Render a blocked tool call as a normal structured error result."""+ return json.dumps(+ {+ "status": "error",+ "error_code": self.error_code or "identity_gate_blocked",+ "tool": tool_name,+ "message": self.message or "Tool call blocked by identity gate",+ "symbols": list(self.symbols),+ "identity": dict(identity),+ "required_action": (+ "Call search_symbol in a separate assistant tool turn, wait for "+ "its result, then reuse the exact locked symbol and venue."+ ),+ },+ ensure_ascii=False,+ )+++@dataclass(frozen=True)+class ValidationResult:+ """Final-answer grounding decision."""++ valid: bool+ issues: list[dict[str, Any]] = field(default_factory=list)+++class GroundingLedger:+ """Run-scoped identity state machine and evidence ledger."""++ def __init__(+ self,+ *,+ run_dir: Path,+ user_message: str,+ history: Sequence[Mapping[str, Any]] | None = None,+ ) -> None:+ """Create a ledger and seed only authoritative prior identities.++ Args:+ run_dir: Active run directory.+ user_message: Current user request.+ history: Optional prior message history. It remains available to+ the model, but is deliberately not an authorization source for+ this run: stale identities from an earlier user subject must+ not unlock a new subject's tools.+ """+ self.run_dir = Path(run_dir)+ self.user_message = user_message+ self._identities: dict[str, IdentityRecord] = {}+ self._evidence: list[EvidenceRecord] = []+ self._tool_failures: list[dict[str, Any]] = []+ self._validations: list[dict[str, Any]] = []+ self._identity_required = bool(_ACTIONABLE_MARKET_RE.search(user_message))+ self._buffer_output = self._identity_required++ self._seed_symbols(user_message, source="user_message")+ self.persist()++ @property+ def authorized_symbols(self) -> set[str]:+ """Return exact symbols locked before the next tool batch."""+ return {+ record.symbol+ for record in self._identities.values()+ if record.status == "locked" and record.symbol+ }++ @property+ def identity_status(self) -> str:+ """Return the aggregate first-class identity state."""+ records = list(self._identities.values())+ if not records:+ return "unresolved" if self._identity_required else "not_required"+ statuses = {record.status for record in records}+ for blocking in ("conflicting", "ambiguous", "invalidated", "unresolved"):+ if blocking in statuses:+ return blocking+ if "locked" in statuses:+ return "locked"+ if statuses == {"not_found"}:+ return "not_found"+ return "unresolved"++ @property+ def should_buffer_output(self) -> bool:+ """Return whether unverified model prose must be hidden from live sinks."""+ return self._buffer_output or bool(self._evidence)++ @property+ def validation_count(self) -> int:+ """Return the number of final drafts checked so far."""+ return len(self._validations)++ def identity_summary(self) -> dict[str, Any]:+ """Return compact identity state for traces and tool errors."""+ return {+ "status": self.identity_status,+ "authorized_symbols": sorted(self.authorized_symbols),+ "records": [asdict(record) for record in self._identities.values()],+ }++ def authorize_tool_call(+ self,+ tool_name: str,+ arguments: Mapping[str, Any],+ *,+ batch_authorized_symbols: Iterable[str],+ call_id: str,+ batch_identity_status: str | None = None,+ ) -> ToolAuthorization:+ """Authorize against identity state frozen before the whole LLM batch.++ Args:+ tool_name: Requested tool.+ arguments: Model-supplied arguments.+ batch_authorized_symbols: Snapshot taken before processing any call+ from this assistant response.+ call_id: Provider tool-call identity.+ batch_identity_status: Aggregate identity status from the same+ pre-batch snapshot. Defaults to the current state for direct+ callers outside the Agent loop.++ Returns:+ An allow/block decision. Resolver calls are allowed but their result+ cannot affect another call in this same batch.+ """+ if tool_name == _RESOLVER_TOOL:+ self._identity_required = True+ self._buffer_output = True+ self._begin_resolution(str(arguments.get("query") or ""), call_id)+ return ToolAuthorization(allowed=True)++ if self._is_private_company_skill(tool_name, arguments):+ 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:+ 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."+ ),+ )+ return ToolAuthorization(allowed=True)++ symbols = tuple(self._extract_symbol_arguments(arguments))+ if not symbols:+ return ToolAuthorization(allowed=True)++ self._identity_required = True+ self._buffer_output = True+ 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:+ return ToolAuthorization(+ allowed=False,+ error_code=(+ "identity_conflict"+ if frozen_status in {"ambiguous", "conflicting", "invalidated"}+ else "identity_required"+ ),+ message=(+ "A canonical, non-conflicting identity was not locked before this "+ "assistant tool-call batch started. A resolver result from this same "+ "batch cannot be consumed."+ ),+ symbols=symbols,+ )++ mismatched = tuple(+ symbol+ for symbol in symbols+ if self._match_authorized_symbol(tool_name, symbol, authorized) is None+ )+ if mismatched:+ return ToolAuthorization(+ allowed=False,+ error_code="identity_mismatch",+ message=(+ "Consumer symbol/venue differs from the locked resolver identity; "+ "silent suffix or exchange rewrites are forbidden."+ ),+ symbols=mismatched,+ )+ return ToolAuthorization(allowed=True, symbols=symbols)++ @staticmethod+ def _match_authorized_symbol(+ tool_name: str,+ requested_symbol: str,+ authorized_symbols: Iterable[str],+ ) -> str | None:+ """Map a consumer argument to one unique locked canonical symbol.++ Most repository tools accept the canonical symbol verbatim. A small+ explicit set of U.S.-only APIs and broker transports require a bare+ ticker; for those tools only, ``AAPL`` may consume ``AAPL.US``. Venue+ aliases such as ``.SS`` and ``.SH`` are never treated as equivalent.++ Args:+ tool_name: Requested consumer tool.+ requested_symbol: Model-supplied symbol argument.+ authorized_symbols: Symbols locked before the tool batch.++ Returns:+ The unique canonical identity consumed by the argument, or ``None``.+ """+ requested = _normalize_symbol(requested_symbol)+ authorized = {_normalize_symbol(item) for item in authorized_symbols}+ if requested in authorized:+ return requested+ if tool_name not in _BARE_US_TICKER_TOOLS or "." in requested:+ return None+ matches = [+ symbol+ for symbol in authorized+ if symbol.endswith(".US") and symbol.rsplit(".", 1)[0] == requested+ ]+ return matches[0] if len(matches) == 1 else None++ def ingest_tool_result(+ self,+ *,+ tool_name: str,+ arguments: Mapping[str, Any],+ result: str,+ call_id: str,+ success: bool,+ ) -> None:+ """Consume the full untruncated tool result and persist its evidence.++ Args:+ tool_name: Executed tool name.+ arguments: Exact normalized tool arguments.+ result: Full raw result, before model-context truncation.+ call_id: Provider tool-call identity.+ success: Result-envelope success classification.+ """+ payload = _json_object(result)+ if not success:+ self._record_tool_failure(tool_name, call_id, result)+ if tool_name == _RESOLVER_TOOL:+ self._finish_failed_resolution(arguments, call_id)+ self.persist()+ return++ if tool_name == _RESOLVER_TOOL:+ self._ingest_resolution(arguments, payload, call_id)+ elif tool_name == "get_market_data":+ self._ingest_market_data(arguments, payload, call_id)+ elif payload is not None:+ self._ingest_generic_numeric(tool_name, arguments, payload, call_id)+ self.persist()++ def validate_final_answer(self, content: str) -> ValidationResult:+ """Validate identity assertions and numeric price claims.++ Args:+ content: Candidate assistant answer.++ Returns:+ A deterministic validation result. A record containing only the+ answer hash and structured issues is appended to the artifact.+ """+ issues: list[dict[str, Any]] = []+ issues.extend(self._validate_identity(content))+ issues.extend(self._validate_price_claims(content))+ result = ValidationResult(valid=not issues, issues=issues)+ self._validations.append(+ {+ "attempt": len(self._validations) + 1,+ "checked_at": _utc_now(),+ "content_sha256": hashlib.sha256(content.encode("utf-8")).hexdigest(),+ "valid": result.valid,+ "issues": issues,+ }+ )+ self.persist()+ return result++ def correction_prompt(self, validation: ValidationResult) -> str:+ """Build bounded feedback for one rejected model draft."""+ lines = [+ "[GROUNDING GATE] The previous draft was rejected and was not released to the user.",+ "Correct every issue using the existing structured identity and tool evidence:",+ ]+ for issue in validation.issues[:12]:+ lines.append(f"- {issue.get('message', issue.get('code', 'grounding error'))}")+ lines.extend(+ [+ "Reuse the exact locked symbol and venue.",+ "For every derived number, label it as derived and show the source inputs and formula.",+ "If evidence is unavailable or conflicting, say so and ask for clarification; do not guess.",+ ]+ )+ return "\n".join(lines)++ 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))+ price_records = self._price_records()+ if price_records:+ by_symbol: dict[str, list[EvidenceRecord]] = {}+ for record in price_records:+ by_symbol.setdefault(record.symbol or "unknown", []).append(record)+ facts = []+ for symbol, records in sorted(by_symbol.items()):+ values = [float(record.value) for record in records if record.value is not None]+ currency = next((record.currency for record in records if record.currency), None)+ sources = sorted({record.source for record in records if record.source})+ source_label = "/".join(sources) if sources else "unknown"+ unit = f" {currency}" if currency else ""+ facts.append(+ f"{symbol}: {min(values):g}–{max(values):g}{unit} "+ f"(source: {source_label}; currency conversion: none)"+ )+ joined = ";".join(facts) if is_zh else "; ".join(facts)+ if is_zh:+ return (+ "为避免输出与工具证据冲突的价格,我已拒绝上一版答案。"+ f"当前可验证的已观测 OHLC 范围是:{joined}。"+ "在重新核对标的或明确展示推导公式前,我不会生成买入价。"+ )+ return (+ "I rejected the previous draft because its prices conflicted with tool evidence. "+ f"The verified observed OHLC range is: {joined}. "+ "I will not invent an entry price without a visible derivation or refreshed evidence."+ )+ if is_zh:+ return (+ "当前无法安全确认标的身份或价格证据,因此没有生成交易结论。"+ "请确认候选证券代码和交易所后再继续。"+ )+ return (+ "I could not safely lock the instrument identity or price evidence, so I did not "+ "produce a trading conclusion. Please confirm the candidate symbol and venue."+ )++ def persist(self) -> None:+ """Atomically persist the current structured ledger."""+ artifact_dir = self.run_dir / "artifacts"+ try:+ artifact_dir.mkdir(parents=True, exist_ok=True)+ path = artifact_dir / GROUNDING_ARTIFACT+ temp = path.with_suffix(path.suffix + ".tmp")+ payload = {+ "schema_version": 1,+ "updated_at": _utc_now(),+ "identity": self.identity_summary(),+ "evidence": [asdict(record) for record in self._evidence],+ "tool_failures": list(self._tool_failures),+ "validations": list(self._validations),+ }+ temp.write_text(+ json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n",+ encoding="utf-8",+ )+ temp.replace(path)+ except OSError:+ # Grounding decisions remain in memory; a read-only/broken artifact+ # directory must not crash the agent's error path.+ return++ def _seed_symbols(self, text: str, *, source: str) -> None:+ """Lock exact symbols explicitly supplied by a user."""+ for match in _CANONICAL_SYMBOL_RE.finditer(text or ""):+ symbol = _normalize_symbol(match.group(0))+ key = f"explicit:{symbol}"+ existing = self._identities.get(key)+ version = existing.version + 1 if existing else 1+ self._identities[key] = IdentityRecord(+ query=symbol,+ status="locked",+ symbol=symbol,+ venue=_infer_venue(symbol),+ instrument_type=_infer_instrument_type(symbol),+ currency=_infer_currency(symbol),+ source_tool_call_id=source,+ source=[source],+ version=version,+ )+ self._identity_required = True+ self._buffer_output = True++ def _begin_resolution(self, query: str, call_id: str) -> None:+ """Enter unresolved state before the resolver executes."""+ key = _query_key(query) or f"call:{call_id}"+ existing = self._identities.get(key)+ self._identities[key] = IdentityRecord(+ query=query,+ status="unresolved",+ source_tool_call_id=call_id,+ version=(existing.version + 1) if existing else 1,+ )+ self.persist()++ def _finish_failed_resolution(+ self,+ arguments: Mapping[str, Any],+ call_id: str,+ ) -> None:+ """Mark transport/business failure as invalidated, never not-found."""+ query = str(arguments.get("query") or "")+ key = _query_key(query) or f"call:{call_id}"+ existing = self._identities.get(key)+ self._identities[key] = IdentityRecord(+ query=query,+ status="invalidated",+ source_tool_call_id=call_id,+ version=(existing.version + 1) if existing else 1,+ )++ def _ingest_resolution(+ self,+ arguments: Mapping[str, Any],+ payload: dict[str, Any] | None,+ call_id: str,+ ) -> None:+ """Advance unresolved identity from a structured resolver result."""+ data = payload.get("data") if isinstance(payload, dict) else None+ data = data if isinstance(data, dict) else {}+ query = str(data.get("query") or arguments.get("query") or "")+ key = _query_key(query) or f"call:{call_id}"+ existing = self._identities.get(key)+ version = (existing.version + 1) if existing else 1++ if not isinstance(payload, dict) or payload.get("ok") is False:+ self._identities[key] = IdentityRecord(+ query=query,+ status="invalidated",+ source_tool_call_id=call_id,+ version=version,+ )+ return++ raw_candidates = data.get("candidates")+ candidates = [dict(item) for item in raw_candidates if isinstance(item, dict)] if isinstance(raw_candidates, list) else []+ sources = data.get("sources") if isinstance(data.get("sources"), dict) else {}+ if not candidates:+ clean_sources = [+ str(name)+ for name, value in sources.items()+ if str(value).casefold() == "ok"+ ]+ self._identities[key] = IdentityRecord(+ query=query,+ status="not_found" if len(clean_sources) >= 2 else "invalidated",+ source_tool_call_id=call_id,+ source=clean_sources,+ candidates=[],+ version=version,+ )+ return++ chosen = self._choose_candidate(query, candidates)+ if chosen is None:+ self._identities[key] = IdentityRecord(+ query=query,+ status="ambiguous",+ source_tool_call_id=call_id,+ candidates=candidates,+ version=version,+ )+ return++ symbol = _normalize_symbol(chosen.get("symbol"))+ if not symbol:+ self._identities[key] = IdentityRecord(+ query=query,+ status="invalidated",+ source_tool_call_id=call_id,+ candidates=candidates,+ version=version,+ )+ return++ alias_conflicts = [+ record+ for record in self._identities.values()+ if record.status == "locked"+ and record.symbol+ and _is_exchange_alias_conflict(record.symbol, symbol)+ ]+ if alias_conflicts:+ conflicting = list(candidates)+ conflicting.extend(+ {"symbol": record.symbol, "source": record.source}+ for record in alias_conflicts+ )+ self._identities[key] = IdentityRecord(+ query=query,+ status="conflicting",+ source_tool_call_id=call_id,+ candidates=conflicting,+ version=version,+ )+ return++ if existing and existing.status == "locked" and existing.symbol != symbol:+ conflicting = list(candidates)+ conflicting.insert(0, {"symbol": existing.symbol, "source": existing.source})+ self._identities[key] = IdentityRecord(+ query=query,+ status="conflicting",+ source_tool_call_id=call_id,+ candidates=conflicting,+ version=version,+ )+ return++ source_names = []+ for value in [chosen.get("source"), *(chosen.get("also_from") or [])]:+ name = str(value or "").strip()+ if name and name not in source_names:+ source_names.append(name)+ venue = str(chosen.get("exchange") or chosen.get("market") or "").strip() or _infer_venue(symbol)+ self._identities[key] = IdentityRecord(+ query=query,+ status="locked",+ symbol=symbol,+ venue=venue,+ instrument_type=_infer_instrument_type(symbol, chosen.get("type")),+ currency=_infer_currency(symbol),+ source_tool_call_id=call_id,+ source=source_names,+ candidates=candidates,+ version=version,+ )++ @staticmethod+ def _choose_candidate(+ query: str,+ candidates: list[dict[str, Any]],+ ) -> dict[str, Any] | None:+ """Choose only a unique or strongly corroborated resolver candidate."""+ if len(candidates) == 1:+ return candidates[0]+ normalized_query = re.sub(r"[^a-z0-9\u3400-\u9fff]", "", query.casefold())+ exact: list[dict[str, Any]] = []+ strong: list[dict[str, Any]] = []+ for candidate in candidates:+ symbol = _normalize_symbol(candidate.get("symbol"))+ base = symbol.split(".", 1)[0].split("-", 1)[0].split("/", 1)[0]+ name = str(candidate.get("name") or "")+ comparable = {+ re.sub(r"[^a-z0-9\u3400-\u9fff]", "", base.casefold()),+ re.sub(r"[^a-z0-9\u3400-\u9fff]", "", name.casefold()),+ re.sub(r"[^a-z0-9\u3400-\u9fff]", "", symbol.casefold()),+ }+ if normalized_query and normalized_query in comparable:+ exact.append(candidate)+ if candidate.get("also_from") or candidate.get("cik"):+ strong.append(candidate)+ if len(exact) == 1:+ return exact[0]+ if len(strong) == 1:+ return strong[0]+ return None++ def _authorize_private_company_skill(self) -> ToolAuthorization:+ """Keep private-company routing symmetric with locked listing evidence."""+ locked_listings = [+ record+ for record in self._identities.values()+ if record.status == "locked"+ and record.instrument_type in {"listed_security", "fund"}+ ]+ if locked_listings:+ return ToolAuthorization(+ allowed=False,+ error_code="identity_conflict",+ message=(+ "A resolver has locked this entity to a listed security. Model memory "+ "cannot replace that evidence with a private-company workflow."+ ),+ symbols=tuple(+ record.symbol for record in locked_listings if record.symbol+ ),+ )+ if self.identity_status == "not_found" or not self._identity_required:+ return ToolAuthorization(allowed=True)+ return ToolAuthorization(+ allowed=False,+ error_code="identity_required",+ message=(+ "Private-company routing requires a completed resolver result with clean "+ "not_found status; current identity is unresolved, ambiguous, or invalidated."+ ),+ )++ @staticmethod+ def _is_private_company_skill(+ tool_name: str,+ arguments: Mapping[str, Any],+ ) -> bool:+ """Return whether this call selects a private-company skill."""+ if tool_name != "load_skill":+ return False+ name = str(arguments.get("name") or "").strip().casefold()+ return name in _PRIVATE_COMPANY_SKILL_NAMES or (+ "private" in name and "company" in name+ )++ @staticmethod+ def _extract_symbol_arguments(arguments: Mapping[str, Any]) -> list[str]:+ """Extract model-selected identities from well-known argument keys."""+ symbols: list[str] = []+ for key, value in arguments.items():+ if str(key).casefold() not in _SYMBOL_ARGUMENT_KEYS:+ continue+ values = value if isinstance(value, (list, tuple, set, frozenset)) else [value]+ for item in values:+ if not isinstance(item, (str, int)):+ continue+ symbol = _normalize_symbol(item)+ if symbol and symbol not in symbols:+ symbols.append(symbol)+ return symbols++ def _record_tool_failure(self, tool_name: str, call_id: str, result: str) -> None:+ """Store structured unavailable evidence for failed business envelopes."""+ payload = _json_object(result) or {}+ self._tool_failures.append(+ {+ "call_id": call_id,+ "tool": tool_name,+ "status": "unavailable",+ "error_code": payload.get("error_code"),+ "message": str(payload.get("error") or payload.get("message") or "tool failed")[:500],+ "recorded_at": _utc_now(),+ }+ )++ def _ingest_market_data(+ self,+ arguments: Mapping[str, Any],+ payload: dict[str, Any] | None,+ call_id: str,+ ) -> None:+ """Convert full OHLCV payloads into source-linked evidence rows."""+ if payload is None:+ self._record_tool_failure("get_market_data", call_id, "malformed JSON result")+ return+ requested_source = str(arguments.get("source") or "auto")+ provenance = payload.get("_provenance")+ provenance = provenance if isinstance(provenance, dict) else {}+ for raw_symbol, raw_rows in payload.items():+ if str(raw_symbol).startswith("_"):+ continue+ symbol = _normalize_symbol(raw_symbol)+ rows = raw_rows.get("data") if isinstance(raw_rows, dict) else raw_rows+ if not isinstance(rows, list):+ continue+ symbol_provenance = provenance.get(raw_symbol)+ actual_source = (+ str(symbol_provenance.get("source"))+ if isinstance(symbol_provenance, dict) and symbol_provenance.get("source")+ else requested_source+ )+ currency_conversion = (+ str(symbol_provenance.get("currency_conversion"))+ if isinstance(symbol_provenance, dict)+ and symbol_provenance.get("currency_conversion")+ else None+ )+ for row in rows:+ if not isinstance(row, dict):+ continue+ timestamp = next(+ (str(row[key]) for key in _TIMESTAMP_FIELDS if row.get(key) is not None),+ None,+ )+ for field_name, value in row.items():+ normalized_field = str(field_name).casefold()+ if normalized_field in _TIMESTAMP_FIELDS or not _is_number(value):+ continue+ self._evidence.append(+ EvidenceRecord(+ call_id=call_id,+ tool="get_market_data",+ symbol=symbol,+ source=actual_source,+ timestamp=timestamp,+ field=normalized_field,+ value=value,+ status="observed",+ currency=_infer_currency(symbol),+ venue=_infer_venue(symbol),+ currency_conversion=currency_conversion,+ )+ )+ unresolved = payload.get("_unresolved")+ if isinstance(unresolved, list):+ for raw_symbol in unresolved:+ symbol = _normalize_symbol(raw_symbol)+ self._evidence.append(+ EvidenceRecord(+ call_id=call_id,+ tool="get_market_data",+ symbol=symbol,+ source=requested_source,+ timestamp=None,+ field="availability",+ value=None,+ status="unavailable",+ currency=_infer_currency(symbol),+ venue=_infer_venue(symbol),+ )+ )++ def _ingest_generic_numeric(+ self,+ tool_name: str,+ arguments: Mapping[str, Any],+ payload: dict[str, Any],+ call_id: str,+ ) -> None:+ """Flatten bounded numeric leaves from other market-sensitive tools."""+ symbols = self._extract_symbol_arguments(arguments)+ symbol = symbols[0] if len(symbols) == 1 else None+ if symbol:+ symbol = self._match_authorized_symbol(+ tool_name,+ symbol,+ self.authorized_symbols,+ ) or symbol+ source = str(payload.get("source") or tool_name)+ remaining = _MAX_GENERIC_EVIDENCE++ def visit(value: Any, path: str) -> None:+ nonlocal remaining+ if remaining <= 0:+ return+ if _is_number(value):+ self._evidence.append(+ EvidenceRecord(+ call_id=call_id,+ tool=tool_name,+ symbol=symbol,+ source=source,+ timestamp=None,+ field=path or "value",+ value=value,+ status="observed",+ currency=_infer_currency(symbol or ""),+ venue=_infer_venue(symbol or ""),+ )+ )+ remaining -= 1+ return+ if isinstance(value, dict):+ for key, item in value.items():+ visit(item, f"{path}.{key}" if path else str(key))+ elif isinstance(value, list):+ for index, item in enumerate(value):+ visit(item, f"{path}[{index}]")++ visit(payload, "")++ def _validate_identity(self, content: str) -> list[dict[str, Any]]:+ """Validate aggregate state and listed/private contradictions."""+ issues: list[dict[str, Any]] = []+ status = self.identity_status+ if self._identity_required and status in {+ "unresolved",+ "ambiguous",+ "conflicting",+ "invalidated",+ }:+ issues.append(+ {+ "code": "identity_not_locked",+ "status": status,+ "message": f"Instrument identity is {status}; a final market conclusion requires locked identity.",+ }+ )+ listed = [+ record+ for record in self._identities.values()+ if record.status == "locked"+ and record.instrument_type in {"listed_security", "fund"}+ ]+ if listed and _PRIVATE_ASSERTION_RE.search(content):+ symbols = sorted(record.symbol for record in listed if record.symbol)+ issues.append(+ {+ "code": "listed_identity_relabelled_private",+ "symbols": symbols,+ "message": (+ f"Locked listed identity {', '.join(symbols)} was relabelled as private/unlisted "+ "without a conflicting resolver result."+ ),+ }+ )+ return issues++ def _validate_price_claims(self, content: str) -> list[dict[str, Any]]:+ """Check Markdown OHLC tables and price prose against observed records."""+ issues, table_lines = self._validate_price_tables(content)+ records = self._price_records()+ has_price_claim = any(+ self._numbers_without_dates_or_percent(line)+ for index, line in enumerate(content.splitlines())+ if index in table_lines+ )+ for index, line in enumerate(content.splitlines()):+ 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):+ if not _PRICE_CONTEXT_RE.search(segment):+ continue+ values = self._numbers_without_dates_or_percent(segment)+ if not values:+ continue+ has_price_claim = True+ symbol = self._symbol_for_claim(segment, records) or line_symbol+ if self._is_explicit_derivation(segment, records, symbol):+ continue+ for value in values:+ issue = self._compare_price_claim(+ value=value,+ records=records,+ field_name=None,+ date_value=None,+ symbol=symbol,+ claim=segment.strip(),+ )+ if issue:+ issues.append(issue)+ if has_price_claim and records:+ issues.extend(self._validate_price_provenance(content, records))+ return self._dedupe_issues(issues)++ @staticmethod+ def _symbol_for_claim(+ content: str,+ records: Sequence[EvidenceRecord],+ ) -> str | None:+ """Return one canonical evidence symbol explicitly named in a claim."""+ known = {record.symbol for record in records if record.symbol}+ matches = {+ _normalize_symbol(match.group(0))+ for match in _CANONICAL_SYMBOL_RE.finditer(content)+ if _normalize_symbol(match.group(0)) in known+ }+ return next(iter(matches)) if len(matches) == 1 else None++ def _validate_price_provenance(+ self,+ content: str,+ records: Sequence[EvidenceRecord],+ ) -> list[dict[str, Any]]:+ """Require canonical symbol, actual source, and quote currency in output."""+ issues: list[dict[str, Any]] = []+ folded = content.casefold()+ symbols = sorted({record.symbol for record in records if record.symbol})+ mentioned = [symbol for symbol in symbols if symbol.casefold() in folded]+ if not mentioned:+ issues.append(+ {+ "code": "canonical_symbol_not_surfaced",+ "symbols": symbols,+ "message": (+ "A price claim must surface its locked canonical symbol and venue suffix."+ ),+ }+ )+ target_symbols = set(mentioned or (symbols if len(symbols) == 1 else []))+ target_records = [+ record+ for record in records+ if not target_symbols or record.symbol in target_symbols+ ]++ sources = sorted(+ {+ record.source+ for record in target_records+ if record.source and record.source.casefold() not in {"auto", "unknown"}+ }+ )+ missing_sources = [source for source in sources if source.casefold() not in folded]+ if missing_sources:+ issues.append(+ {+ "code": "data_source_not_surfaced",+ "sources": missing_sources,+ "message": (+ "Price claims must name the actual data source: "+ + ", ".join(missing_sources)+ + "."+ ),+ }+ )++ currencies = sorted(+ {record.currency for record in target_records if record.currency}+ )+ missing_currencies = [+ currency+ for currency in currencies+ if not self._currency_is_surfaced(currency, content)+ ]+ if missing_currencies:+ issues.append(+ {+ "code": "currency_not_surfaced",+ "currencies": missing_currencies,+ "message": (+ "Price claims must name their quote currency: "+ + ", ".join(missing_currencies)+ + "."+ ),+ }+ )+ return issues++ @staticmethod+ def _currency_is_surfaced(currency: str, content: str) -> bool:+ """Return whether a quote currency or an unambiguous alias is visible."""+ aliases = {+ "USD": ("usd", "us$", "美元"),+ "CNY": ("cny", "rmb", "人民币"),+ "HKD": ("hkd", "hk$", "港元"),+ "KRW": ("krw", "韩元"),+ "INR": ("inr", "印度卢比"),+ }+ folded = content.casefold()+ tokens = aliases.get(currency.upper(), (currency.casefold(),))+ return any(token.casefold() in folded for token in tokens)++ def _validate_price_tables(+ self,+ content: str,+ ) -> tuple[list[dict[str, Any]], set[int]]:+ """Validate field/date-specific claims in Markdown OHLC tables."""+ lines = content.splitlines()+ issues: list[dict[str, Any]] = []+ consumed: set[int] = set()+ index = 0+ records = self._price_records()+ while index + 1 < len(lines):+ header = self._table_cells(lines[index])+ separator = self._table_cells(lines[index + 1])+ if not header or not separator or len(header) != len(separator):+ index += 1+ continue+ if not all(_TABLE_SEPARATOR_RE.match(cell.replace(" ", "")) for cell in separator):+ index += 1+ continue+ field_columns = {+ position: _TABLE_FIELD_ALIASES[cell.strip().casefold()]+ for position, cell in enumerate(header)+ if cell.strip().casefold() in _TABLE_FIELD_ALIASES+ }+ if not field_columns:+ index += 1+ continue+ date_column = next(+ (position for position, cell in enumerate(header) if cell.strip().casefold() in _DATE_HEADERS),+ None,+ )+ symbol_column = next(+ (position for position, cell in enumerate(header) if cell.strip().casefold() in _SYMBOL_HEADERS),+ None,+ )+ consumed.update({index, index + 1})+ row_index = index + 2+ while row_index < len(lines):+ row = self._table_cells(lines[row_index])+ if not row or len(row) != len(header):+ break+ consumed.add(row_index)+ date_value = row[date_column].strip() if date_column is not None else None+ symbol = _normalize_symbol(row[symbol_column]) if symbol_column is not None else None+ for position, field_name in field_columns.items():+ values = self._numbers_without_dates_or_percent(row[position])+ if len(values) != 1:+ continue+ issue = self._compare_price_claim(+ value=values[0],+ records=records,+ field_name=field_name,+ date_value=date_value,+ symbol=symbol,+ claim=row[position].strip(),+ )+ if issue:+ issues.append(issue)+ row_index += 1+ index = max(row_index, index + 1)+ return issues, consumed++ @staticmethod+ def _table_cells(line: str) -> list[str]:+ """Split one Markdown table row, or return an empty list."""+ if "|" not in line:+ return []+ stripped = line.strip()+ if stripped.startswith("|"):+ stripped = stripped[1:]+ if stripped.endswith("|"):+ stripped = stripped[:-1]+ return [cell.strip() for cell in stripped.split("|")]++ def _compare_price_claim(+ self,+ *,+ value: float,+ records: list[EvidenceRecord],+ field_name: str | None,+ date_value: str | None,+ symbol: str | None,+ claim: str,+ ) -> dict[str, Any] | None:+ """Compare one unlabelled observed claim to the closest evidence value."""+ candidates = records+ if symbol:+ candidates = [record for record in candidates if record.symbol == symbol]+ symbols = sorted({record.symbol for record in candidates if record.symbol})+ if not symbol and len(symbols) == 1:+ symbol = symbols[0]+ elif not symbol and len(symbols) > 1:+ return {+ "code": "numeric_claim_ambiguous_symbol",+ "claim": claim,+ "value": value,+ "symbols": symbols,+ "message": (+ f"Price claim {value:g} is ambiguous across multiple evidence symbols; "+ "name the canonical symbol explicitly."+ ),+ }+ if field_name:+ candidates = [record for record in candidates if record.field == field_name]+ if date_value:+ candidates = [+ record+ for record in candidates+ if record.timestamp and record.timestamp.startswith(date_value)+ ]+ if not candidates:+ return {+ "code": "numeric_claim_unavailable",+ "claim": claim,+ "value": value,+ "symbol": symbol,+ "field": field_name,+ "date": date_value,+ "message": f"Price claim {value:g} has no matching observed tool evidence.",+ }+ observed = [float(record.value) for record in candidates if record.value is not None]+ if any(abs(value - item) <= max(abs(item) * 0.005, 1e-9) for item in observed):+ return None+ return {+ "code": "numeric_claim_conflict",+ "claim": claim,+ "value": value,+ "symbol": symbol,+ "field": field_name,+ "date": date_value,+ "observed_min": min(observed),+ "observed_max": max(observed),+ "source_tool_call_ids": sorted({record.call_id for record in candidates}),+ "message": (+ f"Price claim {value:g} conflicts with observed {field_name or 'OHLC'} "+ f"evidence {min(observed):g}–{max(observed):g}."+ ),+ }++ def _price_records(self) -> list[EvidenceRecord]:+ """Return observed OHLC/price evidence only."""+ return [+ record+ for record in self._evidence+ if record.status == "observed"+ and record.field in _PRICE_FIELDS+ and record.value is not None+ ]++ @staticmethod+ def _numbers_without_dates_or_percent(text: str) -> list[float]:+ """Extract numbers while excluding dates and percentages."""+ without_dates = _DATE_RE.sub(" ", text)+ values: list[float] = []+ for match in _NUMBER_RE.finditer(without_dates):+ tail = without_dates[match.end() :].lstrip()+ if tail.startswith(("%", "%")):+ continue+ try:+ values.append(float(match.group(0).replace(",", "")))+ except ValueError:+ continue+ return values++ def _is_explicit_derivation(+ self,+ text: str,+ records: Sequence[EvidenceRecord],+ symbol: str | None,+ ) -> bool:+ """Allow only an arithmetically valid formula anchored to observed input."""+ if not _DERIVATION_RE.search(text):+ return False+ candidates = list(records)+ if symbol:+ candidates = [record for record in candidates if record.symbol == symbol]+ candidate_symbols = {record.symbol for record in candidates if record.symbol}+ if not symbol and len(candidate_symbols) > 1:+ return False+ observed = [+ float(record.value) for record in candidates if record.value is not None+ ]+ if not observed:+ return False++ for equals in re.finditer(r"=", text):+ left = re.search(r"([0-9.,+\-*/×÷()\s]+)$", text[: equals.start()])+ right = re.match(+ r"\s*([-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?)",+ text[equals.end() :],+ )+ if not left or not right:+ continue+ evaluated = self._evaluate_formula(left.group(1))+ if evaluated is None:+ continue+ computed, inputs = evaluated+ try:+ claimed = float(right.group(1).replace(",", ""))+ except ValueError:+ continue+ if not any(+ abs(item - value) <= max(abs(value) * 0.005, 1e-9)+ for item in inputs+ for value in observed+ ):+ continue+ if abs(computed - claimed) <= max(abs(computed) * 0.005, 1e-9):+ return True+ return False++ @staticmethod+ def _evaluate_formula(expression: str) -> tuple[float, list[float]] | None:+ """Evaluate a numeric ``+ - * /`` expression without executing code."""+ normalized = expression.replace("×", "*").replace("÷", "/").replace(",", "").strip()+ try:+ tree = ast.parse(normalized, mode="eval")+ except (SyntaxError, ValueError):+ return None+ inputs: list[float] = []++ def visit(node: ast.AST) -> float:+ if isinstance(node, ast.Expression):+ return visit(node.body)+ if isinstance(node, ast.Constant) and _is_number(node.value):+ value = float(node.value)+ inputs.append(value)+ return value+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):+ value = visit(node.operand)+ return value if isinstance(node.op, ast.UAdd) else -value+ if isinstance(node, ast.BinOp) and isinstance(+ node.op,+ (ast.Add, ast.Sub, ast.Mult, ast.Div),+ ):+ left_value = visit(node.left)+ right_value = visit(node.right)+ if isinstance(node.op, ast.Add):+ return left_value + right_value+ if isinstance(node.op, ast.Sub):+ return left_value - right_value+ if isinstance(node.op, ast.Mult):+ return left_value * right_value+ if right_value == 0:+ raise ValueError("division by zero")+ return left_value / right_value+ raise ValueError("unsupported formula")++ try:+ value = visit(tree)+ except (TypeError, ValueError, ZeroDivisionError, OverflowError):+ return None+ if len(inputs) < 2 or not math.isfinite(value):+ return None+ return value, inputs++ @staticmethod+ def _dedupe_issues(issues: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Remove duplicate validator findings while preserving order."""+ unique: list[dict[str, Any]] = []+ seen: set[str] = set()+ for issue in issues:+ key = json.dumps(issue, sort_keys=True, ensure_ascii=False, default=str)+ if key in seen:+ continue+ seen.add(key)+ unique.append(issue)+ return unique+++__all__ = [+ "GROUNDING_ARTIFACT",+ "GroundingLedger",+ "IdentityRecord",+ "ToolAuthorization",+ "ValidationResult",+]diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 667d99a91..4433d2199 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -26,6 +26,7 @@ from pathlib import Pathfrom typing import Any, Callable, Dict, List, Optionalfrom src.agent.context import ContextBuilder+from src.agent.grounding import GroundingLedgerfrom src.agent.memory import WorkspaceMemoryfrom src.agent.progress import HeartbeatTimer, ProgressEvent, _set_emitterfrom src.agent.tools import ToolRegistry@@ -462,8 +463,12 @@ def _is_tool_success(result: str) -> bool:"""Return True if the tool result does not look like an error response."""try:data = json.loads(result)- if isinstance(data, dict) and data.get("status") == "error":- return False+ if isinstance(data, dict):+ status = str(data.get("status") or "").strip().casefold()+ if status in {"error", "failed", "failure", "cancelled", "canceled"}:+ return False+ if data.get("ok") is False or data.get("success") is False:+ return Falseexcept (json.JSONDecodeError, TypeError):passreturn True@@ -534,6 +539,7 @@ class AgentLoop:self._persistent_memory = persistent_memoryself._run_iteration: int = 0self._has_run = False+ self._grounding: GroundingLedger | None = Nonedef cancel(self) -> None:"""Cancel the current loop.@@ -575,6 +581,11 @@ class AgentLoop:self.memory.run_dir = str(run_dir)state_store.save_request(run_dir, user_message, {"session_id": session_id})+ self._grounding = GroundingLedger(+ run_dir=run_dir,+ user_message=user_message,+ history=history,+ )context = ContextBuilder(self.registry, self.memory,persistent_memory=self._persistent_memory)@@ -687,10 +698,14 @@ class AgentLoop:reasoning_chars = 0reasoning_tail = ""last_reasoning_emit: float | None = None+ buffer_text_output = bool(+ self._grounding and self._grounding.should_buffer_output+ )def _on_text_chunk(delta: str) -> None:thinking_chunks.append(delta)- self._emit("text_delta", {"delta": delta, "iter": current_iter})+ if not buffer_text_output:+ self._emit("text_delta", {"delta": delta, "iter": current_iter})def _on_reasoning_chunk(delta: str) -> None:# Throttled: long reasoning streams produce hundreds of@@ -711,10 +726,13 @@ class AgentLoop:):returnlast_reasoning_emit = now- self._emit(- "reasoning_delta",- {"iter": current_iter, "chars": reasoning_chars, "tail": reasoning_tail},- )+ reasoning_event = {+ "iter": current_iter,+ "chars": reasoning_chars,+ }+ if not buffer_text_output:+ reasoning_event["tail"] = reasoning_tail+ self._emit("reasoning_delta", reasoning_event)# On last iteration, drop tool definitions to force text outputis_last_iteration = (iteration == self.max_iterations)@@ -818,7 +836,11 @@ class AgentLoop:value=thinking_text,offload_kind=f"thinking-{current_iter}",)- self._emit("thinking_done", {"iter": current_iter, "content": thinking_text[:500]})+ if not buffer_text_output:+ self._emit(+ "thinking_done",+ {"iter": current_iter, "content": thinking_text[:500]},+ )# Content-filter skip: provider blocked the response — continue# to the next iteration instead of finalising on empty/garbage@@ -859,6 +881,50 @@ class AgentLoop:})break+ if self._grounding is not None:+ validation = self._grounding.validate_final_answer(final_content)+ if not validation.valid:+ trace.write_text_entry(+ {+ "type": "answer_rejected",+ "iter": current_iter,+ "issues": validation.issues,+ },+ field="content",+ value=final_content,+ offload_kind=f"answer-rejected-{current_iter}",+ )+ react_trace.append(+ {+ "type": "answer_rejected",+ "issues": validation.issues,+ }+ )+ messages.append(+ {"role": "assistant", "content": final_content}+ )+ messages.append(+ {+ "role": "system",+ "content": self._grounding.correction_prompt(validation),+ }+ )+ final_content = ""+ if (+ iteration < self.max_iterations+ and self._grounding.validation_count < 3+ ):+ continue+ final_content = self._grounding.safe_fallback()+ self._emit(+ "text_delta",+ {"delta": final_content, "iter": current_iter},+ )+ elif buffer_text_output:+ self._emit(+ "text_delta",+ {"delta": final_content, "iter": current_iter},+ )should_continue_goal = Falsecontinuation_snapshot = None_max_cont = _goal_max_continuations()@@ -1078,7 +1144,17 @@ class AgentLoop:"""compact_requested = Falsefocus_topic = ""- to_execute = []+ execution_plan: list[tuple[Any, str | None]] = []+ batch_authorized_symbols = (+ set(self._grounding.authorized_symbols)+ if self._grounding is not None+ else set()+ )+ batch_identity_status = (+ self._grounding.identity_status+ if self._grounding is not None+ else "not_required"+ )# Cancelled before this turn's tools ran — skip execution entirely.if self._cancel_event.is_set():@@ -1103,19 +1179,133 @@ class AgentLoop:react_trace.append({"type": "tool_skipped", "tool": tc.name})continue- to_execute.append(tc)+ if self._grounding is not None:+ authorization = self._grounding.authorize_tool_call(+ tc.name,+ tc.arguments,+ batch_authorized_symbols=batch_authorized_symbols,+ call_id=tc.id,+ batch_identity_status=batch_identity_status,+ )+ if not authorization.allowed:+ execution_plan.append(+ (+ tc,+ authorization.error_payload(+ tc.name,+ self._grounding.identity_summary(),+ ),+ )+ )+ continue++ execution_plan.append((tc, None))- if not to_execute:+ if not execution_plan:return compact_requested, focus_topic- # Batch execute: consecutive readonly → parallel, write → serial- if len(to_execute) == 1:- self._execute_single(to_execute[0], context, messages, trace, react_trace, iteration)- else:- self._batch_execute(to_execute, context, messages, trace, react_trace, iteration)+ # Preserve provider tool-result ordering. A synthetic blocked result+ # acts as a batch boundary, while adjacent authorized calls retain the+ # existing readonly-parallel/write-serial scheduler.+ authorized_segment: list[Any] = []++ def flush_authorized_segment() -> None:+ if not authorized_segment:+ return+ if len(authorized_segment) == 1:+ self._execute_single(+ authorized_segment[0],+ context,+ messages,+ trace,+ react_trace,+ iteration,+ )+ else:+ self._batch_execute(+ authorized_segment,+ context,+ messages,+ trace,+ react_trace,+ iteration,+ )+ authorized_segment.clear()++ for tc, blocked_result in execution_plan:+ if blocked_result is None:+ authorized_segment.append(tc)+ continue+ flush_authorized_segment()+ self._record_blocked_tool_call(+ tc,+ blocked_result,+ context,+ messages,+ trace,+ react_trace,+ iteration,+ )+ flush_authorized_segment()return compact_requested, focus_topic+ def _record_blocked_tool_call(+ self,+ tc: Any,+ result: str,+ context: ContextBuilder,+ messages: list,+ trace: TraceWriter,+ react_trace: list,+ iteration: int,+ ) -> None:+ """Record an identity-gated call without invoking its implementation.++ Args:+ tc: Provider tool-call object.+ result: Structured identity-gate error payload.+ context: Context builder.+ messages: Conversation messages.+ trace: Persistent trace writer.+ react_trace: Compact returned trace.+ iteration: Current iteration.+ """+ args = _normalize_tool_run_dir(tc.arguments, self.memory.run_dir)+ redacted_args = redact_payload(args)+ event_args = {key: str(value)[:200] for key, value in redacted_args.items()}+ self._emit(+ "tool_call",+ {+ "tool": tc.name,+ "arguments": event_args,+ "iter": iteration,+ "call_id": tc.id,+ "blocked": True,+ },+ )+ trace.write(+ {+ "type": "tool_call",+ "iter": iteration,+ "tool": tc.name,+ "call_id": tc.id,+ "args": redacted_args,+ "blocked": True,+ }+ )+ self._finalize_tool_result(+ tc,+ result,+ 0,+ context,+ messages,+ trace,+ react_trace,+ iteration,+ update_memory=False,+ )+def _batch_execute(self,tool_calls: list,@@ -1448,6 +1638,8 @@ class AgentLoop:trace: TraceWriter,react_trace: list,iteration: int,+ *,+ update_memory: bool = True,) -> None:"""Record a tool result: update memory, append message, write trace, emit event.@@ -1460,13 +1652,33 @@ class AgentLoop:trace: TraceWriter.react_trace: React trace list.iteration: Current iteration.+ update_memory: Whether this call reached the tool implementation."""- self._update_memory(tc.name)+ if update_memory:+ self._update_memory(tc.name)success = _is_tool_success(result)if success:self._called_ok.add(tc.name)+ if self._grounding is not None:+ self._grounding.ingest_tool_result(+ tool_name=tc.name,+ arguments=_normalize_tool_run_dir(tc.arguments, self.memory.run_dir),+ result=result,+ call_id=tc.id,+ success=success,+ )+ if tc.name == "search_symbol":+ trace.write(+ {+ "type": "identity_state",+ "iter": iteration,+ "call_id": tc.id,+ "identity": self._grounding.identity_summary(),+ }+ )+status = "ok" if success else "error"truncated = result[:TOOL_RESULT_LIMIT]messages.append(context.format_tool_result(tc.id, tc.name, truncated))diff --git a/agent/src/market_data.py b/agent/src/market_data.pyindex 1f753cf98..f3debc86e 100644--- a/agent/src/market_data.py+++ b/agent/src/market_data.py@@ -103,6 +103,7 @@ def fetch_market_data(loader_resolver: Callable[[str], type] = get_loader,fallback_chain_provider: Callable[[str], list[str]] | None = None,max_fallback_attempts: int = 3,+ include_provenance: bool = False,) -> dict[str, Any]:"""Fetch normalized OHLCV data through the repository loader layer.@@ -116,6 +117,7 @@ def fetch_market_data(from backtest.loaders.registry import FALLBACK_CHAINSresults: dict[str, Any] = {}+ provenance: dict[str, dict[str, Any]] = {}result_aliases = {code: code.split(":", 1)[1]if code.lower().startswith("local:")@@ -156,16 +158,13 @@ def fetch_market_data(data_map: dict[str, Any] = {}used_source: str | None = None- last_exc: Exception | None = Nonefor attempt_src in attempts:try:loader_cls = loader_resolver(attempt_src)except NoAvailableSourceError as exc:- last_exc = exclogger.debug("loader %r unavailable: %s", attempt_src, exc)continueexcept Exception as exc: # noqa: BLE001 — resolver may raise for non-network reasons- last_exc = exclogger.debug("loader %r resolver failed: %s", attempt_src, exc)continuetry:@@ -175,7 +174,6 @@ def fetch_market_data(if data_map:breakexcept Exception as exc: # noqa: BLE001 — contained per-symbol fallback- last_exc = exclogger.error("market-data loader %r failed for %s; trying next source in chain: %s",attempt_src, src_codes, exc,@@ -194,6 +192,14 @@ def fetch_market_data(for key, value in row.items():row[key] = _json_safe(value)results[symbol] = cap_rows(records, max_rows)+ if include_provenance:+ provenance[symbol] = {+ "source": used_source or src,+ "requested_source": source,+ "detected_source": src,+ "fallback_used": bool(used_source and used_source != src),+ "currency_conversion": "none",+ }unresolved = [code@@ -202,6 +208,8 @@ def fetch_market_data(]if unresolved:results["_unresolved"] = unresolved+ if include_provenance and provenance:+ results["_provenance"] = provenancereturn resultsdiff --git a/agent/src/tools/market_data_tool.py b/agent/src/tools/market_data_tool.pyindex 896deb0ef..3c24bdcc2 100644--- a/agent/src/tools/market_data_tool.py+++ b/agent/src/tools/market_data_tool.py@@ -95,4 +95,5 @@ class MarketDataTool(BaseTool):source=kwargs.get("source", "auto"),interval=kwargs.get("interval", "1D"),max_rows=kwargs.get("max_rows", DEFAULT_MAX_ROWS),+ include_provenance=True,)diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.pynew file mode 100644index 000000000..1542e6dbe--- /dev/null+++ b/agent/tests/test_agent_grounding.py@@ -0,0 +1,733 @@+"""Regression coverage for identity and numeric grounding (#887, #886)."""++from __future__ import annotations++import json+from pathlib import Path+from types import SimpleNamespace+from typing import Any, Callable++from src.agent.context import ContextBuilder+from src.agent.grounding import GroundingLedger+from src.agent.loop import AgentLoop, _is_tool_success+from src.agent.tools import BaseTool, ToolRegistry+from src.agent.trace import TraceWriter+++def _resolver_payload(+ symbol: str = "562500.SS",+ *,+ candidates: list[dict[str, Any]] | None = None,+ query: str = "机器人ETF",+) -> str:+ rows = candidates+ if rows is None:+ rows = [+ {+ "symbol": symbol,+ "name": "机器人ETF",+ "market": "cn",+ "type": "ETF",+ "source": "yahoo",+ "also_from": ["eastmoney"],+ }+ ]+ return json.dumps(+ {+ "ok": True,+ "source": "symbol_search",+ "data": {+ "query": query,+ "count": len(rows),+ "candidates": rows,+ "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,+ },+ {+ "trade_date": "2026-06-24",+ "open": 1.137,+ "high": 1.180,+ "low": 1.110,+ "close": 1.171,+ "volume": 234567,+ },+ ],+ "_provenance": {+ symbol: {+ "source": "yahoo",+ "requested_source": "auto",+ "detected_source": "yahoo",+ "fallback_used": False,+ "currency_conversion": "none",+ }+ },+ }+ )+++class _ResolverTool(BaseTool):+ name = "search_symbol"+ description = "Resolve a company or instrument name."+ parameters = {+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ }+ repeatable = True++ def __init__(self, result: str) -> None:+ self.result = result+ self.calls = 0++ def execute(self, **kwargs: Any) -> str:+ self.calls += 1+ return self.result+++class _MarketTool(BaseTool):+ name = "get_market_data"+ description = "Fetch OHLCV bars."+ parameters = {+ "type": "object",+ "properties": {"codes": {"type": "array", "items": {"type": "string"}}},+ "required": ["codes"],+ }+ repeatable = True++ def __init__(self, result: str) -> None:+ self.result = result+ self.calls = 0++ def execute(self, **kwargs: Any) -> str:+ self.calls += 1+ return self.result+++class _PrivateCompanySkillTool(BaseTool):+ name = "load_skill"+ description = "Load a skill."+ parameters = {+ "type": "object",+ "properties": {"name": {"type": "string"}},+ "required": ["name"],+ }+ repeatable = True++ def __init__(self) -> None:+ self.calls = 0++ def execute(self, **kwargs: Any) -> str:+ self.calls += 1+ return json.dumps({"status": "ok", "content": "private company workflow"})+++def _tool_call(call_id: str, tool_name: str, **arguments: Any) -> SimpleNamespace:+ return SimpleNamespace(id=call_id, name=tool_name, arguments=arguments)+++def _build_direct_agent(+ tmp_path: Path,+ resolver_result: str,+) -> tuple[AgentLoop, _ResolverTool, _MarketTool, _PrivateCompanySkillTool, TraceWriter]:+ resolver = _ResolverTool(resolver_result)+ market = _MarketTool(_market_payload())+ private_skill = _PrivateCompanySkillTool()+ registry = ToolRegistry()+ for tool in (resolver, market, private_skill):+ registry.register(tool)+ agent = AgentLoop(registry=registry, llm=SimpleNamespace(), max_iterations=5)+ run_dir = tmp_path / "run"+ run_dir.mkdir()+ agent.memory.run_dir = str(run_dir)+ agent._grounding = GroundingLedger(+ run_dir=run_dir,+ user_message="分析机器人ETF并给出买入价",+ )+ return agent, resolver, market, private_skill, TraceWriter(run_dir)+++def test_ok_false_tool_envelope_is_failure() -> None:+ """Business failures must not be recorded as successful tool calls (#886)."""+ assert _is_tool_success('{"ok": false, "error": "upstream failed"}') is False+ assert _is_tool_success('{"success": false, "message": "denied"}') is False+ assert _is_tool_success('{"status": "failed"}') is False+ assert _is_tool_success('{"ok": true, "data": {}}') is True+++def test_resolver_and_consumer_in_same_batch_cannot_race(+ tmp_path: Path,+) -> None:+ """A consumer sees the identity snapshot from before its whole LLM batch."""+ agent, resolver, market, _, trace = _build_direct_agent(+ tmp_path,+ _resolver_payload(),+ )+ messages: list[dict[str, Any]] = []+ react_trace: list[dict[str, Any]] = []++ agent._process_tool_calls(+ [+ _tool_call("resolve", "search_symbol", query="机器人ETF"),+ _tool_call(+ "prices-too-early",+ "get_market_data",+ codes=["562500.SH"],+ start_date="2026-06-23",+ end_date="2026-06-24",+ ),+ ],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 1,+ )++ assert resolver.calls == 1+ assert market.calls == 0+ assert agent._grounding.authorized_symbols == {"562500.SS"}+ blocked = [json.loads(message["content"]) for message in messages]+ assert any(item.get("error_code") == "identity_required" for item in blocked)++ agent._process_tool_calls(+ [+ _tool_call(+ "prices-after-lock",+ "get_market_data",+ codes=["562500.SS"],+ start_date="2026-06-23",+ end_date="2026-06-24",+ source="auto",+ )+ ],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 2,+ )+ trace.close()++ assert market.calls == 1+ artifact = json.loads(+ (tmp_path / "run" / "artifacts" / "grounding_evidence.json").read_text(+ encoding="utf-8"+ )+ )+ assert artifact["identity"]["status"] == "locked"+ assert any(+ record["field"] == "close"+ and record["value"] == 1.137+ and record["source"] == "yahoo"+ and record["currency"] == "CNY"+ and record["currency_conversion"] == "none"+ for record in artifact["evidence"]+ )+++def test_market_sensitive_skill_waits_for_prior_identity_batch(+ tmp_path: Path,+) -> None:+ """Workflow selection cannot race the resolver in the same assistant turn."""+ agent, resolver, _, skill, trace = _build_direct_agent(tmp_path, _resolver_payload())+ messages: list[dict[str, Any]] = []+ react_trace: list[dict[str, Any]] = []++ agent._process_tool_calls(+ [+ _tool_call("resolve", "search_symbol", query="机器人ETF"),+ _tool_call("workflow-too-early", "load_skill", name="valuation-model"),+ ],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 1,+ )++ assert resolver.calls == 1+ assert skill.calls == 0+ assert json.loads(messages[-1]["content"])["error_code"] == "identity_required"++ agent._process_tool_calls(+ [_tool_call("workflow-after-lock", "load_skill", name="valuation-model")],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 2,+ )+ trace.close()++ assert skill.calls == 1+++def test_bare_us_ticker_is_allowed_only_for_explicit_transport_contract(+ tmp_path: Path,+) -> None:+ """SEC's bare ticker consumes AAPL.US without permitting venue aliases."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="请分析 AAPL.US 的价格",+ )++ sec = ledger.authorize_tool_call(+ "get_sec_filings",+ {"ticker": "AAPL"},+ batch_authorized_symbols=ledger.authorized_symbols,+ call_id="sec",+ )+ market_alias = ledger.authorize_tool_call(+ "get_market_data",+ {"codes": ["AAPL"]},+ batch_authorized_symbols=ledger.authorized_symbols,+ call_id="prices",+ )++ assert sec.allowed is True+ assert market_alias.allowed is False+ assert market_alias.error_code == "identity_mismatch"+++def test_stale_history_identity_does_not_unlock_new_subject(tmp_path: Path) -> None:+ """A previous turn's AAPL identity cannot authorize a SpaceX price request."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="SpaceX 在什么价格买入比较合适?",+ history=[{"role": "user", "content": "请分析 AAPL.US"}],+ )++ authorization = ledger.authorize_tool_call(+ "get_market_data",+ {"codes": ["AAPL.US"]},+ batch_authorized_symbols=ledger.authorized_symbols,+ call_id="stale-price",+ )++ assert ledger.authorized_symbols == set()+ assert authorization.allowed is False+ assert authorization.error_code == "identity_required"+++def test_single_clean_not_found_source_is_not_enough_for_private_routing(+ tmp_path: Path,+) -> None:+ """A partial resolver outage cannot turn a public entity into private research."""+ resolver_result = json.dumps(+ {+ "ok": True,+ "source": "symbol_search",+ "data": {+ "query": "Acme",+ "count": 0,+ "candidates": [],+ "sources": {+ "eastmoney": "ok",+ "yahoo": "HTTP 429",+ },+ },+ }+ )+ agent, _, _, private_skill, trace = _build_direct_agent(tmp_path, resolver_result)+ messages: list[dict[str, Any]] = []+ react_trace: list[dict[str, Any]] = []++ agent._process_tool_calls(+ [_tool_call("resolve", "search_symbol", query="Acme")],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 1,+ )+ agent._process_tool_calls(+ [_tool_call("private", "load_skill", name="private-company-research")],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 2,+ )+ trace.close()++ assert agent._grounding.identity_status == "invalidated"+ assert private_skill.calls == 0+ assert json.loads(messages[-1]["content"])["error_code"] == "identity_required"+++def test_explicit_symbol_and_resolver_suffix_alias_become_conflicting(+ tmp_path: Path,+) -> None:+ """A later .SH resolver result cannot silently replace explicit .SS identity."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="请分析 562500.SS 并给出买入价",+ )+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "机器人ETF"},+ result=_resolver_payload("562500.SH"),+ call_id="resolver-alias",+ success=True,+ )++ authorization = ledger.authorize_tool_call(+ "get_market_data",+ {"codes": ["562500.SS"]},+ batch_authorized_symbols=ledger.authorized_symbols,+ batch_identity_status=ledger.identity_status,+ call_id="prices",+ )++ assert ledger.identity_status == "conflicting"+ assert authorization.allowed is False+ assert authorization.error_code == "identity_conflict"+++def test_locked_symbol_rejects_silent_exchange_suffix_rewrite(+ tmp_path: Path,+) -> None:+ """The consumer may not silently turn the resolver's .SS into .SH."""+ agent, _, market, _, trace = _build_direct_agent(tmp_path, _resolver_payload())+ messages: list[dict[str, Any]] = []+ react_trace: list[dict[str, Any]] = []++ agent._process_tool_calls(+ [_tool_call("resolve", "search_symbol", query="机器人ETF")],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 1,+ )+ agent._process_tool_calls(+ [_tool_call("wrong-suffix", "get_market_data", codes=["562500.SH"])],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 2,+ )+ trace.close()++ assert market.calls == 0+ assert json.loads(messages[-1]["content"])["error_code"] == "identity_mismatch"+++def test_listed_identity_blocks_private_company_workflow(+ tmp_path: Path,+) -> None:+ """Model memory cannot relabel a strongly resolved listing as private."""+ candidates = [+ {+ "symbol": "SPCX.US",+ "name": "SpaceX",+ "market": "us",+ "type": "equity",+ "exchange": "NMS",+ "source": "eastmoney",+ "also_from": ["yahoo"],+ "cik": "0001181412",+ }+ ]+ agent, _, _, private_skill, trace = _build_direct_agent(+ tmp_path,+ _resolver_payload("SPCX.US", candidates=candidates, query="SpaceX"),+ )+ messages: list[dict[str, Any]] = []+ react_trace: list[dict[str, Any]] = []++ agent._process_tool_calls(+ [_tool_call("resolve", "search_symbol", query="SpaceX")],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 1,+ )+ agent._process_tool_calls(+ [_tool_call("private", "load_skill", name="private-company-research")],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 2,+ )+ trace.close()++ assert private_skill.calls == 0+ assert json.loads(messages[-1]["content"])["error_code"] == "identity_conflict"+ validation = agent._grounding.validate_final_answer(+ "SpaceX is a private company and is not publicly traded."+ )+ assert validation.valid is False+ assert any(issue["code"] == "listed_identity_relabelled_private" for issue in validation.issues)+++def test_not_found_identity_allows_private_company_workflow(+ tmp_path: Path,+) -> None:+ """A clean multi-source not-found result keeps genuine private research usable."""+ agent, _, _, private_skill, trace = _build_direct_agent(+ tmp_path,+ _resolver_payload(candidates=[], query="Acme Private Labs"),+ )+ messages: list[dict[str, Any]] = []+ react_trace: list[dict[str, Any]] = []++ agent._process_tool_calls(+ [_tool_call("resolve", "search_symbol", query="Acme Private Labs")],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 1,+ )+ agent._process_tool_calls(+ [_tool_call("private", "load_skill", name="private-company-research")],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 2,+ )+ trace.close()++ assert private_skill.calls == 1+ assert agent._grounding.identity_status == "not_found"+++def test_ambiguous_resolution_keeps_consumers_blocked(tmp_path: Path) -> None:+ """Multiple weak candidates must become first-class ambiguous state."""+ candidates = [+ {"symbol": "ABC.US", "name": "ABC Holdings", "source": "yahoo"},+ {"symbol": "ABC.HK", "name": "ABC Group", "source": "eastmoney"},+ ]+ agent, _, market, _, trace = _build_direct_agent(+ tmp_path,+ _resolver_payload(candidates=candidates, query="ABC"),+ )+ messages: list[dict[str, Any]] = []+ react_trace: list[dict[str, Any]] = []++ agent._process_tool_calls(+ [_tool_call("resolve", "search_symbol", query="ABC")],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 1,+ )+ agent._process_tool_calls(+ [_tool_call("prices", "get_market_data", codes=["ABC.US"])],+ ContextBuilder,+ messages,+ trace,+ react_trace,+ 2,+ )+ trace.close()++ assert agent._grounding.identity_status == "ambiguous"+ assert market.calls == 0+ assert json.loads(messages[-1]["content"])["error_code"] == "identity_conflict"+++def test_final_numeric_gate_rejects_known_trace_contradiction(tmp_path: Path) -> None:+ """Known 1.11-1.18 evidence cannot become 0.88-0.91 in the answer."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="请分析 562500.SS 并给出买入价",+ )+ ledger.ingest_tool_result(+ tool_name="get_market_data",+ arguments={+ "codes": ["562500.SS"],+ "source": "auto",+ },+ result=_market_payload(),+ call_id="prices",+ success=True,+ )++ bad = ledger.validate_final_answer(+ """| 日期 | 开盘 | 最高 | 最低 | 收盘 |+|---|---:|---:|---:|---:|+| 2026-06-23 | 0.895 | 0.907 | 0.892 | 0.903 |++建议重仓买入价为 0.881。"""+ )+ good = ledger.validate_final_answer(+ "562500.SS(Yahoo,CNY)在 2026-06-23 的已观测开盘价为 1.141,收盘价为 1.137。"+ )++ assert bad.valid is False+ assert any(issue["code"] == "numeric_claim_conflict" for issue in bad.issues)+ assert good.valid is True+++def test_numeric_gate_validates_derived_formula_and_provenance(tmp_path: Path) -> None:+ """A derived entry level must calculate correctly from observed evidence."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="请分析 562500.SS 并给出买入价",+ )+ ledger.ingest_tool_result(+ tool_name="get_market_data",+ arguments={"codes": ["562500.SS"], "source": "auto"},+ result=_market_payload(),+ call_id="prices",+ success=True,+ )++ bad_math = ledger.validate_final_answer(+ "562500.SS(Yahoo,CNY)的推导买入价:(1.141 + 1.137) / 2 = 0.881。"+ )+ no_observed_input = ledger.validate_final_answer(+ "562500.SS(Yahoo,CNY)的推导买入价:(0.88 + 0.90) / 2 = 0.89。"+ )+ good = ledger.validate_final_answer(+ "562500.SS(Yahoo,CNY)的推导买入价:(1.141 + 1.137) / 2 = 1.139。"+ )+ missing_provenance = ledger.validate_final_answer(+ "2026-06-23 的已观测收盘价为 1.137。"+ )++ assert bad_math.valid is False+ assert no_observed_input.valid is False+ assert good.valid is True+ assert missing_provenance.valid is False+ assert {+ issue["code"] for issue in missing_provenance.issues+ } >= {+ "canonical_symbol_not_surfaced",+ "data_source_not_surfaced",+ "currency_not_surfaced",+ }+++class _Response:+ def __init__(+ self,+ *,+ content: str = "",+ tool_calls: list[SimpleNamespace] | None = None,+ ) -> None:+ self.content = content+ self.tool_calls = tool_calls or []+ self.reasoning_content = None+ self.has_tool_calls = bool(self.tool_calls)+++class _CorrectingLLM:+ model_name = "grounding-test"++ def __init__(self) -> None:+ self.responses = [+ _Response(+ tool_calls=[+ _tool_call("resolve", "search_symbol", query="机器人ETF"),+ _tool_call(+ "too-early",+ "get_market_data",+ codes=["562500.SH"],+ start_date="2026-06-23",+ end_date="2026-06-24",+ ),+ ]+ ),+ _Response(+ tool_calls=[+ _tool_call(+ "prices",+ "get_market_data",+ codes=["562500.SS"],+ start_date="2026-06-23",+ end_date="2026-06-24",+ source="auto",+ )+ ]+ ),+ _Response(content="建议买入价为 0.881。"),+ _Response(+ content=(+ "562500.SS(Yahoo,CNY)在 2026-06-23 的已观测收盘价为 1.137。"+ )+ ),+ ]++ 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,+ ) -> _Response:+ response = self.responses.pop(0)+ if response.content and on_text_chunk:+ on_text_chunk(response.content)+ return response++ def chat(self, messages: list[dict[str, Any]], **kwargs: Any) -> _Response:+ return _Response()+++def test_agent_loop_rejects_then_corrects_ungrounded_final_answer(+ tmp_path: Path,+) -> None:+ """Rejected numeric drafts never become the returned or streamed answer."""+ resolver = _ResolverTool(_resolver_payload())+ market = _MarketTool(_market_payload())+ registry = ToolRegistry()+ registry.register(resolver)+ registry.register(market)+ events: list[tuple[str, dict[str, Any]]] = []+ agent = AgentLoop(+ registry=registry,+ llm=_CorrectingLLM(),+ 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)++ result = agent.run("请分析机器人ETF并给出买入价")++ assert result["status"] == "success"+ assert "1.137" in result["content"]+ assert "0.881" not in result["content"]+ assert market.calls == 1+ streamed = "".join(+ data.get("delta", "") for event, data in events if event == "text_delta"+ )+ assert "0.881" not in streamed+ assert "1.137" in streamed+ completed_thinking = "".join(+ data.get("content", "")+ for event, data in events+ if event == "thinking_done"+ )+ assert "0.881" not in completed_thinking+ artifact = json.loads(+ (run_dir / "artifacts" / "grounding_evidence.json").read_text(encoding="utf-8")+ )+ assert artifact["validations"][0]["valid"] is False+ assert artifact["validations"][-1]["valid"] is Truediff --git a/agent/tests/test_market_data_tool.py b/agent/tests/test_market_data_tool.pyindex 8719200b1..afe0ad032 100644--- a/agent/tests/test_market_data_tool.py+++ b/agent/tests/test_market_data_tool.py@@ -51,6 +51,51 @@ def test_market_data_json_accepts_explicit_longbridge_source():assert seen == [(["AAPL.US"], "2026-01-01", "2026-01-02", "1D")]+def test_market_data_json_can_include_actual_source_provenance():+ """Agent-facing payloads expose fallback/source and conversion status (#886)."""+ idx = pd.date_range("2026-01-01", periods=1, freq="D")+ idx.name = "trade_date"+ df = pd.DataFrame(+ {+ "open": [1.0],+ "high": [1.1],+ "low": [0.9],+ "close": [1.05],+ "volume": [100],+ },+ index=idx,+ )++ class _FallbackLoader:+ def fetch(self, codes, start, end, interval="1D"):+ return {codes[0]: df}++ def _resolver(source: str):+ if source == "yahoo":+ raise RuntimeError("primary unavailable")+ return _FallbackLoader++ payload = json.loads(+ fetch_market_data_json(+ codes=["AAPL.US"],+ start_date="2026-01-01",+ end_date="2026-01-02",+ source="yahoo",+ loader_resolver=_resolver,+ fallback_chain_provider=lambda source: ["yahoo", "yfinance"],+ include_provenance=True,+ )+ )++ assert payload["_provenance"]["AAPL.US"] == {+ "source": "yfinance",+ "requested_source": "yahoo",+ "detected_source": "yahoo",+ "fallback_used": True,+ "currency_conversion": "none",+ }++def test_market_data_json_is_strict_when_loader_returns_nan():idx = pd.date_range("2026-01-01", periods=1, freq="D")diff --git a/agent/tests/test_mcp_client_adapter.py b/agent/tests/test_mcp_client_adapter.pyindex af10f4367..c745d23e8 100644--- a/agent/tests/test_mcp_client_adapter.py+++ b/agent/tests/test_mcp_client_adapter.py@@ -4,6 +4,8 @@ from __future__ import annotationsimport jsonimport logging+from dataclasses import dataclass+from datetime import date, datetime, timezonefrom typing import Anyimport pytest@@ -277,6 +279,85 @@ def test_remote_tool_execute_forwards_arguments_for_composed_schema() -> None:assert state["call_records"][0]["arguments"] == {"symbol": "AAPL"}+@dataclass+class _RobinhoodPosition:+ """FastMCP-style generated dataclass nested in a Robinhood response."""++ symbol: str+ quantity: float+ opened_on: date+ updated_at: datetime+++@dataclass+class _RobinhoodPortfolio:+ """Representative account/positions payload from Robinhood Agentic MCP."""++ account_number: str+ buying_power: float+ positions: list[_RobinhoodPosition]+ market_dates: dict[str, date]+++def test_robinhood_dataclass_dates_are_json_safe_end_to_end() -> None:+ """Generated dataclasses must not raise the false circular-reference error (#922)."""+ portfolio = _RobinhoodPortfolio(+ account_number="RH-123",+ buying_power=2500.75,+ positions=[+ _RobinhoodPosition(+ symbol="AAPL",+ quantity=3.5,+ opened_on=date(2026, 7, 31),+ updated_at=datetime(2026, 8, 1, 7, 30, tzinfo=timezone.utc),+ )+ ],+ market_dates={"next_open": date(2026, 8, 3)},+ )+ state = {+ "list_calls": 0,+ "call_calls": 0,+ "call_records": [],+ "list_outcomes": [[+ mcp_types.Tool(+ name="get_portfolio",+ description="Read the Robinhood portfolio",+ inputSchema={"type": "object", "properties": {}},+ )+ ]],+ "call_outcomes": [+ CallToolResult(+ content=[],+ structured_content=None,+ meta=None,+ data=portfolio,+ )+ ],+ }++ tool = build_mcp_tool_wrappers(+ "robinhood",+ _make_config(enabled_tools=["get_portfolio"]),+ client_factory=_make_factory(state),+ )[0]+ payload = json.loads(tool.execute())++ assert payload["status"] == "ok"+ assert payload["data"] == {+ "account_number": "RH-123",+ "buying_power": 2500.75,+ "positions": [+ {+ "symbol": "AAPL",+ "quantity": 3.5,+ "opened_on": "2026-07-31",+ "updated_at": "2026-08-01T07:30:00+00:00",+ }+ ],+ "market_dates": {"next_open": "2026-08-03"},+ }++def test_build_mcp_tool_wrappers_disambiguates_colliding_local_names() -> None:state = {"list_calls": 0,diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex 244237073..7eb532da9 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -1,12 +1,12 @@{"name": "vibe-trading-frontend",- "version": "0.1.12",+ "version": "0.1.13","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "vibe-trading-frontend",- "version": "0.1.12",+ "version": "0.1.13","dependencies": {"@fontsource/inter": "^5.3.0","@fontsource/jetbrains-mono": "^5.3.0",diff --git a/frontend/package.json b/frontend/package.jsonindex 438679dc3..bda0a862a 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -1,7 +1,7 @@{"name": "vibe-trading-frontend","private": true,- "version": "0.1.12",+ "version": "0.1.13","type": "module","engines": {"node": ">=22.22.0"diff --git a/frontend/src/components/layout/__tests__/Layout.test.tsx b/frontend/src/components/layout/__tests__/Layout.test.tsxindex e48d6fbed..52b87c60d 100644--- a/frontend/src/components/layout/__tests__/Layout.test.tsx+++ b/frontend/src/components/layout/__tests__/Layout.test.tsx@@ -12,7 +12,7 @@ const sessions = [vi.mock("react-i18next", () => ({useTranslation: () => ({t: (key: string) => ({- "app.version": "v0.1.12",+ "app.version": "v0.1.13","layout.agent": "Agent","layout.alphaZoo": "Alpha Zoo","layout.cancel": "Cancel",diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 61a8cc9e8..ee3d6b7f8 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -1,6 +1,6 @@{"app": {- "version": "v0.1.12"+ "version": "v0.1.13"},"layout": {"home": "الرئيسية",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 611fb312b..4b2a8e475 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -1,6 +1,6 @@{"app": {- "version": "v0.1.12"+ "version": "v0.1.13"},"charts": {"noPriceData": "No price data for this symbol yet",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex 7c45f316b..85838bb19 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -1,6 +1,6 @@{"app": {- "version": "v0.1.12"+ "version": "v0.1.13"},"layout": {"home": "ホーム",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex fc0c3fa48..ee3ca85b3 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -1,6 +1,6 @@{"app": {- "version": "v0.1.12"+ "version": "v0.1.13"},"layout": {"home": "홈",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex 0c47abc72..4b406f616 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -1,6 +1,6 @@{"app": {- "version": "v0.1.12"+ "version": "v0.1.13"},"layout": {"home": "首页",diff --git a/pyproject.toml b/pyproject.tomlindex 0e12bcabc..355cc7882 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,6 +1,6 @@[project]name = "vibe-trading-ai"-version = "0.1.12"+version = "0.1.13"description = "Natural-language finance research AI agent with backtesting"# Upper bound is real, not cautionary: smartmoneyconcepts -> numba -> llvmlite,# and llvmlite ships no 3.14 wheel, so pip falls back to a source build that