"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(agent): preserve explicit market context in grounding
AirHua-byte7f78745047ce
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.pyindex d207ab8ad..ed6b8e7ef 100644--- a/agent/src/agent/grounding.py+++ b/agent/src/agent/grounding.py@@ -31,6 +31,12 @@ from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Iterable, Mapping, Sequence+from src.agent.resolution_context import (+ IdentityConstraint,+ ResolutionContext,+ candidate_market,+)+GROUNDING_ARTIFACT = "grounding_evidence.json"@@ -863,6 +869,7 @@ class IdentityRecord:source_tool_call_id: str | None = Nonesource: list[str] = field(default_factory=list)candidates: list[dict[str, Any]] = field(default_factory=list)+ resolution_constraints: list[dict[str, Any]] = field(default_factory=list)version: int = 1updated_at: str = field(default_factory=_utc_now)@@ -932,6 +939,7 @@ class GroundingLedger:run_dir: Path,user_message: str,history: Sequence[Mapping[str, Any]] | None = None,+ contextual_identity_constraints: bool = True,) -> None:"""Create a ledger and seed only authoritative prior identities.@@ -939,12 +947,19 @@ class GroundingLedger: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.+ the model. Only explicit constraints whose clause names the+ current resolver subject may carry forward; stale global+ instructions cannot authorize a new subject.+ contextual_identity_constraints: Whether explicit market words in+ the original conversation may narrow resolver candidates."""self.run_dir = Path(run_dir)self.user_message = user_message+ self.resolution_context = ResolutionContext.from_messages(+ user_message,+ history,+ enabled=contextual_identity_constraints,+ )self._identities: dict[str, IdentityRecord] = {}self._evidence: list[EvidenceRecord] = []self._tool_failures: list[dict[str, Any]] = []@@ -1574,6 +1589,9 @@ class GroundingLedger:raw_candidates = data.get("candidates")candidates = [dict(item) for item in raw_candidates if isinstance(item, dict)] if isinstance(raw_candidates, list) else []+ resolver_candidates = candidates+ relevant_constraints = self.resolution_context.constraints_for(query)+ constraint_audit = [item.audit_record() for item in relevant_constraints]sources = data.get("sources") if isinstance(data.get("sources"), dict) else {}if not candidates:# "This entity does not exist" may only be concluded when every@@ -1599,17 +1617,46 @@ class GroundingLedger:source_tool_call_id=call_id,source=clean_sources,candidates=[],+ resolution_constraints=constraint_audit,version=version,)return+ market_values = {+ item.value+ for item in relevant_constraints+ if item.dimension == "market" and item.explicit+ }+ if market_values:+ constrained = [+ candidate+ for candidate in candidates+ if candidate_market(candidate) in market_values+ ]+ if constrained:+ candidates = constrained+ else:+ # A mismatch with an explicit constraint must stay fail closed.+ # The candidate list may be truncated, so this is ambiguity,+ # not proof that the requested listing does not exist.+ self._identities[key] = IdentityRecord(+ query=query,+ status="ambiguous",+ source_tool_call_id=call_id,+ candidates=resolver_candidates,+ resolution_constraints=constraint_audit,+ 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,+ candidates=resolver_candidates,+ resolution_constraints=constraint_audit,version=version,)return@@ -1620,7 +1667,8 @@ class GroundingLedger:query=query,status="invalidated",source_tool_call_id=call_id,- candidates=candidates,+ candidates=resolver_candidates,+ resolution_constraints=constraint_audit,version=version,)return@@ -1640,6 +1688,7 @@ class GroundingLedger:status="conflicting",source_tool_call_id=call_id,candidates=conflicting,+ resolution_constraints=constraint_audit,version=version,)return@@ -1652,6 +1701,7 @@ class GroundingLedger:status="conflicting",source_tool_call_id=call_id,candidates=conflicting,+ resolution_constraints=constraint_audit,version=version,)return@@ -1671,7 +1721,8 @@ class GroundingLedger:currency=_infer_currency(symbol),source_tool_call_id=call_id,source=source_names,- candidates=candidates,+ candidates=resolver_candidates,+ resolution_constraints=constraint_audit,version=version,)self._supersede_shortlists(symbol)@@ -2643,7 +2694,9 @@ class GroundingLedger:__all__ = ["GROUNDING_ARTIFACT","GroundingLedger",+ "IdentityConstraint","IdentityRecord",+ "ResolutionContext","ToolAuthorization","ValidationResult",]diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 923c108cb..4270ef57c 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -25,7 +25,7 @@ import threadingimport time as _timefrom datetime import datetime, timezonefrom pathlib import Path-from typing import Any, Callable, Dict, List, Optional+from typing import Any, Callable, Dict, List, Mapping, Optionalfrom src.agent.context import ContextBuilderfrom src.agent.grounding import GroundingLedger@@ -1066,6 +1066,9 @@ class AgentLoop:run_dir=run_dir,user_message=user_message,history=history,+ contextual_identity_constraints=(+ get_env_config().agent_tuning.vibe_contextual_identity_constraints+ ),)context = ContextBuilder(self.registry, self.memory,diff --git a/agent/src/agent/resolution_context.py b/agent/src/agent/resolution_context.pynew file mode 100644index 000000000..b8b0c2fa4--- /dev/null+++ b/agent/src/agent/resolution_context.py@@ -0,0 +1,259 @@+"""Explicit identity constraints carried beside the original conversation.++This module deliberately performs no query rewrite. It keeps the exact current+user message in memory and extracts only literal market words with source spans+that the grounding state machine can audit.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from typing import Any, Mapping, Sequence++_CLAUSE_BOUNDARY_RE = re.compile(r"[,,;;。.!!??\n]")+_MARKET_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (+ (+ "cn",+ re.compile(+ r"A\s*股|沪深(?:市场)?|上交所|深交所|上海证券交易所|深圳证券交易所|"+ r"\bA[- ]?shares?\b|\bmainland China (?:stock|listing|market)s?\b",+ re.IGNORECASE,+ ),+ ),+ (+ "hk",+ re.compile(+ r"港股|港交所|香港(?:市场|上市)|\bHK[- ]?(?:listed|stocks?|shares?)\b|"+ r"\bHong Kong (?:stock|listing|market)s?\b",+ re.IGNORECASE,+ ),+ ),+ (+ "us",+ re.compile(+ r"美股|纳斯达克|纽交所|美国(?:市场|上市)|"+ r"\bU\.?S\.?[- ]?(?:listed|stocks?|shares?|market)\b|\bNASDAQ\b|\bNYSE\b",+ re.IGNORECASE,+ ),+ ),+)+_CROSS_LISTING_RE = re.compile(+ r"(?:A\s*股?\s*[//和与、]\s*H\s*股?|H\s*股?\s*[//和与、]\s*A\s*股?|A\s*H\s*股)",+ re.IGNORECASE,+)+_NEGATED_RE = re.compile(+ r"(?:不要|不看|不分析|排除|剔除|非).{0,12}$",+ re.IGNORECASE,+)+_HISTORY_RESET_RE = re.compile(+ r"忽略之前|不用之前|取消.{0,8}(?:限制|市场)|不限制市场|重新选择市场",+ re.IGNORECASE,+)+_SUBJECT_NOISE_RE = re.compile(+ r"我的|我们|请|想要|需要|持仓|标的|公司|股票|证券|市场|"+ r"包括|都是|均为|全部|这些|上述|以下|只看|都看|看|"+ r"分析|比较|两地|上市|表现|以及|和|与|及|的",+ re.IGNORECASE,+)+++@dataclass(frozen=True)+class IdentityConstraint:+ """One explicit identity restriction found without rewriting the request."""++ subject_text: str | None+ dimension: str+ value: str+ source_message_id: str+ source_span: tuple[int, int]+ explicit: bool = True++ def audit_record(self) -> dict[str, Any]:+ """Return a trace-safe record without copying conversation text."""+ return {+ "dimension": self.dimension,+ "value": self.value,+ "source_message_id": self.source_message_id,+ "source_span": list(self.source_span),+ "explicit": self.explicit,+ }+++@dataclass(frozen=True)+class ResolutionContext:+ """Immutable original request plus narrow, auditable identity constraints."""++ raw_user_message: str+ constraints: tuple[IdentityConstraint, ...] = ()++ @classmethod+ def from_messages(+ cls,+ raw_user_message: str,+ history: Sequence[Mapping[str, Any]] | None = None,+ *,+ enabled: bool = True,+ ) -> ResolutionContext:+ """Build context from user-authored text while preserving that text verbatim."""+ if not enabled:+ return cls(raw_user_message=raw_user_message)+ extracted: list[IdentityConstraint] = []+ retained_history = (+ () if _HISTORY_RESET_RE.search(raw_user_message) else history or ()+ )+ for index, message in enumerate(retained_history):+ if str(message.get("role") or "").casefold() != "user":+ continue+ content = message.get("content")+ if isinstance(content, str):+ extracted.extend(+ _extract_market_constraints(content, f"history:user:{index}")+ )+ extracted.extend(+ _extract_market_constraints(raw_user_message, "current_user_message")+ )+ return cls(raw_user_message=raw_user_message, constraints=tuple(extracted))++ def constraints_for(self, query: str) -> tuple[IdentityConstraint, ...]:+ """Return only constraints that can be tied to this resolver query."""+ normalized_query = _comparable_text(query)+ ranked: list[tuple[tuple[int, int], IdentityConstraint]] = []+ for constraint in self.constraints:+ if constraint.subject_text is not None:+ subject = _comparable_text(constraint.subject_text)+ if normalized_query and normalized_query in subject:+ ranked.append(((_source_rank(constraint), 1), constraint))+ continue+ # A subject-free constraint is safe only in the current turn. Old+ # global instructions must not silently authorize a new subject.+ if constraint.source_message_id == "current_user_message":+ ranked.append(((_source_rank(constraint), 0), constraint))+ best_by_dimension: dict[str, tuple[int, int]] = {}+ for score, constraint in ranked:+ best_by_dimension[constraint.dimension] = max(+ score,+ best_by_dimension.get(constraint.dimension, score),+ )+ return tuple(+ constraint+ for score, constraint in ranked+ if score == best_by_dimension[constraint.dimension]+ )+++def candidate_market(candidate: Mapping[str, Any]) -> str | None:+ """Normalize a resolver candidate's market without provider coupling."""+ symbol = str(candidate.get("symbol") or "").strip().upper()+ if symbol.endswith(".SS"):+ symbol = f"{symbol[:-3]}.SH"+ suffix = symbol.rsplit(".", 1)[-1] if "." in symbol else ""+ if suffix in {"SH", "SZ", "BJ"}:+ return "cn"+ if suffix == "HK":+ return "hk"+ if suffix == "US":+ return "us"+ raw = (+ str(candidate.get("market") or candidate.get("exchange") or "")+ .strip()+ .casefold()+ )+ return {+ "cn": "cn",+ "china": "cn",+ "a": "cn",+ "a-share": "cn",+ "hk": "hk",+ "hong kong": "hk",+ "us": "us",+ "usa": "us",+ }.get(raw)+++def _comparable_text(value: Any) -> str:+ return re.sub(r"[^a-z0-9\u3400-\u9fff]", "", str(value or "").casefold())+++def _source_rank(constraint: IdentityConstraint) -> int:+ if constraint.source_message_id == "current_user_message":+ return 1_000_000_000+ try:+ return int(constraint.source_message_id.rsplit(":", 1)[-1])+ except ValueError:+ return -1+++def _constraint_clause(text: str, start: int, end: int) -> str:+ left = 0+ right = len(text)+ for match in _CLAUSE_BOUNDARY_RE.finditer(text):+ if match.end() <= start:+ left = match.end()+ elif match.start() >= end:+ right = match.start()+ break+ return text[left:right].strip()+++def _constraint_is_negated(text: str, start: int) -> bool:+ clause_start = 0+ for match in _CLAUSE_BOUNDARY_RE.finditer(text[:start]):+ clause_start = match.end()+ return bool(_NEGATED_RE.search(text[clause_start:start]))+++def _constraint_subject(clause: str) -> str | None:+ """Keep a named clause; collapse a pure follow-up like ``都只看 A 股``."""+ remainder = _CROSS_LISTING_RE.sub("", clause)+ for _, pattern in _MARKET_PATTERNS:+ remainder = pattern.sub("", remainder)+ remainder = _SUBJECT_NOISE_RE.sub("", remainder)+ return clause if len(_comparable_text(remainder)) >= 2 else None+++def _extract_market_constraints(+ text: str,+ source_message_id: str,+) -> list[IdentityConstraint]:+ constraints: list[IdentityConstraint] = []+ cross_spans: list[tuple[int, int]] = []+ for match in _CROSS_LISTING_RE.finditer(text or ""):+ if _constraint_is_negated(text, match.start()):+ continue+ cross_spans.append(match.span())+ clause = _constraint_clause(text, *match.span())+ subject = _constraint_subject(clause)+ constraints.extend(+ IdentityConstraint(+ subject_text=subject,+ dimension="market",+ value=value,+ source_message_id=source_message_id,+ source_span=match.span(),+ )+ for value in ("cn", "hk")+ )+ for value, pattern in _MARKET_PATTERNS:+ for match in pattern.finditer(text or ""):+ if _constraint_is_negated(text, match.start()):+ continue+ if any(+ start <= match.start() and match.end() <= end+ for start, end in cross_spans+ ):+ continue+ clause = _constraint_clause(text, *match.span())+ constraints.append(+ IdentityConstraint(+ subject_text=_constraint_subject(clause),+ dimension="market",+ value=value,+ source_message_id=source_message_id,+ source_span=match.span(),+ )+ )+ return constraints+++__all__ = ["IdentityConstraint", "ResolutionContext", "candidate_market"]diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.pyindex be4ae07f4..b97769ff6 100644--- a/agent/src/config/env_schema.py+++ b/agent/src/config/env_schema.py@@ -421,6 +421,9 @@ class AgentTuningConfig(_EnvBase):vibe_trading_enable_scheduler: EnvBool = Field(alias="VIBE_TRADING_ENABLE_SCHEDULER", default=False,)+ vibe_contextual_identity_constraints: EnvBool = Field(+ alias="VIBE_CONTEXTUAL_IDENTITY_CONSTRAINTS", default=True,+ )vibe_trading_scheduler_max_consecutive_failures: int = Field(alias="VIBE_TRADING_SCHEDULER_MAX_CONSECUTIVE_FAILURES", default=3,)diff --git a/agent/tests/test_env_schema.py b/agent/tests/test_env_schema.pyindex b7e60664f..70a3097dd 100644--- a/agent/tests/test_env_schema.py+++ b/agent/tests/test_env_schema.py@@ -169,6 +169,7 @@ class TestEnvConfigDefaults:assert c.agent_tuning.content_filter_warning_threshold == 0.05assert c.agent_tuning.vibe_trading_enable_advisory is Falseassert c.agent_tuning.vibe_trading_enable_scheduler is False+ assert c.agent_tuning.vibe_contextual_identity_constraints is Trueassert c.agent_tuning.vibe_trading_scheduler_max_consecutive_failures == 3assert c.agent_tuning.vibe_trading_scheduler_retry_base_delay_ms == 60_000assert c.agent_tuning.vibe_trading_scheduler_retry_max_delay_ms == 3_600_000@@ -242,6 +243,13 @@ class TestEnvConfigTypeCoercion:assert tuning.vibe_trading_scheduler_retry_base_delay_ms == 2500assert tuning.vibe_trading_scheduler_retry_max_delay_ms == 10000+ def test_contextual_identity_constraints_can_be_disabled(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setenv("VIBE_CONTEXTUAL_IDENTITY_CONSTRAINTS", "false")++ assert EnvConfig().agent_tuning.vibe_contextual_identity_constraints is False+# ===================================================================# TestEnvConfigOverridediff --git a/agent/tests/test_grounding_resolution_context.py b/agent/tests/test_grounding_resolution_context.pynew file mode 100644index 000000000..e1bd288ec--- /dev/null+++ b/agent/tests/test_grounding_resolution_context.py@@ -0,0 +1,308 @@+"""Context-aware identity resolution without rewriting the user request."""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++from src.agent.grounding import GroundingLedger+++def _resolver_payload(query: str, candidates: list[dict[str, Any]]) -> str:+ return json.dumps(+ {+ "ok": True,+ "source": "symbol_search",+ "data": {+ "query": query,+ "candidates": candidates,+ "sources": {"eastmoney": "ok", "yahoo": "ok"},+ },+ },+ ensure_ascii=False,+ )+++def _hengrui_candidates() -> list[dict[str, Any]]:+ return [+ {+ "symbol": "600276.SH",+ "name": "恒瑞医药",+ "market": "cn",+ "source": "eastmoney",+ },+ {+ "symbol": "01276.HK",+ "name": "恒瑞医药",+ "market": "hk",+ "source": "eastmoney",+ },+ ]+++def _ingest(+ ledger: GroundingLedger,+ query: str,+ candidates: list[dict[str, Any]],+ call_id: str = "resolve",+) -> None:+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": query},+ result=_resolver_payload(query, candidates),+ call_id=call_id,+ success=True,+ )+++def test_explicit_a_share_context_locks_the_a_share_candidate(tmp_path: Path) -> None:+ message = "请分析A股恒瑞医药的最新财务情况"+ ledger = GroundingLedger(run_dir=tmp_path, user_message=message)++ _ingest(ledger, "恒瑞医药", _hengrui_candidates())++ assert ledger.resolution_context.raw_user_message == message+ assert ledger.authorized_symbols == {"600276.SH"}+ record = ledger.identity_summary()["records"][0]+ assert record["status"] == "locked"+ assert record["resolution_constraints"] == [+ {+ "dimension": "market",+ "value": "cn",+ "source_message_id": "current_user_message",+ "source_span": [3, 5],+ "explicit": True,+ }+ ]+ assert message not in json.dumps(record, ensure_ascii=False)+ artifact = (tmp_path / "artifacts" / "grounding_evidence.json").read_text()+ assert message not in artifact+++def test_explicit_a_h_comparison_keeps_both_candidates(tmp_path: Path) -> None:+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="比较恒瑞医药 A/H 两地上市表现",+ )++ _ingest(ledger, "恒瑞医药", _hengrui_candidates())++ assert ledger.identity_status == "ambiguous"+ assert ledger.authorized_symbols == set()+ constraints = ledger.identity_summary()["records"][0]["resolution_constraints"]+ assert {item["value"] for item in constraints} == {"cn", "hk"}+++def test_no_explicit_market_remains_fail_closed(tmp_path: Path) -> None:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="分析恒瑞医药")++ _ingest(ledger, "恒瑞医药", _hengrui_candidates())++ assert ledger.identity_status == "ambiguous"+ assert ledger.authorized_symbols == set()+++def test_explicit_us_market_in_english_locks_the_us_candidate(tmp_path: Path) -> None:+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="Analyze the US stock ABC",+ )+ candidates = [+ {"symbol": "ABC.US", "name": "ABC", "market": "us", "source": "yahoo"},+ {+ "symbol": "00123.HK",+ "name": "ABC",+ "market": "hk",+ "source": "eastmoney",+ },+ ]++ _ingest(ledger, "ABC", candidates)++ assert ledger.authorized_symbols == {"ABC.US"}+++def test_negated_market_is_not_used_as_positive_authorization(tmp_path: Path) -> None:+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="不要看港股恒瑞医药",+ )++ _ingest(ledger, "恒瑞医药", _hengrui_candidates())++ assert ledger.identity_status == "ambiguous"+ assert ledger.authorized_symbols == set()+++def test_constraint_mismatch_stays_fail_closed(tmp_path: Path) -> None:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="只看A股恒瑞医药")++ _ingest(ledger, "恒瑞医药", [_hengrui_candidates()[1]])++ assert ledger.identity_status == "ambiguous"+ assert ledger.authorized_symbols == set()+++def test_one_ambiguous_entity_does_not_retract_another_lock(tmp_path: Path) -> None:+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="A股恒瑞医药;比较 ABC A/H",+ )+ abc_candidates = [+ {"symbol": "600123.SH", "name": "ABC", "market": "cn", "source": "eastmoney"},+ {"symbol": "00123.HK", "name": "ABC", "market": "hk", "source": "eastmoney"},+ ]++ _ingest(ledger, "恒瑞医药", _hengrui_candidates(), "hengrui")+ _ingest(ledger, "ABC", abc_candidates, "abc")++ assert ledger.authorized_symbols == {"600276.SH"}+ assert (+ ledger.authorize_tool_call(+ "get_market_data",+ {"codes": ["600276.SH"]},+ batch_authorized_symbols=ledger.authorized_symbols,+ batch_identity_status=ledger.identity_status,+ call_id="prices",+ ).allowed+ is True+ )+++def test_market_constraints_stay_attached_to_their_named_clause(tmp_path: Path) -> None:+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="我的持仓包括A股恒瑞医药,港股腾讯",+ )+ tencent_candidates = [+ {+ "symbol": "00700.HK",+ "name": "腾讯",+ "market": "hk",+ "source": "eastmoney",+ },+ {+ "symbol": "TCEHY.US",+ "name": "腾讯",+ "market": "us",+ "source": "yahoo",+ },+ ]++ _ingest(ledger, "恒瑞医药", _hengrui_candidates(), "hengrui")+ _ingest(ledger, "腾讯", tencent_candidates, "tencent")++ assert ledger.authorized_symbols == {"600276.SH", "00700.HK"}+++def test_current_follow_up_constraint_applies_to_prior_subjects(tmp_path: Path) -> None:+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="都只看 A 股",+ history=[+ {"role": "user", "content": "比较恒瑞医药和药明康德"},+ {"role": "assistant", "content": "你希望看哪个市场?"},+ ],+ )+ wuxi_candidates = [+ {+ "symbol": "603259.SH",+ "name": "药明康德",+ "market": "cn",+ "source": "eastmoney",+ },+ {+ "symbol": "02359.HK",+ "name": "药明康德",+ "market": "hk",+ "source": "eastmoney",+ },+ ]++ _ingest(ledger, "恒瑞医药", _hengrui_candidates(), "hengrui")+ _ingest(ledger, "药明康德", wuxi_candidates, "wuxi")++ assert ledger.authorized_symbols == {"600276.SH", "603259.SH"}+++def test_named_constraint_overrides_current_global_constraint(tmp_path: Path) -> None:+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="都只看A股,腾讯看港股",+ )+ candidates = [+ {"symbol": "00700.HK", "name": "腾讯", "market": "hk", "source": "eastmoney"},+ {"symbol": "TCEHY.US", "name": "腾讯", "market": "us", "source": "yahoo"},+ ]++ _ingest(ledger, "腾讯", candidates)++ assert ledger.authorized_symbols == {"00700.HK"}+++def test_stale_global_history_does_not_authorize_a_new_turn(tmp_path: Path) -> None:+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="分析恒瑞医药",+ history=[{"role": "user", "content": "都只看港股"}],+ )++ _ingest(ledger, "恒瑞医药", _hengrui_candidates())++ assert ledger.identity_status == "ambiguous"+ assert ledger.authorized_symbols == set()+++def test_named_history_constraint_can_follow_its_subject(tmp_path: Path) -> None:+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="继续分析",+ history=[{"role": "user", "content": "只看A股恒瑞医药"}],+ )++ _ingest(ledger, "恒瑞医药", _hengrui_candidates())++ assert ledger.authorized_symbols == {"600276.SH"}+++def test_latest_named_history_constraint_wins(tmp_path: Path) -> None:+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="继续分析恒瑞医药",+ history=[+ {"role": "user", "content": "只看港股恒瑞医药"},+ {"role": "assistant", "content": "好的"},+ {"role": "user", "content": "改为A股恒瑞医药"},+ ],+ )++ _ingest(ledger, "恒瑞医药", _hengrui_candidates())++ assert ledger.authorized_symbols == {"600276.SH"}+++def test_current_reset_discards_history_constraints(tmp_path: Path) -> None:+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="忽略之前的市场限制,分析恒瑞医药",+ history=[{"role": "user", "content": "只看港股恒瑞医药"}],+ )++ _ingest(ledger, "恒瑞医药", _hengrui_candidates())++ assert ledger.identity_status == "ambiguous"+ assert ledger.authorized_symbols == set()+++def test_feature_flag_can_restore_previous_resolution_behavior(tmp_path: Path) -> None:+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="只看A股恒瑞医药",+ contextual_identity_constraints=False,+ )++ _ingest(ledger, "恒瑞医药", _hengrui_candidates())++ assert ledger.identity_status == "ambiguous"+ assert ledger.authorized_symbols == set()