"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
refactor(grounding): model-declared figure roles replace the prose word catalogue
Haozhe Wu3f9faa24c5f9
diff --git a/agent/src/agent/grounding/__init__.py b/agent/src/agent/grounding/__init__.pyindex ca8922b88..4ba09e200 100644--- a/agent/src/agent/grounding/__init__.py+++ b/agent/src/agent/grounding/__init__.py@@ -11,9 +11,16 @@ facts are structural rather than advisory:Those are the mechanically decidable parts of the agent's output principles.The rest of that contract — "state the as-of", "analysis, not advice", "refuse-out loud" — stays in the system prompt on purpose: see-``policies._validate_price_claims`` and the package tests for why a regex gate-on them rejects correct answers.+out loud" — stays in the system prompt on purpose.++What a number IS — an observed print, a derived level, a proposal, a citation,+a count — is declared by the model in a ``figures`` block and verified against+evidence (:mod:`figures`, :mod:`policies`). It used to be inferred from the+prose around the number, against a catalogue of price words, level words,+indicator names, attribution verbs and forecast frames. A catalogue is only as+complete as the day it was typed: the same sentence got opposite verdicts in+its two translations, and each missing phrasing was either a rejected correct+answer or a released fabrication.The package deliberately contains no provider or tool-registry dependencies soits state machine and final-answer checks remain deterministic and testable.diff --git a/agent/src/agent/grounding/evidence.py b/agent/src/agent/grounding/evidence.pyindex 656b2a62e..ce4437138 100644--- a/agent/src/agent/grounding/evidence.py+++ b/agent/src/agent/grounding/evidence.py@@ -146,30 +146,24 @@ _ANALYSIS_KIND_ALIASES = {"return": "return","returns": "return","ic_positive_ratio": "win_rate",+ # A-share tools key their JSON in Chinese. These are TOOL FIELD NAMES, in+ # the same category as ``max_drawdown`` above: they name what a leaf of a+ # result IS. Nothing here reads the answer's prose.+ "最大回撤": "drawdown",+ "回撤": "drawdown",+ "夏普": "sharpe",+ "夏普比率": "sharpe",+ "年化波动率": "vol",+ "波动率": "vol",+ "胜率": "win_rate",+ "命中率": "win_rate",+ "概率": "probability",+ "年化收益率": "return",+ "累计收益率": "return",+ "收益率": "return",}-# Order matters: 最大回撤 is drawdown before 收益/return, and 年化波动率 is vol-# before the generic return branch.-_ANALYSIS_KIND_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (- (re.compile(r"(?:回撤|drawdown|maxdd|最大亏损)", re.IGNORECASE), "drawdown"),- (- re.compile(- r"(?:波动率|波动性|volatility|annualized\s*vol|return\s*vol|年化波动)",- re.IGNORECASE,- ),- "vol",- ),- (re.compile(r"(?:夏普|sharpe)", re.IGNORECASE), "sharpe"),- (re.compile(r"(?:胜率|命中率|win\s*rate|hit\s*rate)", re.IGNORECASE), "win_rate"),- (re.compile(r"(?:概率|probability|prob)", re.IGNORECASE), "probability"),- # 年化/annualized alone ("| 年化 | 18.2% |") resolves to return so a- # generic-header table cannot dodge the gate with the fragment the prose- # detector (_ANALYSIS_METRIC_RE) already treats as a metric word.- (re.compile(r"(?:收益|回报|收益率|回报率|年化|\breturns?\b|\bannualized\b)", re.IGNORECASE), "return"),-)--def _symbol_from_csv_filename(stem: str) -> str | None:"""Map a run-dir CSV stem back to a canonical project symbol.@@ -237,40 +231,16 @@ def _coerce_csv_number(value: Any) -> int | float | None:# "." is deliberately not a separator: a decimal price such as 8.5 would parse-# as month 8 day 5 and match a real trading day.-# A report writes the day as a table cell -- "08-10(一)", "08-10(周一)盘中",-# "08-10盘中" -- and the weekday or session suffix made the cell match no-# evidence row at all, so every price in that row came back-# "numeric_claim_unavailable" even though the run had fetched the bar.-_TRADING_DAY_SUFFIX = (- r"(?:\s*[((]\s*(?:周|星期)?[一二三四五六日天]\s*[))])?"- r"\s*(?:盘中|盘后|盘前|收盘|开盘|早盘|尾盘)?"-)---_YEARLESS_CLAIM_DATE_RE = re.compile(- r"^(0?[1-9]|1[0-2])\s*[-/月]\s*(0?[1-9]|[12]\d|3[01])\s*[日号]?"- + _TRADING_DAY_SUFFIX- + r"$"-)---# Two-digit day alternatives are tried before a bare digit so an-# unanchored prefix match consumes the full day ("10" of "08-10(一)")-# instead of stopping at "1".-_ISO_CLAIM_DATE_PREFIX_RE = re.compile(- r"^\s*((?:19|20)\d{2})\s*[-/]\s*(0?[1-9]|1[0-2])\s*[-/]\s*([12]\d|3[01]|0?[1-9])"+# A date CELL in a report carries annotations the bare ISO form does not:+# "08-10(一)", "08-10(周一)盘中", "2026-08-10". Only the leading date matters,+# so the year is optional and everything after the day is ignored — which is+# also how the weekday/session annotations stopped needing a vocabulary.+_CLAIM_DATE_RE = re.compile(+ r"^\s*(?:((?:19|20)\d{2})\s*[-/年]\s*)?"+ r"(0?[1-9]|1[0-2])\s*[-/月]\s*([12]\d|3[01]|0?[1-9])")-_YEARLESS_CLAIM_DATE_PREFIX_RE = re.compile(- r"^\s*(0?[1-9]|1[0-2])\s*[-/月]\s*([12]\d|3[01]|0?[1-9])"-)---_ISO_TIMESTAMP_RE = re.compile(r"^(\d{4})-(\d{1,2})-(\d{1,2})")--def _claim_date_tuple(date_value: str) -> tuple[int, int] | None:"""Extract the (month, day) named by a report-style date cell.@@ -287,17 +257,10 @@ def _claim_date_tuple(date_value: str) -> tuple[int, int] | None:Returns:The (month, day) tuple, or None when no date prefix is present."""- claim = (date_value or "").strip()- match = _YEARLESS_CLAIM_DATE_RE.match(claim)- if match:- return (int(match.group(1)), int(match.group(2)))- match = _ISO_CLAIM_DATE_PREFIX_RE.match(claim)- if match:- return (int(match.group(2)), int(match.group(3)))- match = _YEARLESS_CLAIM_DATE_PREFIX_RE.match(claim)- if match:- return (int(match.group(1)), int(match.group(2)))- return None+ match = _CLAIM_DATE_RE.match((date_value or "").strip())+ if match is None:+ return None+ return (int(match.group(2)), int(match.group(3)))def _timestamp_matches_claim_date(timestamp: str, date_value: str) -> bool:@@ -331,10 +294,14 @@ def _timestamp_matches_claim_date(timestamp: str, date_value: str) -> bool:if stamp.startswith(claim):return Trueclaim_tuple = _claim_date_tuple(claim)- iso = _ISO_TIMESTAMP_RE.match(stamp)- if claim_tuple is None or not iso:+ parts = stamp[:10].split("-")+ if claim_tuple is None or len(parts) != 3:+ return False+ try:+ stamp_tuple = (int(parts[1]), int(parts[2]))+ except ValueError:return False- return (int(iso.group(2)), int(iso.group(3))) == claim_tuple+ return stamp_tuple == claim_tupledef _price_field_for_path(path: str) -> str | None:@@ -352,98 +319,62 @@ def _price_field_for_path(path: str) -> str | None:return _GENERIC_PRICE_FIELD_ALIASES.get(leaf)-# A price-denominated indicator the session fetched is observed evidence in-# the same sense an OHLC bar is: ``indicators.sma_20: 0.7158`` came out of-# ``technical_indicators`` for this symbol, and an answer that writes "MA20-# 0.7158" or derives an entry from it is quoting a tool, not inventing a-# number. Before this, the value was compared against OHLC bars only and-# rejected as a fabricated price (deriv2 probe, 2026-09-09). The family list is-# closed and price-denominated on purpose — a moving average, band, pivot,-# support/resistance level, VWAP or ATR is in the instrument's currency; RSI,-# MACD, volume, counts and row totals are not. Letting a quote match-# ``rows: 54`` or a volume average would gut the fabrication check, so any-# non-price token anywhere in the path disqualifies the leaf.-_PRICE_INDICATOR_TOKENS = frozenset(- {- "sma", "ema", "wma", "dma", "dema", "tema", "hma", "kama", "ma", "vwap", "vwma",- "bb", "bbands", "boll", "bollinger", "band", "bands", "keltner", "kc", "donchian",- "pivot", "pp", "support", "resistance",- "atr", "psar", "sar", "supertrend", "ichimoku", "tenkan", "kijun", "senkou",- "chikou", "highest", "lowest",- }-)---# Generic band leaves. "lower" is a price only under a band family, so these-# need a family token elsewhere in the path: ``bollinger.lower`` qualifies,-# a bare ``summary.lower`` does not.-_PRICE_BAND_LEAVES = frozenset({"upper", "lower", "middle", "mid", "top", "bottom", "basis"})---# Standard pivot-level spellings. They are matched before the trailing digits-# are stripped: ``r1`` would otherwise become ``r``, which is in no set, and-# the six literals ``r1 r2 r3 s1 s2 s3`` sat in the family list unreachable.-_PIVOT_LEVEL_RE = re.compile(r"^[rs][123]$")---_NON_PRICE_TOKENS = frozenset(- {- "volume", "vol", "turnover", "amount", "count", "rows", "returned", "signal",- "histogram", "rsi", "kdj", "k", "d", "j", "cci", "adx", "obv", "mfi", "roc",- "williams", "wr", "stoch", "pct", "percent", "ratio", "change", "chg", "width",- "position", "score", "z", "zscore", "slope", "angle", "days", "bars",- # Parameters and derived shapes, not levels: ``params.ma_period: 20``- # and ``entry_condition.ma_window: 20`` are settings, ``ma_diff`` and- # ``sma_cross`` are differences and booleans. The leaf test below- # already rejects those three, but a path that also carries a family- # token in another segment must not be readmitted by it.- "window", "period", "length", "span", "lookback", "n", "cross", "flag",- }-)-+# Price-denominated indicator leaves, REGISTERED PER TOOL (spec §5). The+# previous rule guessed from path tokens: a leaf counted as a price when its+# name carried a family word ("sma", "band", "pivot") and no non-price word.+# Guessing from a name is the same failure as guessing from prose — the family+# list and the denylist both had to be complete, and they were not:+# ``indicators.ma_diff``, ``indicators.sma_cross`` and+# ``indicators.supertrend_direction`` were all admitted as observed prices,+# so a payload with any of them set to 1.30 let the answer print "现价 1.30 元".+#+# A tool's output shape is a fact about that tool, so it is stated here per+# tool and matched by path prefix. A leaf that is not registered is still+# recorded as evidence — it simply cannot ground a price. Adding a tool that+# returns price levels means adding a row here, which is the point: the+# registration is a decision someone made, not a coincidence of naming.+_REGISTERED_PRICE_INDICATORS: dict[str, tuple[str, ...]] = {+ "technical_indicators": (+ "latest_close",+ "indicators.sma_",+ "indicators.ema_",+ "indicators.bollinger.upper",+ "indicators.bollinger.middle",+ "indicators.bollinger.lower",+ ),+}-def _is_price_denominated_indicator(path: str) -> bool:- """Return whether a generic evidence path is a price-denominated indicator.- The decision is made on the LEAF — the last dotted segment, with a- trailing index stripped — not on "some token anywhere in the path". Under- the old any-token rule ``indicators.ma_diff``, ``indicators.sma_cross``- and ``indicators.supertrend_direction`` were all admitted as observed- prices because they carry ``ma`` / ``sma`` / ``supertrend`` somewhere,- and a payload with any of them set to 1.30 let the answer print- "现价 1.30 元" (attack6 probe, 2026-09-09). A difference, a crossover- flag and a direction are not prices.+def _is_registered_price_indicator(tool: str, path: str) -> bool:+ """Whether a tool registered this leaf as a price-denominated level.Args:+ tool: The tool whose result produced the evidence record.path: Recorded evidence field, e.g. ``"indicators.bollinger.lower"``.Returns:- True when the leaf names a price-denominated indicator level and no- path token names a non-price quantity.+ True when the tool has a registration whose prefix the path matches."""- text = str(path or "")- tokens = [- re.sub(r"\d+$", "", token).casefold()- for token in re.split(r"[._\[\]\-\s]+", text)- if token- ]- tokens = [token for token in tokens if token]- if not tokens:- return False- if any(token in _NON_PRICE_TOKENS for token in tokens):+ prefixes = _REGISTERED_PRICE_INDICATORS.get(str(tool or ""))+ if not prefixes:return False- segments = [segment for segment in re.split(r"[.\[\]]+", text) if segment]- if not segments:- return False- leaf = segments[-1].strip().casefold()- if _PIVOT_LEVEL_RE.match(leaf):- return True- leaf = re.sub(r"[_\-]?\d+$", "", leaf) or leaf- if leaf in _PRICE_INDICATOR_TOKENS:- return True- return leaf in _PRICE_BAND_LEAVES and any(- token in _PRICE_INDICATOR_TOKENS for token in tokens- )+ leaf = str(path or "").strip()+ for prefix in prefixes:+ if leaf == prefix:+ return True+ if not leaf.startswith(prefix):+ continue+ # A registration ending in "_" names a parametrised family+ # (``indicators.sma_20``), so what follows must be the parameter.+ # Without that, ``indicators.sma_cross`` — a boolean — matched+ # ``indicators.sma_`` and became a price, which is the exact defect+ # the name-reading rule kept producing.+ rest = leaf[len(prefix):]+ if not prefix.endswith("_"):+ return True+ if rest.isdigit():+ return True+ return Falsedef _metric_kind_for_path(path: str) -> str | None:@@ -464,14 +395,6 @@ def _metric_kind_for_path(path: str) -> str | None:kind = _ANALYSIS_KIND_ALIASES.get("_".join(tokens[start : start + size]))if kind is not None:return kind- return _metric_kind_for_text(path)---def _metric_kind_for_text(text: str) -> str | None:- """Return the analysis metric kind named in a claim or header."""- for pattern, kind in _ANALYSIS_KIND_PATTERNS:- if pattern.search(text):- return kindreturn None@@ -949,7 +872,7 @@ class _EvidenceMixin:continuefield_name = _price_field_for_path(record.field)if field_name is None:- if _is_price_denominated_indicator(record.field):+ if _is_registered_price_indicator(record.tool, record.field):records.append(replace(record, field="indicator"))continuerecords.append(replace(record, field=field_name))diff --git a/agent/src/agent/grounding/figures.py b/agent/src/agent/grounding/figures.pyindex 408852ca4..85c5e4232 100644--- a/agent/src/agent/grounding/figures.py+++ b/agent/src/agent/grounding/figures.py@@ -1,165 +1,210 @@-"""Shape primitives for locating numbers, dates and tables in answer text.--This module is deliberately language-agnostic: it answers "what shape is this-run of characters" and nothing about what the surrounding prose calls it.+"""The figures block, the shape of a number, and how the two are matched.++This module is the whole "inference" surface of the gate, and it is+deliberately tiny. It answers three questions and no others:++* where is the model's ``figures`` block, and what did it declare;+* what SHAPE is each run of digits in the prose — a date, a symbol, a list+ marker, a measurement, or a bare integer;+* which declaration, if any, covers a given prose number.++Nothing here reads a natural-language word. The predecessor of this module+decided a number's ROLE from a catalogue of price words, target/stop words,+ATH spellings, indicator names, order-book phrases and observation binders;+every one of those catalogues was only as complete as the day it was typed,+so the gate's verdict differed between two translations of one sentence and a+correct draft was rejected for a phrasing the list had not seen. The role is+now declared by the model and verified against evidence; shape is all that is+left to infer, and shape is language-independent."""from __future__ import annotationsimport re+from dataclasses import dataclass+from typing import Sequence-# "从 2026-08-03 的 100.0 涨到 2026-09-02 的 112.4" / "rose from 100.0 to-# 112.4": a return figure framed as growth between two endpoints is-# arithmetic on sourced inputs, not an invented backtest metric (#1338-# review). The frame alone never grounds anything — the values must also-# match an observed endpoint pair exactly (see _return_derived_from_observed).-_NUMBER_RE = re.compile(- r"(?<![A-Za-z0-9_])[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?"- r"(?![A-Za-z0-9_])"-)+from src.agent.grounding.identity import _CANONICAL_SYMBOL_RE+#: The five roles a declaration may carry (spec §2).+ROLES = ("observed", "derived", "proposed", "cited", "count")-# A line-leading ordered-list marker ("1. **标题**") is prose structure, not a-# number. Without masking it, "1." is parsed as a float and rejected downstream-# as a numeric_claim_conflict against an observed OHLC range (#BUGS-1). The-# pattern only matches a digit run at the start of a line followed by "." or ")"-# and whitespace, so an in-text decimal like "1.5" (digit after the dot) is-# never affected.-_MD_LIST_ITEM_RE = re.compile(r"^\s*\d+[.)]\s+", re.MULTILINE)---# re.ASCII keeps ``\b`` a *byte* word boundary. Without it, ``\w`` is-# Unicode-aware and CJK letters count as word characters, so a date that runs-# straight into Chinese text -- "(2026-07-14最低)" -- has no boundary after-# "14" and is left unmasked, contributing 2026/7/14 as candidate prices that-# reject a correct report (#1122).-_DATE_RE = re.compile(r"\b(?:19|20)\d{2}[-/]\d{1,2}[-/]\d{1,2}\b", re.ASCII)---# A year-less "8/5" is how a trading day is written in running prose, and it-# contributed 8 and 5 as candidate prices (#983). The month and day ranges are-# bounded, and both sides are fenced off from a longer slash run, so the window-# enumeration "20/50/200-day" cannot be mistaken for a date. Reports also write-# the same day as "08-10(一)" or "08-10盘中"; that dash form is masked by-# ``_DASH_DATE_RE`` below, where a zero-padded month or a weekday/session-# marker is required so a quoted price range like "8-10 元" stays checkable.-_SHORT_DATE_RE = re.compile(- r"(?<![\d/])(?:0?[1-9]|1[0-2])/(?:0?[1-9]|[12]\d|3[01])(?![\d/])"-)+#: The info string that marks the declaration block.+BLOCK_LANGUAGE = "figures"-# A report writes a trading day as "08-10(一)" or "08-10盘中", and the dash form-# leaked 8 and 10 as candidate prices exactly as "8/5" once did. The dash is-# NOT symmetric with the slash, though: it also separates a range, and "目标价-# 10-20 元" must stay checkable. So the two halves are split -- a zero-padded-# month (01-09) is a formatting intent no price range imitates, while 10/11/12-# have to carry a weekday or session marker to read as a date.-_DASH_DATE_RE = re.compile(- r"(?<![\d/-])(?:"- r"0[1-9]-(?:0[1-9]|[12]\d|3[01])"- r"|1[0-2]-(?:0[1-9]|[12]\d|3[01])"- r"(?=\s*(?:[((]\s*(?:周|星期)?[一二三四五六日天]\s*[))]"- r"|盘中|盘后|盘前|收盘|开盘|最低|最高"- r"|\s*(?:close|open|intraday|low|high)\b))"- r")(?![\d/-])",- re.IGNORECASE,+# SHAPE 1 — a number. Grouped thousands are one token, and the lookbehind+# keeps an identifier's digits ("SMA20", "MA5") from being read as a value.+#+# The lookahead deliberately fences only DIGITS, not letters. Fencing letters+# too truncated a figure glued to its unit: "3.6pp" failed the fence at "p",+# backtracked, and matched the bare "3" — so the same statement was a decimal+# in Chinese ("3.6 个百分点") and a bare integer in English, and the two+# languages got different verdicts from a difference in spacing conventions.+_NUMBER_RE = re.compile(+ r"(?<![A-Za-z0-9_])[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?!\d)")-# Localized calendar text carries digits that the ISO pattern above leaves-# behind: "8 月 3 日" otherwise contributes 8 and 3 as candidate prices.-_LOCALIZED_DATE_RE = re.compile(- r"(?:(?:19|20)\d{2}\s*年\s*)?\d{1,2}\s*月(?:\s*\d{1,2}\s*[日号])?|(?:19|20)\d{2}\s*年"+# SHAPE 2 — a calendar date or a bare year. Both are structural exemptions+# (spec §3): a date's digits are never a measurement. Only the spellings that+# could otherwise be read as a measurement need to be here — a year-less+# "8/5" or "08-10" is a pair of bare integers, which this gate does not check+# at all, so no mask is needed for them.+_DATE_RE = re.compile(+ r"(?:19|20)\d{2}\s*[-/年]\s*\d{1,2}\s*[-/月]\s*\d{1,2}\s*[日号]?"+ r"|\d{1,2}\s*月\s*\d{1,2}\s*[日号]"+ r"|(?:19|20)\d{2}\s*年"+ r"|(?:19|20)\d{2}")-# A numbered markdown heading ("### 6. 关键价位") names a section index, not-# a price. The ordered-list mask only covers line-leading "1." and stops at-# the "### " prefix, so the section number was extracted as a claim.-_NUMBERED_HEADING_RE = re.compile(r"(?m)^\s*#{1,6}\s*\d+(?:[.、.])?\s*")---# The clause splitter does not split on the ASCII period, so "close was 210.-# In 2024 the market rallied" stays one clause and 2024 would be misread as-# the asserted price. A period/bang/question followed by whitespace and a-# sentence-start (capital, quote, or bracket) is a boundary here — but only-# in this price-claim scan, never in the global clause splitter, where it-# would tear apart "000543.SZ" and "1.5". The capital/open-bracket lookahead-# deliberately excludes abbreviations: "close approx. 2500" keeps 2500 gated.-_SENTENCE_BOUNDARY_RE = re.compile(r"[.!?]\s+(?=[A-Z((])")---# Full-width enumeration commas delimit prose clauses. Paired brackets (ASCII-# or full-width ()()[]) are deliberately not separators: an explicit-# derivation such as "(8.5 - 7.9) / 2" must stay in one segment for the-# formula check, and 公司名(代码)价格 must stay in one segment so the-# unsourced-symbol gate can see the symbol with its figure (#1260).-# The English sentence period is a clause separator too. Without it two-# English sentences sharing a line were ONE clause, so the header's "last-# close" labelled the whole line and a derivation in the first sentence-# exempted a fabricated price in the second: "Based on close 1.171 * 0.80 =-# 0.937. The last traded price is 0.937." validated, while the byte-identical-# text with a paragraph break between the sentences was rejected — and the-# Chinese translation was rejected either way, because 。 always split. A-# per-language split is a per-language verdict, which is exactly what-# ``test_grounding_language_parity`` exists to stop.-# The lookahead is what keeps a decimal point, a ticker suffix (562500.SS) and-# an abbreviation ("approx. 1.10") out: only a period followed by whitespace-# and the start of a new sentence separates.-_CLAUSE_SEPARATOR_RE = re.compile(- r"[,,;;。、\n]|[.!?](?=\s+[\"'(\[“‘]?[A-Z])"-)+# SHAPE 3 — a line-leading ordinal: an ordered-list marker or a numbered+# heading. The punctuation is required, so a line that opens with a real+# figure ("1.171 元是收盘价") is untouched.+_ORDINAL_RE = re.compile(r"(?m)^[^\S\n]*(?:#{1,6}[^\S\n]*)?\d{1,3}[.)、.][^\S\n]+")-# The ASCII comma both separates clauses and groups thousands, and the clause-# split ran first: "收盘价 ¥1,309.22" became a clause ending in "¥1", whose 1 was-# compared against the observed 1300.01–1363.35 range and rejected as a-# conflict. That is every price above 999 written the ordinary way, and it is-# self-contradictory — ``_NUMBER_RE`` and the float conversion below it both-# already understand grouped numbers. Only a real group is removed: a comma-# needs a digit before it and exactly three digits after.-_THOUSANDS_SEPARATOR_RE = re.compile(r"(?<=\d),(?=\d{3}(?!\d))")+# SHAPE 4 — a fenced block. Its contents are code or the figures block, and+# neither is prose.+_FENCE_RE = re.compile(r"(?m)^[^\S\n]*(?:`{3,}|~{3,})[^\n]*$")-def _clause_spans(text: str, offset: int = 0) -> list[tuple[str, int, int]]:- """Split prose into clauses, keeping each clause's span in the source text.+# A currency marker is a SYMBOL SET, not a vocabulary: the question is only+# whether a character that denotes money touches the number, which is what+# makes a bare integer ("$100", "820 CNY") measurement-shaped. Membership is+# per character for the symbols and per token for the ISO codes.+_CURRENCY_CHARS = frozenset("$¥¥€£₩₹元币圆镑")- A grouping comma is not a separator and is stripped from the returned- segment text, but the span is into the ORIGINAL, un-stripped text. The- redaction path needs that: it used to locate a flagged clause with- ``text.find(claim)`` on the normalised string, which never matched once a- price carried a thousands separator ("1,450.50"), and which matched inside- an unrelated longer number when the claim was a bare table cell ("1.10"- found inside "21.10").- Args:- text: One line of candidate answer text.- offset: Where ``text`` starts inside the document being validated.+_CURRENCY_CODES = frozenset(+ {+ "USD", "CNY", "CNH", "RMB", "HKD", "JPY", "EUR", "GBP", "KRW", "INR",+ "CAD", "AUD", "SGD", "TWD", "THB", "IRR", "IRT", "USDT", "USDC",+ }+)- Returns:- ``(segment, start, end)`` per clause, with ``start``/``end`` measured- in the document (``offset`` already added).- """- bounds: list[tuple[int, int]] = []- cursor = 0- for match in _CLAUSE_SEPARATOR_RE.finditer(text):- if match.group(0) == "," and _THOUSANDS_SEPARATOR_RE.match(text, match.start()):- continue- bounds.append((cursor, match.start()))- cursor = match.end()- bounds.append((cursor, len(text)))- return [- (_THOUSANDS_SEPARATOR_RE.sub("", text[start:end]), start + offset, end + offset)- for start, end in bounds- ]++_PERCENT_CHARS = "%%"+++# A CJK currency word is at most three characters (人民币 is the longest).+# Bounding the run is what keeps 元宵/元件 from reading as money: those sit+# inside a longer uninterrupted CJK run.+_MAX_CURRENCY_WORD = 3+++@dataclass(frozen=True)+class Declaration:+ """One parsed line of the model's figures block."""++ index: int+ value_text: str+ value: float+ percent: bool+ role: str+ note: str+ ref: str+++@dataclass(frozen=True)+class FiguresBlock:+ """The declaration block, or the absence of one."""++ present: bool+ span: tuple[int, int] | None+ raw: str+ declarations: tuple[Declaration, ...]+ malformed: tuple[tuple[int, str], ...]++ def match(self, value: float, percent: bool) -> Declaration | None:+ """Return the declaration covering ``value``, or None.++ Matching is by NUMERIC value at the precision the figure was written+ with (tolerance 1e-9), and percent-ness must agree: ``37%`` and+ ``0.37`` are different assertions and never cover each other, while+ ``37%`` and ``37 %`` are the same one.++ Args:+ value: The prose figure's numeric value.+ percent: Whether the prose figure carries a percent sign.++ Returns:+ The first matching declaration, or None.+ """+ for declaration in self.declarations:+ if declaration.percent != percent:+ continue+ if abs(declaration.value - value) <= max(abs(value) * 1e-9, 1e-9):+ return declaration+ return None+++@dataclass(frozen=True)+class Figure:+ """One number located in the prose, with the shape it was written in."""++ text: str+ value: float+ percent: bool+ start: int+ end: int+ line: int+ shape: str+ column: str | None = None+ date: str | None = None+ symbol: str | None = None+++@dataclass(frozen=True)+class TableRow:+ """One Markdown table row and the column roles of its header."""++ line: int+ cells: tuple[tuple[str, int, int], ...]+ columns: dict[int, str]+ date_column: int | None+ symbol_column: int | None+++# Header spellings that bind a table column to an OHLC field or to a date.+# These are the TABLE's own schema — the column header declares what its+# cells are, exactly as a tool result's field name declares what its leaf is+# — so they are a header map, not prose inference (spec §4).+_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 _lines_with_offsets(content: str) -> list[tuple[str, int]]:"""Return each line of ``content`` with its character offset in it.``str.splitlines`` discards the terminators, so an issue raised on a line- cannot say where in the document that line sits. Offsets are recovered by- scanning forward, which is exact because only line terminators separate+ could not say where in the document that line sits. Offsets are recovered+ by scanning forward, which is exact because only line terminators separateone line's end from the next line's start."""positions: list[tuple[str, int]] = []@@ -173,4 +218,398 @@ def _lines_with_offsets(content: str) -> list[tuple[str, int]]:return positions-_TABLE_SEPARATOR_RE = re.compile(r"^:?-{3,}:?$")+def _fenced_blocks(content: str) -> list[tuple[int, int, str, tuple[int, int]]]:+ """Return ``(start, end, info, body)`` for every fenced block.++ An unterminated fence runs to the end of the document, which is how a+ truncated answer ends and must not silently un-fence the rest of it.+ """+ fences = list(_FENCE_RE.finditer(content))+ blocks: list[tuple[int, int, str, tuple[int, int]]] = []+ index = 0+ while index < len(fences):+ opener = fences[index]+ info = opener.group(0).strip().lstrip("`~").strip().casefold()+ if index + 1 < len(fences):+ closer = fences[index + 1]+ blocks.append((opener.start(), closer.end(), info, (opener.end(), closer.start())))+ index += 2+ else:+ blocks.append((opener.start(), len(content), info, (opener.end(), len(content))))+ index += 1+ return blocks+++def _parse_value(text: str) -> tuple[float, bool] | None:+ """Parse a declared value, tolerating currency marks and separators."""+ raw = text.strip().replace(",", "").replace(" ", "").replace(" ", "")+ percent = raw.endswith(tuple(_PERCENT_CHARS))+ if percent:+ raw = raw[:-1]+ raw = raw.strip("".join(_CURRENCY_CHARS))+ if not raw:+ return None+ try:+ return float(raw), percent+ except ValueError:+ return None+++def parse_figures_block(content: str) -> FiguresBlock:+ """Parse the model's ``figures`` block out of a draft.++ Parsing is lenient by contract (spec §2): a full-width pipe, run-on+ spacing and a missing ``ref`` are all accepted. What is NOT accepted is+ silence — a line that cannot be read as ``value | role | note | ref`` is+ reported as malformed, because a declaration the gate skipped is a figure+ the gate never checked.++ Args:+ content: The candidate answer.++ Returns:+ The parsed block, or an absent one when the draft has no block.+ """+ target: tuple[int, int, str, tuple[int, int]] | None = None+ for block in _fenced_blocks(content):+ if block[2] == BLOCK_LANGUAGE:+ target = block+ if target is None:+ return FiguresBlock(False, None, "", (), ())+ start, end, _, (body_start, body_end) = target+ body = content[body_start:body_end]+ declarations: list[Declaration] = []+ malformed: list[tuple[int, str]] = []+ for offset, line in enumerate(body.splitlines()):+ stripped = line.strip()+ if not stripped:+ continue+ parts = [part.strip() for part in stripped.replace("|", "|").split("|")]+ parts = [part for part in parts if part != ""] or [""]+ parsed = _parse_value(parts[0]) if parts else None+ role = parts[1].casefold() if len(parts) > 1 else ""+ if parsed is None or role not in ROLES:+ malformed.append((offset + 1, stripped[:120]))+ continue+ value, percent = parsed+ declarations.append(+ Declaration(+ index=offset + 1,+ value_text=parts[0],+ value=value,+ percent=percent,+ role=role,+ note=parts[2] if len(parts) > 2 else "",+ ref=parts[3] if len(parts) > 3 else "",+ )+ )+ return FiguresBlock(True, (start, end), body, tuple(declarations), tuple(malformed))+++def strip_figures_block(content: str, block: FiguresBlock) -> str:+ """Return the text to release: the draft without its declaration block."""+ if block.span is None:+ return content+ start, end = block.span+ return (content[:start].rstrip() + "\n" + content[end:].lstrip()).strip()+++def _table_cells(line: str, offset: int) -> list[tuple[str, int, int]]:+ """Split one Markdown row into ``(text, start, end)`` cells."""+ if line.count("|") < 2:+ return []+ cells: list[tuple[str, int, int]] = []+ cursor = 0+ for piece in line.split("|"):+ start = cursor+ cursor += len(piece) + 1+ text = piece.strip()+ if not text:+ cells.append(("", offset + start, offset + start + len(piece)))+ continue+ lead = len(piece) - len(piece.lstrip())+ cells.append((text, offset + start + lead, offset + start + lead + len(text)))+ if cells and cells[0][0] == "":+ cells = cells[1:]+ if cells and cells[-1][0] == "":+ cells = cells[:-1]+ return cells+++def _is_separator_row(cells: Sequence[tuple[str, int, int]]) -> bool:+ """Whether every cell is a Markdown alignment run (``---``, ``:--:``)."""+ if not cells:+ return False+ return all(+ text and set(text.replace(" ", "")) <= {"-", ":"} and "-" in text+ for text, _, _ in cells+ )+++def table_rows(content: str) -> list[TableRow]:+ """Return every Markdown table row with its header's column roles.++ A table block is a maximal run of lines carrying at least two pipes. The+ first line is the header; its cells bind columns to OHLC fields, to the+ trade date and to the symbol, which is the only per-column semantics this+ gate has (spec §4).+ """+ positions = _lines_with_offsets(content)+ rows: list[TableRow] = []+ index = 0+ while index < len(positions):+ if positions[index][0].count("|") < 2:+ index += 1+ continue+ block_start = index+ while index < len(positions) and positions[index][0].count("|") >= 2:+ index += 1+ header = _table_cells(positions[block_start][0], positions[block_start][1])+ headers = [text.casefold() for text, _, _ in header]+ columns = {+ position: _TABLE_FIELD_ALIASES[name]+ for position, name in enumerate(headers)+ if name in _TABLE_FIELD_ALIASES+ }+ date_column = next(+ (position for position, name in enumerate(headers) if name in _DATE_HEADERS),+ None,+ )+ symbol_column = next(+ (position for position, name in enumerate(headers) if name in _SYMBOL_HEADERS),+ None,+ )+ for line_index in range(block_start + 1, index):+ cells = _table_cells(positions[line_index][0], positions[line_index][1])+ if not cells or _is_separator_row(cells):+ continue+ rows.append(+ TableRow(line_index, tuple(cells), columns, date_column, symbol_column)+ )+ return rows+++def _currency_before(text: str, start: int) -> bool:+ """Whether a currency symbol touches the number on its left."""+ head = text[:start].rstrip()+ return bool(head) and head[-1] in _CURRENCY_CHARS+++def _currency_after(text: str, end: int) -> bool:+ """Whether a currency symbol or ISO code touches the number on its right.++ The CJK branch takes the maximal run of CJK characters and accepts it only+ when it is short enough to BE a currency word: "美元" qualifies, the+ six-character run of "元宵节后关注" does not.+ """+ tail = text[end:].lstrip()+ if not tail:+ return False+ if tail[0] in _CURRENCY_CHARS and not _is_cjk(tail[0]):+ return True+ if _is_cjk(tail[0]):+ run = ""+ for char in tail:+ if not _is_cjk(char):+ break+ run += char+ return len(run) <= _MAX_CURRENCY_WORD and any(+ char in _CURRENCY_CHARS for char in run+ )+ code = ""+ for char in tail:+ if not char.isascii() or not char.isalpha():+ break+ code += char+ return code.upper() in _CURRENCY_CODES+++def currency_prefix_start(text: str, start: int) -> int:+ """Where a currency symbol attached to the LEFT of a figure begins.++ Redacting "$1.10" has to take the "$" with it, or the released sentence+ reads "$(omitted)".+ """+ head = text[:start]+ stripped = head.rstrip()+ if stripped and stripped[-1] in _CURRENCY_CHARS and not _is_cjk(stripped[-1]):+ return len(stripped) - 1+ return start+++def currency_suffix_end(text: str, end: int) -> int:+ """Where a currency unit attached to the RIGHT of a figure ends.++ Redacting "0.95 元" has to take the 元 with it. It must NOT take the first+ half of a compound unit: 元/股 and USD/share are one unit, and swallowing+ only its numerator left a denominator with nothing above it.+ """+ tail = text[end:]+ lead = len(tail) - len(tail.lstrip(" \t"))+ body = tail[lead:]+ if not body:+ return end+ run = ""+ if _is_cjk(body[0]):+ for char in body:+ if not _is_cjk(char):+ break+ run += char+ if len(run) > _MAX_CURRENCY_WORD or not any(+ char in _CURRENCY_CHARS for char in run+ ):+ return end+ else:+ for char in body:+ if not char.isascii() or not char.isalpha():+ break+ run += char+ if run.upper() not in _CURRENCY_CODES:+ return end+ following = body[len(run) : len(run) + 1]+ if following in {"/", "/"}:+ return end+ return end + lead + len(run)+++def _is_cjk(char: str) -> bool:+ """Whether a character is in the CJK ideograph range."""+ return "㐀" <= char <= "鿿"+++# Punctuation that ends one statement and starts the next. This is the ONLY+# segmentation the gate has, and it is made of characters: it decides which+# instrument a figure is about (spec §4), never what the figure means. The+# ASCII period counts only when whitespace follows it, which is what keeps a+# decimal, a ticker suffix and an abbreviation inside one segment.+_SEGMENT_BREAKS = frozenset(",,;;。、\n!!??")+++def segment_bounds(content: str, start: int, end: int) -> tuple[int, int]:+ """The punctuation-delimited stretch of text a figure sits in.++ Args:+ content: The whole answer.+ start: Where the figure starts.+ end: Where it ends.++ Returns:+ ``(segment start, segment end)`` in document offsets.+ """+ left = start+ while left > 0:+ char = content[left - 1]+ if char in _SEGMENT_BREAKS:+ break+ if char == "." and left < len(content) and content[left].isspace():+ break+ left -= 1+ right = end+ while right < len(content):+ char = content[right]+ if char in _SEGMENT_BREAKS:+ break+ if char == "." and right + 1 < len(content) and content[right + 1].isspace():+ break+ right += 1+ return left, right+++def _within(span: tuple[int, int], spans: Sequence[tuple[int, int]]) -> bool:+ """Whether ``span`` sits inside any of ``spans``."""+ return any(start <= span[0] and span[1] <= end for start, end in spans)+++def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:+ """Locate and classify every number in the prose of a draft.++ Three classes, and only three (spec §3):++ * ``exempt`` — a date, a year, digits inside a security code, a+ line-leading ordinal, a table's own date/symbol column, or anything+ inside a fenced block. Structure, not measurement.+ * ``measured`` — carries a decimal point, a percent sign, a touching+ currency mark, or sits in a table cell. This is the shape a fabricated+ price, level or metric is written in, and it must be declared.+ * ``bare`` — a plain integer with none of those marks. Counts, horizons,+ window lengths, lot sizes and line numbers all live here and are not+ checked, which is what retires the mask catalogue that used to try to+ name each of them.++ Args:+ content: The candidate answer.+ block: The parsed figures block (its span is exempt).++ Returns:+ Every number in document order, each with its span and shape.+ """+ positions = _lines_with_offsets(content)+ line_of: list[tuple[int, int, int]] = [+ (start, start + len(line), index) for index, (line, start) in enumerate(positions)+ ]+ # Every fenced block is exempt, the ``figures`` block among them: its span+ # comes from the same scan, so it needs no entry of its own.+ exempt: list[tuple[int, int]] = [+ (start, end) for start, end, _, _ in _fenced_blocks(content)+ ]+ for pattern in (_DATE_RE, _CANONICAL_SYMBOL_RE, _ORDINAL_RE):+ exempt.extend((match.start(), match.end()) for match in pattern.finditer(content))++ cell_at: list[tuple[int, int, TableRow, int]] = []+ for row in table_rows(content):+ for position, (_, start, end) in enumerate(row.cells):+ if position == row.date_column or position == row.symbol_column:+ exempt.append((start, end))+ continue+ cell_at.append((start, end, row, position))++ figures: list[Figure] = []+ for match in _NUMBER_RE.finditer(content):+ start, end = match.start(), match.end()+ percent = False+ tail = content[end:]+ stripped = len(tail) - len(tail.lstrip(" \t"))+ if tail[stripped : stripped + 1] and tail[stripped] in _PERCENT_CHARS:+ percent = True+ end = end + stripped + 1+ try:+ value = float(match.group(0).replace(",", ""))+ except ValueError:+ continue+ line = next(+ (index for low, high, index in line_of if low <= start <= high), 0+ )+ cell = next(+ (entry for entry in cell_at if entry[0] <= start and end <= entry[1]), None+ )+ if _within((start, match.end()), exempt):+ shape = "exempt"+ elif percent or "." in match.group(0) or cell is not None:+ shape = "measured"+ elif _currency_before(content, start) or _currency_after(content, match.end()):+ shape = "measured"+ else:+ shape = "bare"+ column = date_value = symbol_value = None+ if cell is not None:+ row, position = cell[2], cell[3]+ column = row.columns.get(position)+ if row.date_column is not None and row.date_column < len(row.cells):+ date_value = row.cells[row.date_column][0] or None+ if row.symbol_column is not None and row.symbol_column < len(row.cells):+ symbol_value = row.cells[row.symbol_column][0] or None+ figures.append(+ Figure(+ text=content[start:end],+ value=value,+ percent=percent,+ start=start,+ end=end,+ line=line,+ shape=shape,+ column=column,+ date=date_value,+ symbol=symbol_value,+ )+ )+ return figuresdiff --git a/agent/src/agent/grounding/ledger.py b/agent/src/agent/grounding/ledger.pyindex 35a32153a..26471648b 100644--- a/agent/src/agent/grounding/ledger.py+++ b/agent/src/agent/grounding/ledger.py@@ -19,6 +19,7 @@ from src.agent.grounding.identity import (_utc_now,)from src.agent.grounding.evidence import EvidenceRecord, _EvidenceMixin, _json_object+from src.agent.grounding.figures import parse_figures_block, scan_figures, strip_figures_blockfrom src.agent.grounding.policies import ValidationResult, _PolicyMixinfrom src.agent.grounding.release import (MAX_GROUNDING_RECOVERY_ROUNDS,@@ -263,12 +264,18 @@ class GroundingLedger(A deterministic validation result."""self._ingest_run_dir_ohlc_csvs()+ block = parse_figures_block(content)+ figures = scan_figures(content, block)issues: list[dict[str, Any]] = []issues.extend(self._validate_identity(content))- issues.extend(self._validate_unsourced_symbols(content))- issues.extend(self._validate_price_claims(content))- issues.extend(self._validate_analysis_claims(content))- result = ValidationResult(valid=not issues, issues=issues)+ issues.extend(self._validate_unsourced_symbols(content, figures, block))+ issues.extend(self._validate_figures(content, block, figures))+ issues = self._dedupe_issues(issues)+ result = ValidationResult(+ valid=not issues,+ issues=issues,+ released_text=strip_figures_block(content, block),+ )if not record:return resultself._validations.append(@@ -278,6 +285,7 @@ class GroundingLedger("content_sha256": hashlib.sha256(content.encode("utf-8")).hexdigest(),"valid": result.valid,"issues": issues,+ "figures_block": block.raw,})self.persist()diff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.pyindex 13e79b9dc..df9c5e4a8 100644--- a/agent/src/agent/grounding/policies.py+++ b/agent/src/agent/grounding/policies.py@@ -1,13 +1,22 @@-"""Per-claim validation: the checks that turn evidence into issues."""+"""Per-role validation: what each declared figure has to survive.++The model declares what every measurement-shaped number in its answer IS+(spec §2); this module decides whether the evidence backs that declaration+(spec §4). It reads no prose word. Its predecessor did — twenty-two masks and+a dozen phrase catalogues — and the catalogues could never close: the same+sentence passed in one language and failed in the other, a level word the list+had not seen cost a revision round, and every new phrasing needed a new entry.+Roles now come from the model, evidence comes from the ledger, and shape comes+from :mod:`figures`.+"""from __future__ import annotationsimport astimport jsonimport math-import refrom dataclasses import dataclass, field-from typing import Any, Sequence+from typing import Any, Iterable, Sequencefrom src.agent.grounding.identity import (_CANONICAL_SYMBOL_RE,@@ -18,54 +27,20 @@ from src.agent.grounding.evidence import (EvidenceRecord,_is_number,_metric_kind_for_path,- _metric_kind_for_text,_timestamp_matches_claim_date,)from src.agent.grounding.figures import (- _DASH_DATE_RE,- _DATE_RE,- _LOCALIZED_DATE_RE,- _MD_LIST_ITEM_RE,- _NUMBERED_HEADING_RE,- _NUMBER_RE,- _SENTENCE_BOUNDARY_RE,- _SHORT_DATE_RE,- _TABLE_SEPARATOR_RE,- _clause_spans,+ Declaration,+ Figure,+ FiguresBlock,_lines_with_offsets,+ segment_bounds,)-# Tools whose run produces the equity/regime windows behind a categorical-# "all N-month windows were profitable" statement.-_ANALYSIS_WINDOW_TOOLS = frozenset({"backtest", "run_shadow_backtest"})---# Unit / currency tokens glued to a price, swallowed with the figure.-# The single-character 元 additionally guards against CJK: without it the-# swallow ate the 元 of 元宵/元旦/元件 and left an orphan "宵节后关注" in the-# released text. The multi-character units cannot start a longer word the-# same way, so they keep the Latin-only guard (it is there for USD/USDT).-# Both guards also refuse a following slash: 元/股 and USD/share are ONE-# compound unit, and swallowing only its first half rewrote-# "建议买入价 0.95 元/股" into "建议买入价(略※)/股" — a denominator with-# nothing left above it.-_CURRENCY_UNIT_WORDS = (- r"人民币|美元|美金|港元|港币|日元|欧元|英镑|"- r"CNY|RMB|USD|HKD|JPY|EUR|GBP|CAD|AUD|SGD|USDT"-)---# The same tokens without the swallow guards. Those guards decide how much-# text the marker may EAT; this one only asks whether a figure is written as a-# price, and there "1.180 元已回撤" is as much a quote as "1.180 元。" is.-_UNIT_TOKEN_AFTER_RE = re.compile(- r"\s*(?:" + _CURRENCY_UNIT_WORDS + r"|元)", re.IGNORECASE-)---_CURRENCY_BEFORE_RE = re.compile(r"(?:US\$|HK\$|C\$|A\$|S\$|\$|¥|¥|€|£)\s*$")-+import re+#: An answer that relabels a locked listed identity as private contradicts the+#: resolver, which is an identity finding rather than a figure finding._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|"@@ -74,620 +49,10 @@ _PRIVATE_ASSERTION_RE = re.compile()-# The bare verbs below are present tense only, which is not how an answer-# actually states an observed price: "closed at 412.35" and "last traded at-# 412.35" are the ordinary spellings and neither matches \bclose\b or-# \btrade\b. Chinese 收盘 / 现价 match, so the gate was strictly leakier in-# English than in Chinese — a fabricated USD price in the most natural-# phrasing walked straight through while its Chinese translation was caught.-# The past-tense forms are required to be followed by "at" so that reporting-# volume ("traded 1.2M shares") or a corporate event ("the deal closed at a-# 30% premium" — a percentage, already masked) is not read as a quote.-_PRICE_VERB_PAST_RE = r"\b(?:closed|opened|traded|quoted|priced|settled|fixed)\s+at\b"---_PRICE_CONTEXT_RE = re.compile(- r"(?:\b(?:opening|open|high|low|closing|close|price|quote)\b|"- + _PRICE_VERB_PAST_RE + r"|"- r"\b(?:entry|buy|target|support|resistance)\s+(?:price|level)\b|"- r"开盘价?|最高价?|最低价?|收盘价?|买入价|入场价|目标价|支撑位?|阻力位?|"- # Chinese had the mirror-image gap: these four are as ordinary as 收盘价- # and none of them matched, so a fabricated 成交价 / 股价 walked through- # exactly the way "closed at" did in English.- r"成交价|最新价|股价|收报|"- r"现价|报价|价格|价位)",- re.IGNORECASE,-)---# The vocabulary of a price LEVEL — a band, a moving average, a support or-# resistance line. It is the only shape for which an indicator reading is-# admissible evidence, and the rule is stated this way round on purpose.-#-# It used to be stated the other way: an indicator was admissible unless the-# clause named an OHLC field, against a hand-written list of field phrases.-# A hand-written denylist is only ever as complete as the day it was typed,-# and it was not complete for one day: with the session's sma_20 at 1.150 and-# the observed close at 1.171, "收盘价为 1.150 元" was caught while "收盘于"'s-# English twins "closed at 1.150" / "the close was 1.150" / "highest price was-# 1.150" were released, and every spot-quote spelling there is — 现价 / 最新价-# / 成交价 / 报价 / 股价 / current price / the quote is — leaked in both-# scripts, because a spot quote names the latest print and named no OHLC-# field. An allowlist fails the other way: a level word this list misses costs-# a correction round instead of releasing a fabricated print.-_PRICE_LEVEL_WORD_RE = re.compile(- r"(?:\b(?:support|resistance|pivot|moving[- ]average|"- r"(?:upper|lower|middle) band|band|channel|bollinger|keltner|donchian|"- r"ichimoku|supertrend|vwap|atr)\b|"- r"\b(?:SMA|EMA|WMA|DMA|MA|BOLL)\d{0,3}\b|"- r"支撑|阻力|压力|均线|上轨|下轨|中轨|轨道|通道|中枢|枢轴|布林)",- re.IGNORECASE,-)---_ANALYSIS_METRIC_RE = re.compile(- r"(?:\breturn vol(?:atility)?\b|\bmax(?: |\.)?drawdown\b|\bmaxdd\b|"- r"\bsharpe(?: ratio)?\b|\bwin rate\b|\bhit rate\b|"- r"\bprob(?:ability)?\.?\s+of\b|\bvolatility\b|\bdrawdown\b|"- r"\bannualiz\w*\b|\bwindow(?:s)?\b|\bregime(?:s)?\b|"- r"\b(?:annual|cumulative|total)\s+return\b|"- r"夏普|回撤|波动率|胜率|命中率|概率|年化|回测|窗口|收益(?:率)?|回报(?:率)?)",- re.IGNORECASE,-)---# Phrases that indicate a figure is attributed to an external source rather-# than model memory (paper restatement, #1338 review). Attributing a number-# to a named source is the opposite of an unsourced claim. The subject list-# is deliberately restricted to sources that cannot be this run's own output-# (papers, studies, analysts, filings): "the backtest reports" / "the data-# shows" is exactly how a model dresses up its own numbers (#1336), so-# data/backtest/strategy/report subjects do NOT count.-_ATTRIBUTION_RE = re.compile(- r"(?:"- r"\b(?:the\s+(?:papers?|studies?|researchers?|analysts?|surveys?"- r"|regulators?|authorities|literature|authors?)"- r"|analysts?|researchers?|literature|sec\s+filings?\b|filings?"- r"|annual\s+filings?|quarterly\s+filings?|rating\s+agencies?)"- r"\s+(?:reports?|estimates?|shows?|indicates?|suggests?|states?|claims?"- r"|notes?|cites?|mentions?|reveals?|discloses?|publishes?|found"- r"|calculated|computed|derived)\b"- r"|"- r"(?:论文|文献|分析师|研究机构|学者)"- r"[^。,\n]{0,6}?(?:报告|显示|表明|指出|称|估计|发现)"- r")",- re.IGNORECASE,-)---# Measurement-shaped numbers for analysis claims: keeps the % sign and sign-# (unlike _numbers_without_dates_or_percent, which drops percentages on-# purpose). A bare integer is NOT a measurement — "252 个交易日年化" is the-# standard convention, not a claim about this run's analysis (#1032-style-# definitional prose must stay untouched). Dates can still look like-# measurements, so date masks run first.-_MEASURE_NUMBER_RE = re.compile(- r"[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)\s*[%%]?" # decimal: 1.21, -8.1%- r"|[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)\s*[%%]" # integer percent: 55%, 70%-)---# A forward-looking frame means the figure is a forecast, not a claim that a-# backtest/analysis measured it — the measurement gate only polices "measured-# facts" (#1336), forecasts stay under the "analysis, not advice" prompt rule.-_FORECAST_FRAME_RE = re.compile(- r"(?:\b(?:forecast|expected|projected|predicted)\b|预计|预期|预测|估计|展望)",- re.IGNORECASE,-)---# Definitional prose ("夏普比率大于 1.0 通常被认为较好") states a convention,-# not a measurement this session produced (#1336: preserve explicitly labelled-# definitions). The bare 通常 alone is deliberately not enough — "通常实现-# 18.2% 年化" is a measured claim.-_DEFINITION_FRAME_RE = re.compile(- r"(?:通常(?:认为|被?认为|说来|指|用于)|一般认为|定义为|是指|惯例|"- r"conventionally|typically\s+(?:considered|regarded|seen)|"- r"generally\s+(?:accepted|considered|regarded)|by\s+convention)",- re.IGNORECASE,-)---# A categorical "all N-month windows were profitable" claim carries only an-# integer window length, which _MEASURE_NUMBER_RE deliberately ignores; it is a-# measured fact about the run and needs a window-producing analysis result.-_CATEGORICAL_WINDOW_RE = re.compile(- r"(?:所有|全部|每个|任何|each|every|all)[\s\S]{0,40}?"- r"(?:窗口|区间|windows?|periods?)[\s\S]{0,30}?"- r"(?:正收益|均为正|都为正|盈利|上涨|positive|profitable)",- re.IGNORECASE,-)---_DERIVATION_RE = re.compile(- r"(?:\bderived\b|\bcalculated\b|\bformula\b|\bbased on\b|计算|推导|公式|基于)",- re.IGNORECASE,-)---# The separator between a formula and its result. "=" is how the gate first-# accepted a derivation; "≈" / "≒" / "约" / "约等于" are how a model writes one-# whose result it rounded, and each was rejected with the multiplier read as a-# quoted price. The evaluation tolerance already absorbs the rounding.-# The English spellings are here for the same reason the Chinese ones are:-# ``test_derived_return_exemption_is_structural_not_phrasal`` is the repo's-# standing rule that identical arithmetic gets an identical verdict in both-# languages, and "1.171 * 0.97 approximately 1.136" was still burning a-# revision round while its ≈ twin passed.-_RESULT_SEPARATOR_RE = re.compile(- r"约等于|≈|≒|=|约|~|\b(?:approximately|approx\.?|about|around|roughly)\b",- re.IGNORECASE,-)---# The subject of a performance metric decides which evidence may ground it.-# A strategy's max drawdown is a property of an equity curve a backtest-# produced; two observed prints of the instrument are not that curve, and-# neither is any arithmetic on them. "回测显示该策略最大回撤 5.9%(从 1.180-# 跌至 1.110)" rode out of the session on the endpoint-arithmetic exemption-# with no backtest anywhere in it. A PRICE-subject drawdown ("股价较 5 月高点-# 1.053 元已回撤约 37%") is the arithmetic itself and keeps the exemption.-_STRATEGY_SUBJECT_RE = re.compile(- r"(?:\bstrateg(?:y|ies)\b|\bbacktest(?:ed|ing)?\b|\bportfolio\b|"- r"\bequity curve\b|\bNAV\b|\bholdings?\b|"- r"策略|回测|组合|持仓|净值)",- re.IGNORECASE,-)---_INDICATOR_IDENTIFIER_RE = re.compile(r"(?<![0-9.])[A-Za-z_]+\d+(?![0-9.])")---# Unitless identity constants in a symbolic rate formula are not quoted prices.-# Without this mask, ``1 - 单边成本率`` in a position-sizing formula is read as-# a one-yuan price merely because the same clause also mentions a close price.-# Keep the relaxation narrow: only 0/1 directly participating in arithmetic-# with a token explicitly labelled as a rate is removed.-_RATE_FORMULA_IDENTITY_RE = re.compile(- r"\b[01](?=\s*[-+]\s*(?:[A-Za-z_][A-Za-z0-9_]*_?rate\b|[^\d\s()+*/=-]{0,12}(?:成本率|费率|税率|滑点率)))",- re.IGNORECASE,-)---# A level stated as a RANGE has the same shape: the separator touches the-# second number, so masking "目标价 10" left "-20" behind and a negative price-# matches no OHLC window at all -- a guaranteed rejection of a correct draft.-# The tail is optional, so a single-value level is unaffected.-_RANGE_TAIL = r"(?:\s*[-–—~~至到]\s*[-+]?\d[\d,]*(?:\.\d+)?)?"---# A percentage range masks only its upper bound through the "%" tail check-# below, because the sign touches the second number: "1–2%" left 1 behind-# (#983). Mask the span as a whole.-_PERCENT_RANGE_RE = re.compile(- r"\d[\d,]*(?:\.\d+)?\s*[-–—~至]\s*\d[\d,]*(?:\.\d+)?\s*[%%]"-)---# A percentage-POINT delta is not a quoted price. "~3.6pp below Penumbra"-# describes a margin gap; left unmasked the ".6" is consumed as a decimal-# and the number reaches the OHLC comparator, which then rejects an-# otherwise correct fundamentals answer and demands `get_market_data` to-# substantiate a claim that has nothing to do with price.-# The trailing "%" spellings are already handled above; this covers the-# percentage-point spellings, which the percent masks never matched.-# The Chinese units take an optional measure word ("3.6 个百分点" is the-# ordinary spelling; bare "3.6 百分点" is the rare one) and are matched-# without a trailing \b: after a CJK character \b requires a non-word-# character to follow, so "下降 3.6 个百分点后企稳" would not match. The-# ASCII units keep \b, which is what stops "3.6ppm" being read as pp.-_PERCENTAGE_POINT_RE = re.compile(- r"[-+~≈]?\s*\d[\d,]*(?:\.\d+)?\s*"- r"(?:(?:pp|ppt|ppts|bps|bp)\b|个?(?:百分点|基点))",- re.IGNORECASE,-)---# An aggregate amount is not a quoted price. "100 股成本 820 CNY" states a-# position cost; comparing 820 against a per-share OHLC range is a category-# error. The tradeoff is that a per-share figure written only as "成本 8.20"-# goes unchecked — provenance still requires symbol, source, and currency.-_AGGREGATE_AMOUNT_RE = re.compile(- r"(?:成本|总额|总价|总市值|市值|合计|金额|cost|total|notional|market value)"- r"\s*(?:为|是|约)?\s*[::]?\s*[-+]?\d[\d,]*(?:\.\d+)?",- re.IGNORECASE,-)---# Quantities, horizons, lot sizes, and lookback windows are unit-bearing:-# "100 股", "1–4 周", "3 个月", "52-week", "20/50/200-day". None are prices.-# The hyphenated English compound needs its own branch: the range alternation-# consumes "-4" in "1-4 周" but stalls on "-week", which left 52 behind to be-# compared against an OHLC range (#1001). The slash enumeration shares a single-# trailing unit, so "20/50/200-day" has to be masked as one span or its first-# two window lengths survive. ASCII units carry a trailing word boundary so-# "120 more" is not read as a quantity; the CJK branch cannot, because 周 and-# 内 are both word characters and "1–4 周内" must still mask.-_QUANTITY_WITH_UNIT_RE = re.compile(- r"\d[\d,]*(?:\.\d+)?"- r"(?:\s*/\s*\d[\d,]*(?:\.\d+)?)*"- r"(?:\s*[-–—~至]\s*\d[\d,]*(?:\.\d+)?)?"- r"\s*[-–—]?\s*"- r"(?:"- r"(?:股|手|张|份|口|笔|倍|个月|周|天|日|年|次|个交易日|项|行)"- r"|(?:shares?|contracts?|lots?|units?|sessions?|bars?|periods?|"- r"wks?|weeks?|months?|days?|years?|yrs?)\b"- r")",- re.IGNORECASE,-)---# A conviction reading is on a labelled scale, not a price scale: the 6 in-# "CONFIDENCE: 6" is bounded by the label that introduces it. Only the value-# bound to the label is masked, so a genuine quote elsewhere in the same-# clause is still checked. The optional denominator covers "6/10" (#1001).-_LABELLED_SCORE_RE = re.compile(- r"(?:confidence|conviction|score|rating|probability|odds|weighting|"- r"置信度|信心|评分|得分|概率|胜率)"- r"\s*(?:is|of|=|为|是)?\s*[::]?\s*"- r"[-+]?\d[\d,]*(?:\.\d+)?(?:\s*/\s*\d[\d,]*(?:\.\d+)?)?",- re.IGNORECASE,-)---# A named indicator reads on its own scale — "RSI of 46.7" is bounded at 100,-# not quoted in the instrument's currency. The name must be adjacent to the-# value, so a bare number elsewhere in the clause stays checked. Only-# unambiguous indicator names are listed: generic words such as "momentum" or-# "volatility" sit too close to price prose to mask safely.-_INDICATOR_VALUE_RE = re.compile(- r"\b(?:rsi|macd|atr|adx|cci|obv|kdj|boll|dif|dea|vix|iv|"- r"sharpe|sortino|beta)\b"- r"(?:\s*\([^)]{0,20}\))?"- # #1354: "RSI below 30" / "sharpe above 1" — a directional connective is- # part of the indicator reading, so the reading's number stays masked.- # Only indicator NAMES get these connectives; a price word with- # "below/above" ("close above 2500") is an observed-value claim and- # matches none of these names, so it stays gated.- r"\s*(?:is|at|of|reads?|=|为|是|below|above|under|over)?\s*[::]?\s*"- r"[-+]?\d[\d,]*(?:\.\d+)?",- re.IGNORECASE,-)---# A currency token may sit between a level marker or comparison operator and-# the number: "收盘 <$2.86", "目标位 C$6.80", "trigger at $119.68". Without-# it, the number survives masking and is compared against observed OHLC as a-# price claim even though it is a prospective level, not an observed quote.-_CURRENCY_TOKEN = r"(?:\$|US\$|C\$|HK\$|CAD|USD|CNY|HKD|¥|¥)?"---# An order line is an instruction, not an observation. "100 @ $3.50" states-# where a limit sits and "100" is a share count that was never a price at all,-# yet both went to the OHLC check and rejected a weekly update whose quotes-# were correct. This is the same category as the target/stop levels below -- a-# level the report proposes, not one the data source reported.--# #1354: a signal value trailing an arrow or a signal word ("sinal +1",-# "-> +1", "触发 +1", "Sinal: +1") is the formula's output, not an observed-# price. Signal values are small integers (a +/-1 signal, a 1-10 score); a-# multi-digit price never follows these words, so the digit bound keeps-# "close -> 2500" (a price claim written in arrow notation) gated. The colon-# is optional ("Sinal: +1" — ASCII '.' is not a clause separator, so this can-# sit in the same clause as the price word), the sign may be spaced ("sinal-# - 1"), and the lookahead stops the bound from masking the first two digits-# of a longer number ("signal 2500" keeps the full 2500 gated).-_SIGNAL_VALUE_RE = re.compile(- r"(?:\b(?:signal|sinal|trigger|triggers|triggered|dispara|信号|触发)\b[::]?"- r"|->|→|=>)"- r"\s*[-+]?\s*\d{1,2}(?:\.\d+)?(?!\d)",- re.IGNORECASE,-)---_ORDER_LEVEL_RE = re.compile(- r"(?:"- # (a) "<qty> [股|shares] @ <price>" -- the whole clause, quantity included- r"\d[\d,]*(?:\.\d+)?\s*(?:股|shares?)?\s*@\s*"- + _CURRENCY_TOKEN + r"\s*[-+]?\d[\d,]*(?:\.\d+)?"- r"|"- # (b) an order label, optionally carrying its own "<qty> @", then the level.- # There is deliberately no bare "@ <price>" branch: dates are masked before- # this runs, so "收盘 2026-08-10 @ 8.20" would arrive here as "@ 8.20" and a- # genuinely observed close would stop being checked. 买入价 / 卖出价 are- # absent for the same reason -- in running prose they name a price the- # report says it observed, not an instruction it proposes.- r"(?:挂单|限价单|限价|委托价?|订单"- r"|limit\s+(?:order|price)|\bGTC\b|\bGTD\b|\bIOC\b|\bFOK\b)"- r"\s*(?:为|是|at|=)?\s*[::]?\s*"- r"(?:\d[\d,]*(?:\.\d+)?\s*(?:股|shares?)?\s*@\s*)?"- + _CURRENCY_TOKEN + r"\s*[-+]?\d[\d,]*(?:\.\d+)?"- r")" + _RANGE_TAIL,- re.IGNORECASE,-)---# A historical reference names a price the instrument once traded at — an-# all-time high, a 52-week extreme — and the answer is not claiming it as-# today's observed quote. "8/12 高 149.60 为 6/16 ATH 225.64 以来最高" was-# rejected because 225.64 (the June ATH) fell outside this session's observed-# OHLC range. The marker must be adjacent to the number, so a plain field-# reading such as "8/12 高 149.60" stays checked: its 高 carries no historical-# qualifier. "创历史新高" shares the 历史新高 marker and is masked with it; the-# relaxation follows the same trade-off as prospective levels — the historical-# extreme is a reference, not an assertion about the current bar.-_REFERENCE_LEVEL_RE = re.compile(- r"(?:"- r"\bATH\b|all[- ]?time\s+(?:high|low)|"- r"52\s*[- ]?W(?:EEK)?\s*(?:high|low)|52\s*[- ]?W(?:EEK)?\s*高(?:点|位)?|"- r"52\s*周(?:高|低)(?:点|位)?|"- r"历史(?:最高|最低|新高|新低|高|低)(?:点|位|价)?|"- r"上市以来(?:最高|最低)(?:点|位|价)?"- r")"- r"\s*(?:of|为|是|约|at)?\s*[::]?\s*\(?"- r"\s*" + _CURRENCY_TOKEN + r"\s*[-+]?\d[\d,]*(?:\.\d+)?" + _RANGE_TAIL,- re.IGNORECASE,-)---# A date-anchored reference puts the historical extreme after the number:-# "7/10(150.57)以来最高" and "highest since 7/10 (150.57)". The parenthesized-# value is the earlier high/low, not a current quote, and was rejected against-# the session's observed window (which does not reach back to July).-_SINCE_REFERENCE_RE = re.compile(- r"[-+]?\d[\d,]*(?:\.\d+)?\s*\)?\s*以来(?:最高|最低|高|低)(?:点|位)?"- # Dates are masked before this runs, so "since 7/10 (150.57)" has lost its- # date digits by the time the connector is matched.- r"|(?:highest|lowest)\s+since[^0-9\n]{0,16}"- r"[-+]?\d[\d,]*(?:\.\d+)?",- re.IGNORECASE,-)---# A validation report cites a plan file by line number — "~line 206",-# "第 206 行" — and the number is a document location, not a price. Before-# this mask, "**文档 ~line 206「…」不成立" contributed 206.0 as a candidate-# price claim and was rejected against the observed OHLC range.-_LINE_REFERENCE_RE = re.compile(- r"(?:~\s*)?\blines?\b\s*[:#]?\s*\d{1,5}(?:\s*[-–—至~]\s*\d{1,5})?"- r"|第\s*\d{1,5}(?:\s*[-–—至~]\s*\d{1,5})?\s*行"- r"|行\s*[::]?\s*\d{1,5}(?:\s*[-–—至~]\s*\d{1,5})?",- re.IGNORECASE,-)---# A ratio ("6:1 折算", "10:1") names a conversion basis, not a quote price.-_RATIO_RE = re.compile(r"\d+(?:\.\d+)?\s*[::]\s*\d+(?:\.\d+)?")---# A currency conversion cited inside a report ("USD/CAD≈1.36") is a basis, not-# an instrument quote. But `EUR/USD` IS this project's canonical forex symbol-# (``backtest/engines/forex.py``, and akshare_loader accepts the slash form), so-# masking every ``AAA/BBB <number>`` would stop checking real FX quotes on a-# first-class market — an invented rate would pass. The pair form therefore-# requires an approximation marker, which a conversion basis carries and a quote-# does not: "USD/CAD≈1.36" is masked, bare "USD/CAD 1.36" stays checked. The-# labelled 汇率 / "exchange rate" form is unambiguous and needs no marker.-_FX_RATE_RE = re.compile(- r"[A-Z]{3}\s*/\s*[A-Z]{3}\s*(?:≈|~|约)\s*\d+(?:\.\d+)?"- r"|(?:汇率|FX\s*rate|exchange\s+rate)\s*(?:≈|~|=|为|是)?\s*\d+(?:\.\d+)?",- re.IGNORECASE,-)---# A trading plan quotes levels it does not claim to have observed. In the-# committee report attached to #983, "收盘 ≥6.45 且量 ≥35M手" is an entry-# trigger, "年线 4.63 成目标区" is a target zone, and neither asserts anything-# about what the instrument traded at. Compared against observed OHLC evidence-# they were reported first as numeric_claim_unavailable (before the run fetched-# prices) and then as numeric_claim_conflict (after it did) — the same false-# positive under two codes.-#-# This is a real relaxation, so every branch is span-local and anchored to the-# token that makes the number prospective, never to a word elsewhere in the-# clause: "现价 5.97,目标位 6.45" masks 6.45 and still checks 5.97. An-# assertion carries no such token and stays checked.-#-# Branch (d) accepts a conditional opener. A number inside "若收盘 5.36" is a-# hypothesis, and a hypothesis does not misrepresent observed data the way a-# bare quote does — but it is the widest branch here, so it requires the opener-# to PRECEDE the number with no digits in between, which keeps it from reaching-# back over an assertion that was already made.-_PROSPECTIVE_LEVEL_RE = re.compile(- r"(?:"- # (a) comparison operator immediately before the number- r"(?:>=|<=|≥|≤|>|<|大于|小于|不低于|不高于|高于|低于)"- r"\s*" + _CURRENCY_TOKEN + r"\s*[-+]?\d[\d,]*(?:\.\d+)?" + _RANGE_TAIL- + r"|"- # (b) a level marker introducing the number- r"(?:目标位|目标区|目标价|均值目标(?:价)?|平均目标(?:价)?|止损位?|止盈位?|触发价|触发位|触发点|上看|下看|"- r"支撑(?:阶梯|位|线)?|阻力(?:位|线)?|压力位|压力线|support(?:\s+(?:level|line|zone))?|"- r"resistance(?:\s+(?:level|line|zone))?|target\s+(?:price|level|zone)|trigger|stop[-\s]?loss|take[-\s]?profit)"- r"\s*(?:为|是|至|到|on|at|of|=)?\s*[::]?\s*"- + _CURRENCY_TOKEN- + r"\s*[-+]?\d[\d,]*(?:\.\d+)?" + _RANGE_TAIL- + r"|"- # (c) the number followed by a level marker- r"" + _CURRENCY_TOKEN + r"[-+]?\d[\d,]*(?:\.\d+)?" + _RANGE_TAIL- + r"\s*(?:一线|附近)?\s*(?:成为?|作为|是)?\s*"- r"(?:目标区|目标位|止损位|止盈位)"- r"|"- # (d) a conditional opener before the number, digits fencing the reach- r"(?:若|如果|一旦|倘若|假如|\bif\b|\bwhen\b|\bshould\b)[^0-9\n]{0,12}"- r"[-+]?\d[\d,]*(?:\.\d+)?"- r")",- re.IGNORECASE,-)---# #1354: the closed structural rule for prose price claims. A number that-# follows a price-context word is an observed value only when nothing-# formula-like binds it instead. Two closed token classes decide that:-#-# * a formula marker sitting between the price word and the number — a-# comparison/division operator, or an indicator identifier followed by-# digits (SMA/EMA/…/VWAP + digits; MA for the Chinese MA20 convention) —-# turns the number into an operand of the formula, not a claimed value;-# * an observation binder after that marker ("was", "at", 报收/收于/收报/收在)-# re-attaches the number to the price word, so "close above SMA50 and was-# 2500" stays a claim while "close/SMA50 > 1" claims nothing.-#-# This replaces the per-phrasing denylist (a signal-value mask, an indicator--# connective mask, …) with one syntactic distinction; the catalogue of-# phrasings can never close, a closed marker set can.-_FORMULA_MARKER_RE = re.compile(- r"(?:>=|<=|≥|≤|>|<|/)"- r"|\b(?:SMA|EMA|WMA|DMA|MA|RSI|MACD|ATR|ADX|CCI|OBV|KDJ|BOLL|VWAP)\d+\b",- re.IGNORECASE | re.ASCII,-)---_OBSERVATION_BINDER_RE = re.compile(- r"\b(?:was|were|is|are|at)\b|(?:报收|收于|收报|收在)|==|=|≈",- re.IGNORECASE,-)---def _matches_any(raw: Any, values: Sequence[float], *, rel: float = 0.005) -> bool:- """Whether a measurement-shaped figure equals one of ``values``.-- Args:- raw: A figure as ``_measure_numbers`` returns it ("1.136", "5.26%").- values: Numeric values to match against.- rel: Relative tolerance, absolute floor 1e-9.-- Returns:- True when the parsed figure matches any value.- """- try:- number = float(str(raw).strip().rstrip("%%").replace(",", ""))- except ValueError:- return False- return any(abs(number - value) <= max(abs(value) * rel, 1e-9) for value in values)---def _figure_reads_as_a_price(text: str, figure: str) -> bool:- """Whether ``figure`` is written as a price somewhere in ``text``.-- A price word ahead of it in the clause, a currency symbol in front of it,- or a currency/unit token glued behind it. Any one of the three is the- ordinary way an answer quotes a price, and none of them is how a metric- figure is written.-- Args:- text: The clause or cell the figure appears in.- figure: The figure exactly as it was written.-- Returns:- True when at least one occurrence reads as a price.- """- for match in re.finditer(re.escape(figure), text):- if _UNIT_TOKEN_AFTER_RE.match(text, match.end()):- return True- if _CURRENCY_BEFORE_RE.search(text[: match.start()]):- return True- if _PRICE_CONTEXT_RE.search(text[: match.start()]):- return True- return False---def _labels_its_result_observed(text: str, formula_start: int) -> bool:- """Whether a market-print word to the left CLAIMS the formula's result.-- The distinguisher is a result separator between the price word and the- formula's first operand. "收盘价 = 1.171 × 0.80" reads "the close IS this- expression" — the equation's subject is an observation, so its result is- a fabricated print. "基于收盘价 1.171 × 0.97 = 1.136" reads "starting from- the observed close" — the word labels an OPERAND, and the result is the- entry price the answer proposes, which is the shape the correction prompt- asks the model to write.-- Args:- text: The clause the formula was found in.- formula_start: Where the formula's arithmetic run starts in it.-- Returns:- True when the formula's result is claimed to be an observed print.- """- last: re.Match[str] | None = None- for match in _OBSERVED_PRICE_WORD_RE.finditer(text[:formula_start]):- last = match- if last is None:- return False- return bool(_RESULT_SEPARATOR_RE.search(text[last.end() : formula_start]))---_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", "日期", "交易日", "时间"}---# A price word that asserts the figure is a MARKET PRINT — an OHLC field or a-# spot quote. Such a figure is an observation, and an observation is never-# something a formula produces: "2026-06-23 收盘价 = 1.171 × 0.80 = 0.937"-# is arithmetic whose result is claimed to be a close the ledger holds as-# 1.137, and the bare-equation derivation exemption released it. Only the-# formula's OPERANDS stay exempt under such a label; see-# ``_labels_its_result_observed``.-#-# The OHLC half is DERIVED from ``_TABLE_FIELD_ALIASES``, which is the table-# path's own source of truth and already carries both scripts — the previous-# hand-written prose list held "closing price" but not "closed at", and-# "收盘价" but not "收盘为". The four bare English words are dropped: "open" is-# a verb, "high"/"low" are adjectives, and "close" only counts when it is not-# "close to". The spot half has no table equivalent and is written out.-_OHLC_PROSE_WORDS = sorted(- (alias for alias in _TABLE_FIELD_ALIASES if alias not in {"open", "high", "low", "close"}),- key=len,- reverse=True,-)---_OBSERVED_PRICE_WORD_RE = re.compile(- "(?:"- # ASCII aliases take word boundaries so "closing" does not match inside- # "disclosing"; the CJK ones are written without spaces and must not.- + "|".join(- (r"\b" + re.escape(word) + r"\b") if word.isascii() else re.escape(word)- for word in _OHLC_PROSE_WORDS- )- + r"|\b(?:closed|opened|settled|fixed|traded|quoted|last[- ]traded|changed hands)\s+at\b"- + r"|\bthe\s+(?:close|open|high|low)\s+(?:was|is)\b"- + r"|\b(?:last|previous|prior|session|intraday|day's|today's)\s+(?:close|open|high|low)\b"- + r"|\bclose\b(?!\s+to\b)"- + r"|\b(?:current|latest|market|spot|share|last(?: traded)?)\s+price\b"- + r"|\bthe\s+quote\b|\btrad(?:es|ing)\s+at\b|\bchanges?\s+hands\s+at\b"- + r"|收盘于|收盘为|收报|报收|收于|现价|最新价|最新成交价|成交价|市价|报价|现报|股价"- + ")",- re.IGNORECASE,-)--# A loader's id is ASCII, but the answer follows the user's language, so a# Chinese report names the same provider in Chinese. Demanding the ASCII id-# verbatim rejected correct prose: an answer reading "数据来源:腾讯财经" was-# reported as ``data_source_not_surfaced`` against evidence sourced from-# ``tencent``, and no rewrite short of writing the English word could pass.+# verbatim rejected correct prose: "数据来源:腾讯财经" was reported as+# ``data_source_not_surfaced`` against evidence sourced from ``tencent``._SOURCE_ALIASES = {"akshare": ("akshare", "ak share"),"baostock": ("baostock",),@@ -707,13 +72,6 @@ _SOURCE_ALIASES = {}-# "元" is how a Chinese answer writes a CNY quote, but it is also the tail of-# 港元/美元/日元, so accepting it unguarded would let an answer about a Hong Kong-# listing satisfy a CNY requirement. It counts only when no other currency's-# character owns it.-_BARE_YUAN_RE = re.compile(r"(?<![港美日欧韩台新加澳])元")--_CURRENCY_ALIASES = {"USD": ("usd", "us$", "美元", "美金"),# ¥ is how a model actually writes a CNY quote. It is the yen sign too, but@@ -727,20 +85,151 @@ _CURRENCY_ALIASES = {}-_SYMBOL_HEADERS = {"symbol", "ticker", "code", "标的", "代码", "证券代码"}+# "元" is how a Chinese answer writes a CNY quote, but it is also the tail of+# 港元/美元/日元, so accepting it unguarded would let an answer about a Hong+# Kong listing satisfy a CNY requirement. It counts only when no other+# currency's character owns it.+_OTHER_CURRENCY_PREFIXES = "港美日欧韩台新加澳"+++#: Relative band a value must fall in to count as matching evidence.+_TOLERANCE = 0.005@dataclass(frozen=True)class ValidationResult:- """Final-answer grounding decision."""+ """Final-answer grounding decision.++ ``released_text`` is the draft with its declaration block removed: the+ block is a contract between the model and this gate, not part of the+ answer, and it never reaches the user.+ """valid: boolissues: list[dict[str, Any]] = field(default_factory=list)+ released_text: str = ""+++def _close(value: float, target: float) -> bool:+ """Whether two values agree inside the evidence tolerance."""+ return abs(value - target) <= max(abs(target) * _TOLERANCE, 1e-9)+++def _close_any(value: float, targets: Iterable[float]) -> bool:+ """Whether ``value`` agrees with any of ``targets``."""+ return any(_close(value, target) for target in targets)+++def _written_half_unit(text: str) -> float:+ """Half a unit of the last digit a figure was WRITTEN with.++ "约 37%" for a derived 36.75% asserts that the value rounds to 37, and a+ flat relative band rejects every integer-percent rounding a model makes.+ """+ body = text.strip().rstrip("%%").strip()+ decimals = len(body.split(".", 1)[1]) if "." in body else 0+ return 0.5 * 10.0 ** (-decimals)+++def _evaluate_formula(expression: str) -> tuple[float, list[float]] | None:+ """Evaluate a numeric ``+ - * /`` expression without executing code.++ Args:+ expression: An arithmetic run, possibly using ``× ÷ −`` and commas.++ Returns:+ ``(result, operands)``, or None when the run is not a well-formed+ expression over at least two numeric operands.+ """+ normalized = (+ expression.replace("×", "*")+ .replace("✕", "*")+ .replace("÷", "/")+ .replace("−", "-")+ .replace("–", "-")+ .replace("(", "(")+ .replace(")", ")")+ .replace(",", "")+ .replace("%", "")+ .strip()+ )+ if not normalized:+ return None+ try:+ tree = ast.parse(normalized, mode="eval")+ except (SyntaxError, ValueError, MemoryError, RecursionError):+ 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 = visit(node.left)+ right = visit(node.right)+ if isinstance(node.op, ast.Add):+ return left + right+ if isinstance(node.op, ast.Sub):+ return left - right+ if isinstance(node.op, ast.Mult):+ return left * right+ if right == 0:+ raise ValueError("division by zero")+ return left / right+ 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+++def _formula_in_note(note: str) -> tuple[float, list[float]] | None:+ """Find the derivation a note states.++ A note is written either as the expression alone ("0.666 × 0.97") or as+ the expression together with its own result ("0.666 × 0.97 = 0.646"). The+ whole note is tried first, then each segment between result separators.+ Those separators are punctuation, not vocabulary, which is why the English+ and Chinese spellings of the same derivation now get the same verdict.++ Args:+ note: The declaration's free-text note.++ Returns:+ ``(result, operands)`` for the first parseable segment, or None.+ """+ candidates = [note]+ parts = [note]+ for separator in ("≈", "≒", "=", "=", "→", "->"):+ parts = [piece for part in parts for piece in part.split(separator)]+ candidates.extend(part for part in parts if part.strip())+ for candidate in candidates:+ evaluated = _evaluate_formula(candidate)+ if evaluated is not None:+ return evaluated+ return Noneclass _PolicyMixin:"""Policy behaviour of :class:`GroundingLedger`."""+ # ------------------------------------------------------------------ #+ # identity+ # ------------------------------------------------------------------ #+def _validate_identity(self, content: str) -> list[dict[str, Any]]:"""Validate aggregate state and listed/private contradictions."""issues: list[dict[str, Any]] = []@@ -750,17 +239,11 @@ class _PolicyMixin:# ``self._identities`` — a run that never named an instrument has no# identity to get wrong. The trigger phrase is matched against the user# message, so "什么是市盈率估值法?" set identity_required and then failed- # every draft it could ever produce, including the honest answer. This- # relaxation invents no licence to guess: a figure still has to survive- # ``_validate_price_claims``, and a figure attached to a symbol no tool- # handled still has to survive ``_validate_unsourced_symbols``.+ # every draft it could ever produce, including the honest answer.#- # ``ambiguous`` is deliberately absent. A shortlist is an answer, which- # is why ``_RESOLUTION_INCOMPLETE_STATUSES`` already lets workflow- # selection proceed on it (#955) — but the final answer stayed blocked,- # so a screening run loaded its skill and was then refused a conclusion.- # Consumers remain blocked on ambiguous in ``authorize_tool_call``, so- # such a run still cannot fetch a quote to misattribute.+ # ``ambiguous`` is deliberately absent. A shortlist is an answer, and+ # consumers stay blocked on it in ``authorize_tool_call``, so such a+ # run still cannot fetch a quote to misattribute.if (self._identity_requiredand self._identities@@ -770,7 +253,15 @@ class _PolicyMixin:{"code": "identity_not_locked","status": status,- "message": f"Instrument identity is {status}; a final market conclusion requires locked identity.",+ "value": None,+ "role": None,+ "span": None,+ "symbol": None,+ "reason": "identity_not_locked",+ "message": (+ f"Instrument identity is {status}; a final market conclusion "+ "requires locked identity."+ ),})listed = [@@ -785,765 +276,644 @@ class _PolicyMixin:{"code": "listed_identity_relabelled_private","symbols": symbols,+ "value": None,+ "role": None,+ "span": None,+ "symbol": None,+ "reason": "listed_relabelled_private","message": (- f"Locked listed identity {', '.join(symbols)} was relabelled as private/unlisted "- "without a conflicting resolver result."+ f"Locked listed identity {', '.join(symbols)} was relabelled as "+ "private/unlisted without a conflicting resolver result."),})return issues- def _validate_unsourced_symbols(self, content: str) -> list[dict[str, Any]]:- """Reject figures attached to an instrument no tool in this run handled.-- This is the mechanically decidable half of "what the tools did not- return, you do not supply" (#886/#887). Naming a symbol is left alone —- prose may legitimately mention an index or a peer — but the moment a- clause pairs an unhandled canonical symbol with a figure, the figure has- no possible origin other than model memory.-- Args:- content: Candidate assistant answer.+ # ------------------------------------------------------------------ #+ # figures+ # ------------------------------------------------------------------ #- Returns:- One issue per distinct unsourced symbol carrying figures.- """- issues: list[dict[str, Any]] = []- reported: set[str] = set()- for line, line_offset in _lines_with_offsets(content):- for segment, span_start, span_end in _clause_spans(line, line_offset):- unknown = sorted(- symbol- for symbol in _scan_symbols(segment) - self._session_symbols - reported- if symbol.rsplit(".", 1)[0] not in self._session_symbol_roots- )- if not unknown or not self._numbers_without_dates_or_percent(segment):- continue- # Accept figures that are attributed to an external source- # (e.g., "The paper reports a Sharpe ratio of 1.8.") rather- # than model memory. Scoped to the clause: a line-level check- # would let a citation in one clause launder an invented- # sibling metric in the next.- if _ATTRIBUTION_RE.search(segment):- continue- for symbol in unknown:- reported.add(symbol)- issues.append(- {- "code": "unsourced_symbol_figures",- "symbol": symbol,- "claim": segment.strip()[:200],- "span": [span_start, span_end],- "message": (- f"No tool call in this session passed in or returned {symbol}, "- "yet the answer attaches figures to it. Retrieve it, or report "- "it as not retrieved."- ),- }- )- return issues-- def _validate_analysis_claims(self, content: str) -> list[dict[str, Any]]:- """Reject backtest/analysis metrics with no kind-scoped evidence.-- #1336: after failed or deduplicated market-data calls the model may- still present return-volatility / drawdown / probability figures as- measured facts. A metric figure is legitimate only when the run's- evidence contains the same *kind* of figure — recorded from a- completed analysis result (backtest artifacts, factor/shadow/quantlib- output) or from any successful tool's numeric output (e.g.- ``portfolio_risk_xray``, flattened into ``_evidence``). Kind scoping- is what keeps an observed price from standing in for an invented- volatility figure. Definitional prose ("夏普比率大于 1.0 通常被认为- 较好"), explicitly forward-looking forecasts, and categorical- historical-window facts without any window-producing analysis are- handled separately here.+ def _validate_figures(+ self,+ content: str,+ block: FiguresBlock,+ figures: Sequence[Figure],+ ) -> list[dict[str, Any]]:+ """Check every measurement-shaped number against its declared role.Args:- content: Candidate assistant answer.+ content: The candidate answer.+ block: Its parsed declaration block.+ figures: Every number located in its prose.Returns:- One issue per metric-bearing clause or table cell.+ One issue per figure that its role does not survive, plus one per+ malformed declaration line and the provenance findings."""- issues: list[dict[str, Any]] = []+ issues: list[dict[str, Any]] = [+ {+ "code": "figures_block_malformed",+ "line": line_no,+ "claim": raw,+ "value": None,+ "role": None,+ "span": None,+ "symbol": None,+ "reason": "unparseable_declaration",+ "message": (+ f"figures block line {line_no} could not be read as "+ "`value | role | note | ref`: " + raw+ ),+ }+ for line_no, raw in block.malformed+ ]+ records = self._comparable_price_records()+ document_symbol = self._symbol_for_claim(content, records)positions = _lines_with_offsets(content)- lines = [line for line, _ in positions]- consumed: set[int] = set()- price_records = self._comparable_price_records()- for header, rows, row_indices in self._pipe_tables(lines):- consumed.update(row_indices)- columns = [- (cell, _metric_kind_for_text(cell), bool(_FORECAST_FRAME_RE.search(cell)))- for cell in header- ]- has_kind_header = any(kind for _, kind, _ in columns)- for row, row_line_index in zip(rows, row_indices):- row_start = positions[row_line_index][1]- row_span = (row_start, row_start + len(lines[row_line_index]))- cells = row + [""] * (len(columns) - len(row))- if not has_kind_header:- # Generic header ("指标 | 数值", "Metric | Value"): a cell- # naming a metric kind is a row LABEL and claims exactly- # one adjacent value cell (right first — "label, value"- # order — then left, for value-first layouts). Validating- # every cell after the label would grab annotation columns- # ("备注 | 较去年提升 2%") that prose never attributes to- # the label; parity with the prose verdict is the bar.- row_kinds = [- (index, _metric_kind_for_text(cell))- for index, cell in enumerate(cells)- if _metric_kind_for_text(cell) is not None- ]- claimed: set[int] = set()- for label_index, row_kind in row_kinds:- # A label cell that smuggles its own measurement- # ("| 年化收益率 18.2% | - |") is prose-identical to- # "年化收益率为 18.2%" — validate the label's own- # numbers against its kind too.- self._check_table_cell(- cells[label_index], row_kind, cells[label_index], issues,- row_span, price_records,- )- # A forecast frame in the LABEL ("| 预计夏普比率 | 1.2 |")- # frames the claimed value clause-wide, exactly as prose- # exempts the whole clause and the metric-header path- # skips a forecast-framed column. Without this the generic- # path is stricter than both of its siblings.- label_is_forecast = bool(- _FORECAST_FRAME_RE.search(cells[label_index])- )- for value_index in (label_index + 1, label_index - 1):- if (- 0 <= value_index < len(cells)- and value_index not in claimed- and _metric_kind_for_text(cells[value_index]) is None- ):- claimed.add(value_index)- if label_is_forecast:- continue- self._check_table_cell(- cells[label_index], row_kind, cells[value_index], issues,- row_span, price_records,- )- continue- for (cell_text, kind, header_forecast), cell in zip(columns, cells):- if kind is None or header_forecast:- continue- self._check_table_cell(- cell_text, kind, cell, issues, row_span, price_records- )- for index, (line, line_offset) in enumerate(positions):- if index in consumed:+ line_symbols = [+ self._symbol_for_claim(line, records) for line, _ in positions+ ]+ declared_observed = {+ declaration.value+ for declaration in block.declarations+ if declaration.role == "observed"+ }+ checked_price = False+ for figure in figures:+ if figure.shape != "measured":continue- line_symbol = self._symbol_for_claim(line, price_records)- for segment, span_start, span_end in _clause_spans(line, line_offset):- if _CATEGORICAL_WINDOW_RE.search(segment) and _NUMBER_RE.search(segment):- if not any(- entry.get("tool") in _ANALYSIS_WINDOW_TOOLS- for entry in self._analysis_completed- ):- match = _NUMBER_RE.search(segment)- issues.append(- {- "code": "analysis_claim_unavailable",- "claim": segment.strip()[:200],- "span": [span_start, span_end],- "value": match.group(0) if match else None,- "message": (- "No backtest completed in this session, yet the "- "answer states a categorical historical-window "- "fact. Mark the analysis as incomplete and omit "- "this claim."- ),- }- )- continue- if _DEFINITION_FRAME_RE.search(segment):- continue- # Attributed figures ("The paper reports a Sharpe of 1.8",- # or the marker in a neighbouring clause: "据研究显示,策略- # 年化收益 18.2%") are citations, not invented measurements- # — skip the gate.- if _ATTRIBUTION_RE.search(segment):- continue- values = self._measure_numbers(segment)- if not values:- continue- if not _ANALYSIS_METRIC_RE.search(segment):- continue- if _FORECAST_FRAME_RE.search(segment):- continue- kind = _metric_kind_for_text(segment)- unsupported = [- value- for value in values- if not self._analysis_value_observed(value, kind)- and not self._is_observed_price_figure(- value, price_records, line_symbol, segment- )- ]- if not unsupported:- continue- # A return figure may be arithmetic on sourced inputs rather- # than an invented backtest metric (#1338 review): an explicit- # formula anchored to observed values, or growth between two- # observed endpoints stated in the same line.- # A drawdown stated against an observed high ("较 5 月高点- # 1.053 元已回撤约 37%") is the same arithmetic on the same- # sourced endpoints, and was rejected as an invented backtest- # metric because only the return branch carried the exemption- # (owner-forwarded 159516.SZ run, 2026-09-09). Drawdown is- # compared by magnitude, as ``_analysis_value_observed`` does.- # Neither exemption is available to a STRATEGY-subject- # metric. A strategy's max drawdown is a property of an- # equity curve, and no arithmetic on two observed prints of- # the instrument is that curve: "回测显示该策略最大回撤 5.9%- # (从 1.180 跌至 1.110)" was released as grounded with no- # backtest in the session at all. Such a figure keeps the- # unchanged backtest-evidence requirement above.- if kind in {"return", "drawdown"} and not _STRATEGY_SUBJECT_RE.search(- segment- ):- if _DERIVATION_RE.search(segment):- # As in the price path: only the values the formula- # justifies are exempt, not every figure beside them.- # Scoped to the CLAUSE, which is where the claim- # itself was measured — a line-scoped exemption let- # "基于 40 × 1.171 = 46.84 计算,策略最大回撤 40%"- # ground the metric in the next clause.- justified = self._derivation_justified_values(- segment, price_records, line_symbol- )- unsupported = [- value- for value in unsupported- if not _matches_any(value, justified)- ]- if not unsupported:- continue- # The operand scan stays LINE-scoped: the endpoints of a- # move are routinely written in two clauses ("当前 0.666- # 元,较 5 月高点 1.053 元已回撤约 37%").- operands = self._observed_operands_in_line(- line, price_records, line_symbol- )- if len(operands) >= 2:- derived = self._returns_derived_from_observed(- unsupported,- price_records,- line_symbol,- operands=operands,- magnitude=kind == "drawdown",- )- # The endpoints themselves are grounded by the same- # exemption: "较高点 1.180 元已回撤约 6%" states the- # observed high beside the ratio it derives.- unsupported = [- value- for value in unsupported- if value not in derived- and not (- not str(value).endswith(("%", "%"))- and _matches_any(value, operands, rel=1e-9)- )- ]- if not unsupported:- continue+ declaration = block.match(figure.value, figure.percent)+ if block.present and declaration is None:issues.append(- {- "code": "analysis_claim_unavailable",- "claim": segment.strip()[:200],- "span": [span_start, span_end],- "value": unsupported[0],- "kind": kind,- "message": (- "No supporting analysis evidence (a completed "- "backtest result or observed risk metric) exists for "- "this figure. Mark the analysis as incomplete and omit "- "these figures."- ),- }+ self._figure_issue(+ "figure_undeclared",+ figure,+ None,+ None,+ "undeclared",+ "is not declared in the figures block; declare it as "+ "observed / derived / proposed / cited / count, or remove it",+ ))+ continue+ role = declaration.role if declaration else "observed"+ symbol = self._figure_symbol(+ content, figure, declaration, line_symbols, document_symbol, records+ )+ if role == "count":+ continue+ if role == "cited":+ issues.extend(+ self._check_cited(figure, declaration, symbol, declared_observed)+ )+ continue+ checked_price = True+ if role == "derived":+ issues.extend(+ self._check_derived(figure, declaration, symbol, records)+ )+ continue+ if role == "proposed":+ issues.extend(+ self._check_proposed(figure, declaration, symbol, records)+ )+ continue+ issues.extend(self._check_observed(figure, declaration, symbol, records))+ market_records = self._price_records()+ if checked_price and market_records:+ issues.extend(self._validate_price_provenance(content, market_records))return issues- def _check_table_cell(+ @staticmethod+ def _figure_issue(+ code: str,+ figure: Figure,+ role: str | None,+ symbol: str | None,+ reason: str,+ message: str,+ **extra: Any,+ ) -> dict[str, Any]:+ """Build one figure-scoped issue.++ Every figure issue carries the same five fields — value, role, span,+ symbol and reason — so the correction prompt can name the exact number+ and the release path can cut exactly it.+ """+ issue = {+ "code": code,+ "value": figure.text,+ "role": role,+ "span": [figure.start, figure.end],+ "symbol": symbol,+ "reason": reason,+ "claim": figure.text,+ "message": f"{figure.text} {message}.",+ }+ issue.update(extra)+ return issue++ def _figure_symbol(self,- label: str,- kind: str | None,- cell: str,- issues: list[dict[str, Any]],- span: tuple[int, int] | None = None,- price_records: Sequence[EvidenceRecord] = (),- ) -> None:- """Reject one table cell whose numeric value is an unsupported metric.-- Shared by the metric-headed and generic-header (label, value) table- paths. A forecast or definitional annotation exempts only that cell.+ content: str,+ figure: Figure,+ declaration: Declaration | None,+ line_symbols: Sequence[str | None],+ document_symbol: str | None,+ records: Sequence[EvidenceRecord],+ ) -> str | None:+ """Resolve which instrument a figure is about (spec §4 order).- Args:- label: The metric label the value is attached to (header cell or- row's first cell), for the issue claim text.- kind: The resolved metric kind, already derived from ``label``.- cell: One value cell to validate.- issues: Accumulator for ``analysis_claim_unavailable`` issues.- span: ``(start, end)`` of the table ROW inside the validated- answer. The claim text is the human-readable ``label: cell``,- which is not a substring of the draft ("| 最大回撤 | 12% |"),- so without the span the release path could never locate a- metric table and every metrics report fell back to the canned- refusal.- price_records: Comparable observed price evidence, so a cell that- merely restates observed closes ("| 峰值→当前 | 0.997 → 0.605 |")- is not reported as an invented drawdown figure and then cut- out of the released answer. Same rule as the prose path.+ The declaration's own ``ref``/``note`` wins, then the table row's+ symbol column, then the one canonical evidence symbol on the figure's+ line, then the one canonical evidence symbol in the whole answer."""- if kind is None:- return- values = _PolicyMixin._measure_numbers(cell)- if not values:- return- # A forecast annotation inside the cell ("预计 12.4%") exempts only- # that cell, never its neighbours.- if _FORECAST_FRAME_RE.search(cell) or _DEFINITION_FRAME_RE.search(cell):- return- # A cell RESTATING endpoints ("| 峰值→当前 | 1.180 → 1.110 |") is not- # a metric figure, and cutting it out of the released answer removed- # two correctly quoted closes. The restatement shape is what the- # exemption is for, so it needs the cell to hold a PAIR: a single- # number in a metric cell IS that metric's value, and exempting it on- # numeric equality alone released "| 夏普比率 | 1.171 |" as grounded- # because 1.171 happened to be an observed close. On a $12.50 stock- # the collision is "| 最大回撤 | 12.5 |".- unsupported = [- value- for value in values- if not self._analysis_value_observed(value, kind)- and not (- len(values) >= 2- and self._matches_observed_price(value, price_records, None)+ if declaration is not None:+ declared = self._symbol_for_claim(+ f"{declaration.ref} {declaration.note}", records)+ if declared:+ return declared+ if figure.symbol:+ normalized = _normalize_symbol(figure.symbol)+ if normalized:+ return normalized+ # Inside the figure's own segment first. A comparison report names both+ # instruments in its header and then writes about one of them, so the+ # LINE is too coarse an owner: 562500's moving average grounded a level+ # written under 600519 on the same line.+ left, right = segment_bounds(content, figure.start, figure.end)+ segment_symbol = self._symbol_for_claim(content[left:right], records)+ if segment_symbol:+ return segment_symbol+ if 0 <= figure.line < len(line_symbols) and line_symbols[figure.line]:+ return line_symbols[figure.line]+ return document_symbol++ # ------------------------------------------------------------------ #+ # evidence pools+ # ------------------------------------------------------------------ #++ def _referenced_values(self, ref: str) -> list[float] | None:+ """Every observed value one tool call produced, or None when unknown.++ A declaration whose ``ref`` names a call id says "this number came out+ of THAT call". That is the tightest scoping available and the only one+ that can ground a figure the price pool cannot hold — a filing's+ revenue, a factor's IC, a volume.+ """+ key = (ref or "").strip()+ if not key:+ return None+ values = [+ float(record.value)+ for record in self._evidence+ if record.call_id == key+ and record.status == "observed"+ and record.value is not None]- if not unsupported:- return- issues.append(- {- "code": "analysis_claim_unavailable",- "claim": f"{label}: {cell}"[:200],- "span": list(span) if span else None,- "value": unsupported[0],- "kind": kind,- "message": (- "No supporting analysis evidence (a completed "- "backtest result or observed risk metric) exists "- "for this figure. Mark the analysis as incomplete "- "and omit these figures."- ),- }+ values.extend(+ float(entry["value"])+ for entry in self._analysis_metrics+ if entry.get("call_id") == key and entry.get("value") is not None)+ return values or None- @staticmethod- def _measure_numbers(text: str) -> list[str]:- """Extract measurement-shaped numbers (decimal or percent) from a claim."""- masked = _LOCALIZED_DATE_RE.sub(" ", text)- masked = _DATE_RE.sub(" ", masked)- masked = _SHORT_DATE_RE.sub(" ", masked)- masked = _DASH_DATE_RE.sub(" ", masked)+ def _price_pool(+ self,+ symbol: str | None,+ records: Sequence[EvidenceRecord],+ *,+ column: str | None = None,+ date: str | None = None,+ ) -> list[float]:+ """Observed price values a figure may be compared against.++ Filtered by symbol when one was resolved; further narrowed to the OHLC+ field and trade date when the figure sits under those table headers,+ which is the table semantics §4 preserves.+ """+ candidates = list(records)+ if symbol:+ candidates = [record for record in candidates if record.symbol == symbol]+ elif len({record.symbol for record in records if record.symbol}) > 1:+ # An indicator reading is symbol-bound in a way an OHLC bar's union+ # is not. With evidence for two instruments and a figure attributed+ # to neither, 562500's sma_20 grounded a level written beside+ # 600519.SH; the union was argued for observed quotes, not for a+ # level attached to one symbol.+ candidates = [record for record in candidates if record.field != "indicator"]+ if column:+ candidates = [record for record in candidates if record.field == column]+ if date:+ candidates = [+ record+ for record in candidates+ if record.timestamp+ and _timestamp_matches_claim_date(record.timestamp, date)+ ]+ return [float(record.value) for record in candidates if record.value is not None]++ def _row_pool(self, symbol: str | None) -> list[float]:+ """Non-price numbers a market-data ROW carried (volume, turnover, …).++ A row is one observation, and a report quoting its volume beside its+ close is quoting the same tool result. Only ``get_market_data`` rows+ and the run-dir CSVs the bash escape hatch writes are included, so a+ generic tool's hundreds of numeric leaves never widen the price check.+ """return [- match.group(0).replace(" ", "").replace(",", "")- for match in _MEASURE_NUMBER_RE.finditer(masked)+ float(record.value)+ for record in self._evidence+ if record.status == "observed"+ and record.value is not None+ and record.tool in {"get_market_data", "bash"}+ and (not symbol or record.symbol == symbol)]- @staticmethod- def _pipe_tables(- lines: Sequence[str],- ) -> list[tuple[list[str], list[list[str]], list[int]]]:- """Yield (header cells, row cells, row line indices) per pipe table."""- tables: list[tuple[list[str], list[list[str]], list[int]]] = []- index = 0- while index < len(lines):- if lines[index].count("|") < 2:- index += 1- continue- block_start = index- block: list[str] = []- while index < len(lines) and lines[index].count("|") >= 2:- block.append(lines[index])- index += 1- rows: list[list[str]] = []- row_indices: list[int] = []- for offset, block_line in enumerate(block[1:], start=1):- cells = _PolicyMixin._table_cells(block_line)- if not cells or all(- _TABLE_SEPARATOR_RE.fullmatch(cell.strip()) for cell in cells- ):- continue- rows.append(cells)- row_indices.append(block_start + offset)- tables.append((_PolicyMixin._table_cells(block[0]), rows, row_indices))- return tables-- def _analysis_value_observed(self, raw: str, kind: str | None) -> bool:- """Return True when a claim measurement matches kind-scoped evidence.-- Tools disagree on scale: ``compute_risk_xray`` returns fractions- (annualized_vol 0.182, max_drawdown -0.094) while answers quote- percents (18.2%, -9.4%). Try both the value and its percent scaling- so an observed 0.182 grounds an 18.2% claim and vice versa. Drawdown- sign conventions disagree too (positive vs negative fraction), so- magnitude is compared for that kind. Only evidence of the claim's own- kind counts: an observed price never grounds a volatility figure.+ def _metric_pool(self, symbol: str | None) -> list[float]:+ """Analysis/risk metric values the run actually recorded.++ Two sources, both keyed on TOOL FIELD NAMES: metrics parsed from a+ completed analysis result, and observed leaves whose path maps to a+ metric kind (``annualized_vol``, ``max_drawdown``, …)."""- try:- value = float(raw.replace("%", "").replace("%", "").replace(",", ""))- except ValueError:- return True- observed: list[float] = []- for record in self._analysis_metrics:- if record.get("metric") == kind and record.get("value") is not None:- observed.append(float(record["value"]))- for record in self._evidence:- if record.status != "observed" or record.value is None:- continue- if _metric_kind_for_path(record.field) != kind:- continue- observed.append(float(record.value))- candidates = {value, value / 100.0}- if kind == "drawdown":- candidates |= {abs(value), abs(value) / 100.0}+ values = [+ float(entry["value"])+ for entry in self._analysis_metrics+ if entry.get("value") is not None+ ]+ values.extend(+ float(record.value)+ for record in self._evidence+ if record.status == "observed"+ and record.value is not None+ and _metric_kind_for_path(record.field) is not None+ and (not symbol or not record.symbol or record.symbol == symbol)+ )+ return values- def close(candidate: float, item: float) -> bool:- return abs(candidate - item) <= max(abs(item) * 0.005, 1e-9)+ def _matches_evidence(+ self,+ figure: Figure,+ direct: Sequence[float],+ scaled: Sequence[float],+ ) -> bool:+ """Whether a figure equals evidence, at its own scale or a metric's.++ ``direct`` is compared literally; the caller decides what may go in it,+ and for a percent-written figure that is nothing at all — an OHLC close+ is never a ratio. ``scaled`` absorbs the two conventions tools and+ answers disagree on: fraction vs percent (0.182 vs 18.2%), and the sign+ a fall is written with (a drawdown is recorded as -0.094 and quoted as+ 9.4%).+ """+ if _close_any(figure.value, direct):+ return True+ candidates = {abs(figure.value), abs(figure.value) / 100.0}+ magnitudes = [abs(target) for target in scaled]+ return any(_close_any(candidate, magnitudes) for candidate in candidates)- return any(close(candidate, item) for candidate in candidates for item in observed)+ # ------------------------------------------------------------------ #+ # roles+ # ------------------------------------------------------------------ #- def _is_observed_price_figure(+ def _check_observed(self,- raw: str,+ figure: Figure,+ declaration: Declaration | None,+ symbol: str | None,records: Sequence[EvidenceRecord],+ ) -> list[dict[str, Any]]:+ """An observed figure must appear in the evidence it claims to quote."""+ referenced = (+ self._referenced_values(declaration.ref) if declaration else None+ )+ if referenced is not None:+ if self._matches_evidence(figure, referenced, referenced):+ return []+ return [+ self._figure_issue(+ "numeric_claim_conflict",+ figure,+ "observed",+ symbol,+ "not_in_referenced_call",+ f"is declared observed from {declaration.ref}, whose results do "+ "not contain it",+ source_tool_call_ids=[declaration.ref],+ )+ ]+ prices = self._price_pool(+ symbol, records, column=figure.column, date=figure.date+ )+ if figure.percent:+ # A percent-written figure is a ratio, and a price or a volume is+ # not, so no amount of price evidence may answer one.+ direct: list[float] = []+ elif figure.column:+ direct = list(prices)+ else:+ direct = list(prices) + self._row_pool(symbol)+ scaled = [] if figure.column else self._metric_pool(symbol)+ if not direct and not scaled:+ return [+ self._figure_issue(+ "numeric_claim_unavailable",+ figure,+ "observed",+ symbol,+ "no_evidence",+ "is declared observed but this session holds no matching tool "+ "evidence to check it against",+ field=figure.column,+ date=figure.date,+ )+ ]+ if self._matches_evidence(figure, direct, scaled):+ return []+ observed = sorted(direct or scaled)+ return [+ self._figure_issue(+ "numeric_claim_conflict",+ figure,+ "observed",+ symbol,+ "value_mismatch",+ "is declared observed but conflicts with the "+ f"{figure.column or 'observed'} evidence "+ f"{observed[0]:g}–{observed[-1]:g}",+ field=figure.column,+ date=figure.date,+ observed_min=observed[0],+ observed_max=observed[-1],+ )+ ]++ def _derivation(+ self,+ declaration: Declaration | None,symbol: str | None,- text: str,- ) -> bool:- """Whether a figure in an analysis clause is literally an observed price.-- ``_validate_analysis_claims`` reports the FIRST unmatched number in a- clause that mentions a metric, and an observed close sharing a clause- with an ungrounded metric was that number: "最新收盘 1.171 元且策略最大- 回撤 12%" reported 1.171, so the release path cut the correctly quoted- close and footnoted it as unverifiable. A value the ledger observed is- not an invented backtest metric — its own check is- ``_compare_price_claim``, which compares any price-word figure against- observed OHLC at the 0.5% band. A percent-written figure is never- exempted here, so every drawdown / return / volatility / win-rate- percentage keeps the full analysis check.-- Numeric equality is not enough on its own. A run holds hundreds of- observed OHLC values spanning the instrument's price range, so ANY- percent-free metric written in that range collides with one:- "策略夏普比率 1.171" and "策略最大回撤 1.171" were released as grounded- against an observed close, with no backtest in the session. The figure- must also be WRITTEN as a price — a price word ahead of it or a- currency unit glued to it — which is exactly the shape that has its- own check in ``_compare_price_claim``.+ records: Sequence[EvidenceRecord],+ ) -> tuple[float, list[float]] | str | None:+ """Evaluate a declaration's note as an observation-anchored formula.- Args:- raw: A figure as ``_measure_numbers`` returns it.- records: Comparable observed price evidence.- symbol: Symbol resolved for the line, if any.- text: The clause the figure was written in.+ Returns the ``(result, operands)`` pair when the note is arithmetic+ over at least two operands, at least one of which the run observed;+ otherwise the reason it is not.+ """+ if declaration is None or not declaration.note.strip():+ return "no_formula"+ evaluated = _formula_in_note(declaration.note)+ if evaluated is None:+ return "formula_not_evaluable"+ result, operands = evaluated+ if not symbol and len({record.symbol for record in records if record.symbol}) > 1:+ # A comparison run holds two instruments' bars, and the expensive+ # one's close makes any arithmetic "anchored" no matter which+ # instrument the answer is about. Without a resolved symbol there+ # is nothing to anchor TO.+ return "no_symbol"+ anchors = (+ self._price_pool(symbol, records)+ + self._row_pool(symbol)+ + self._metric_pool(symbol)+ )+ referenced = self._referenced_values(declaration.ref)+ if referenced:+ anchors.extend(referenced)+ if not anchors:+ return "no_evidence"+ if not any(_close_any(operand, anchors) for operand in operands):+ return "formula_not_anchored"+ return result, operands- Returns:- True when the figure is written without a percent sign, reads as a- price in its clause, and equals an observed price value for this- symbol.+ @staticmethod+ def _result_matches(declaration: Declaration, result: float) -> bool:+ """Whether a formula's result is the value the declaration states.++ The band is half a unit of the last digit the value was WRITTEN with,+ because "约 37%" for a derived 36.75% asserts that it rounds to 37 and+ a flat relative band rejects every rounding a model makes.++ A figure carrying "%" is percentage points and is compared ONLY+ against the derivation in those units. Running it against the fraction+ too gave an integer percent a half-unit band of 0.5 in FRACTION units+ — fifty percentage points — and "区间收益率约 0%" validated against a+ real +58% move. A figure written without "%" is genuinely ambiguous+ and is tried both ways.++ Magnitudes are compared because the note for a fall is written both as+ ``(low − high) / high`` and as the drop it produces; the note itself is+ what states which subtraction was taken."""- figure = str(raw).strip()- if not _figure_reads_as_a_price(text, figure):- return False- return self._matches_observed_price(figure, records, symbol)+ half_unit = _written_half_unit(declaration.value_text)+ targets = (+ {result * 100.0} if declaration.percent else {result, result * 100.0}+ )+ value = abs(declaration.value)+ return any(+ abs(value - abs(target)) <= max(abs(target) * _TOLERANCE, half_unit, 1e-9)+ for target in targets+ )- def _matches_observed_price(+ def _check_derived(self,- raw: str,- records: Sequence[EvidenceRecord],+ figure: Figure,+ declaration: Declaration | None,symbol: str | None,- ) -> bool:- """Whether a percent-free figure equals an observed price value.-- Args:- raw: A figure as ``_measure_numbers`` returns it.- records: Comparable observed price evidence.- symbol: Symbol resolved for the claim, if any.-- Returns:- True when the figure carries no percent sign and matches evidence.- """- figure = str(raw).strip()- if figure.endswith(("%", "%")):- return False- candidates = list(records)- if symbol:- candidates = [record for record in candidates if record.symbol == symbol]- observed = [- float(record.value) for record in candidates if record.value is not None+ records: Sequence[EvidenceRecord],+ ) -> list[dict[str, Any]]:+ """A derived figure must be the arithmetic its note states."""+ derivation = self._derivation(declaration, symbol, records)+ if isinstance(derivation, str):+ return [+ self._figure_issue(+ "numeric_claim_conflict"+ if derivation != "no_evidence"+ else "numeric_claim_unavailable",+ figure,+ "derived",+ symbol,+ derivation,+ "is declared derived, but its note is not arithmetic over at "+ "least two operands with one of them observed in this session",+ )+ ]+ result, _ = derivation+ if declaration is not None and self._result_matches(declaration, result):+ return []+ return [+ self._figure_issue(+ "numeric_claim_conflict",+ figure,+ "derived",+ symbol,+ "derivation_result_mismatch",+ f"is declared derived, but its own formula evaluates to {result:g}",+ )]- return _matches_any(figure, observed, rel=1e-9)- def _observed_operands_in_line(+ def _check_proposed(self,- line: str,- records: Sequence[EvidenceRecord],+ figure: Figure,+ declaration: Declaration | None,symbol: str | None,- ) -> list[float]:- """Observed values that literally appear as numbers in this clause.-- This is the structural half of the derivation exemption. Keying it on- a growth PHRASE ("从…到" / "from…to") made the gate stricter for every- wording the list happened to miss, which is the same per-language- drift that ``test_grounding_language_parity`` exists to stop: the- Chinese "第一日收盘 100.0 美元,第二日收盘 112.4 美元,收益率 12.4%"- states the identical derivation and was rejected. Requiring the- operands themselves to be present and sourced is language-independent- and strictly narrower than a phrase list, because a bare- "cumulative return of 12.4%" carries no operands at all.+ records: Sequence[EvidenceRecord],+ ) -> list[dict[str, Any]]:+ """A proposed level is derived, or inside the observed range.++ An entry, a target or a stop is a number the answer proposes rather+ than one it observed, so it cannot be required to equal a print. It+ can be required to be anchored: either the note derives it from what+ the run observed, or it lies between the lowest and highest price this+ session actually saw for the instrument. A level far outside that+ window is the invention this gate exists to stop."""- candidates = [record for record in records if record.value is not None]- if symbol:- candidates = [record for record in candidates if record.symbol == symbol]- observed = {float(record.value) for record in candidates}- if not observed:+ derivation = self._derivation(declaration, symbol, records)+ if (+ not isinstance(derivation, str)+ and declaration is not None+ and self._result_matches(declaration, derivation[0])+ ):return []- present: set[float] = set()- for raw in self._numbers_without_dates_or_percent(line):- try:- value = float(raw)- except (TypeError, ValueError):- continue- for candidate in observed:- if abs(value - candidate) <= max(abs(candidate) * 1e-9, 1e-9):- present.add(candidate)- return sorted(present)+ prices = self._price_pool(symbol, records)+ if not prices:+ return [+ self._figure_issue(+ "numeric_claim_unavailable",+ figure,+ "proposed",+ symbol,+ "no_evidence",+ "is a proposed level but this session observed no price for "+ "the instrument to anchor it to",+ )+ ]+ if not figure.percent and min(prices) <= figure.value <= max(prices):+ return []+ return [+ self._figure_issue(+ "numeric_claim_conflict",+ figure,+ "proposed",+ symbol,+ "outside_observed_range",+ "is a proposed level outside the observed range "+ f"{min(prices):g}–{max(prices):g} and its note derives no value",+ observed_min=min(prices),+ observed_max=max(prices),+ )+ ]- def _returns_derived_from_observed(+ def _check_cited(self,- claimed: Sequence[str],- records: Sequence[EvidenceRecord],+ figure: Figure,+ declaration: Declaration | None,symbol: str | None,- *,- operands: Sequence[float] | None = None,- magnitude: bool = False,- ) -> set[str]:- """Return the figures that equal growth between observed endpoints.-- #1338 review: "AAPL.US 从 2026-08-03 的 100.0 涨到 2026-09-02 的- 112.4,区间收益率为 12.4%" states arithmetic on sourced inputs. Only- a match against a pair of observed values grounds the figure; the- caller must already have verified the from/to frame, so a bare- unanchored return claim never reaches here.-- The match tolerates the precision the figure was WRITTEN at: "约 37%"- for a derived 36.75% asserts that the value rounds to 37, and the flat- ±0.5% relative band (±0.18 points there) rejected every integer-percent- rounding a model makes. Half a unit of the last written digit is the- bound, so "37%" accepts 36.5–37.5 and "36.8%" accepts 36.75–36.85; a- figure that is simply wrong ("40%") is as far away as before.-- Args:- claimed: Raw figures from the clause, as ``_measure_numbers`` returns them.- records: Observed evidence the operands may come from.- symbol: Symbol the clause names, if any.- operands: Observed values literally present in the clause.- magnitude: Compare absolute values (drawdown sign conventions differ).+ declared_observed: set[float],+ ) -> list[dict[str, Any]]:+ """A cited figure names its source and does not pose as a print.- Returns:- The subset of ``claimed`` the endpoint arithmetic justifies. It- used to be one bool for the whole clause, and the caller skipped- every figure beside the justified one: "at 0.666 down about 37%- from the 1.053 May high with a max drawdown of 60%" released the- 60% because the 37% checked out.+ The value is not checked — the run could never have observed a paper's+ Sharpe — so the only thing to enforce is that the citation is not used+ to launder an observation: the same number may not also be declared+ observed, and it may not sit in a table's OHLC column."""- if operands is not None:- observed = sorted(set(operands))- else:- candidates = [record for record in records if record.value is not None]- if symbol:- candidates = [- record for record in candidates if record.symbol == symbol- ]- observed = sorted({float(record.value) for record in candidates})- if len(observed) < 2:- return set()- values: list[tuple[str, float, float, bool]] = []- for raw in claimed:- raw_text = str(raw).strip()- text = raw_text.rstrip("%%")- try:- value = float(text)- except ValueError:- continue- decimals = len(text.split(".", 1)[1]) if "." in text else 0- values.append((str(raw), value, 0.5 * 10.0 ** (-decimals), raw_text != text))-- def close(value: float, derived: float, half_unit: float) -> bool:- if magnitude:- # A drawdown is a fall. Taking absolute values so "回撤 37%"- # can match a derived -36.75% also made the INVERSE- # derivation match: the same two endpoints read low→high give- # +58.11%, and "最大回撤约 58%" was released as grounded- # (attack2 probe, 2026-09-09). Only the falling direction may- # ground a drawdown.- if derived > 0:- return False- value, derived = abs(value), abs(derived)- return abs(value - derived) <= max(abs(derived) * 0.005, half_unit, 1e-9)-- justified: set[str] = set()- for base in observed:- for target in observed:- if target == base:- continue- derived = (target - base) / base- for raw, value, half_unit, is_percent in values:- # ``half_unit`` is half a unit of the last digit the figure- # was WRITTEN with, so it is only meaningful against the- # derivation expressed in those same units. A figure- # carrying "%" is percentage points and is compared only- # against ``derived * 100``; running it against the- # fraction too gave an integer percent a 0.5 band in- # FRACTION units — 50 percentage points — and "区间收益率- # 约 0%" validated against a real +58% move (attack4- # probe, 2026-09-09). A bare figure stays ambiguous and is- # tried both ways, each against its own consistent band.- # A bare figure always carries a decimal point —- # ``_MEASURE_NUMBER_RE`` extracts an integer only with a- # percent sign on it — so the fraction reading is never- # taken with a 0.5 half unit (which would be 50- # percentage points wide).- if not is_percent and close(value, derived, half_unit):- justified.add(raw)- if close(value, derived * 100.0, half_unit):- justified.add(raw)- return justified-- @staticmethod- def _occurrence_is_derived(- segment: str,- formulas: Sequence[tuple[int, int, list[float], float]],- value: float,- start: int,- end: int,- ) -> bool:- """Whether this figure, HERE, is part of a formula that justifies it.-- Two things are decided per occurrence rather than per value.+ if declaration is not None and not declaration.note.strip():+ return [+ self._figure_issue(+ "numeric_claim_conflict",+ figure,+ "cited",+ symbol,+ "citation_without_source",+ "is declared cited but names no source in its note",+ )+ ]+ if figure.column or any(+ _close(figure.value, value) for value in declared_observed+ ):+ return [+ self._figure_issue(+ "numeric_claim_conflict",+ figure,+ "cited",+ symbol,+ "cited_as_observed",+ "is declared cited yet presented as an observed value of this "+ "instrument",+ )+ ]+ return []- The position: a number is exempt only where it sits inside the- formula. "建议买入价 0.95 元(0.95 × 1.171 = 1.11245 参考)" is arithmetic- that derives nothing, and under a value-scoped exemption the entry- price outside the bracket inherited the exemption its own copy inside- the bracket earned.+ # ------------------------------------------------------------------ #+ # symbols and provenance+ # ------------------------------------------------------------------ #- The role: a formula's RESULT is a number the answer proposes, which is- legitimate for an entry price and never legitimate for a market print.- "2026-06-23 收盘价 = 1.171 × 0.80 = 0.937" claims a close the ledger- holds as 1.137, and the exemption released it. Under an observation- label the operands stay exempt and the result is compared.+ def _validate_unsourced_symbols(+ self,+ content: str,+ figures: Sequence[Figure],+ block: FiguresBlock,+ ) -> list[dict[str, Any]]:+ """Reject figures attached to an instrument no tool in this run handled.- Args:- segment: The clause the figure was found in.- formulas: ``_derivation_formulas`` output for that clause.- value: The figure.- start: Where the figure starts in ``segment``.- end: Where it ends.+ This is the mechanically decidable half of "what the tools did not+ return, you do not supply" (#886/#887). Naming a symbol is left alone —+ prose may legitimately mention an index or a peer — but the moment a+ line pairs an unhandled canonical symbol with a figure, the figure has+ no possible origin other than model memory.- Returns:- True when the occurrence may skip the price comparison.+ A figure the model declared ``cited`` is exempt, because a citation is+ an origin. That replaces the phrase catalogue of attribution verbs the+ exemption used to be keyed on, which could not tell "the paper reports"+ from "the backtest reports" without listing every subject by hand."""- for formula_start, formula_end, inputs, result in formulas:- if not (formula_start <= start and end <= formula_end):+ issues: list[dict[str, Any]] = []+ reported: set[str] = set()+ for index, (line, offset) in enumerate(_lines_with_offsets(content)):+ unknown = sorted(+ symbol+ for symbol in _scan_symbols(line)+ - self._session_symbols+ - reported+ if symbol.rsplit(".", 1)[0] not in self._session_symbol_roots+ )+ if not unknown:+ continue+ carried = [+ figure+ for figure in figures+ if figure.line == index and figure.shape == "measured"+ ]+ if not carried:continue- if _matches_any(value, inputs):- return True- if _matches_any(value, [result]) and not _labels_its_result_observed(- segment, formula_start+ if all(+ (block.match(figure.value, figure.percent) or _NO_DECLARATION).role+ == "cited"+ for figure in carried):- return True- return False-- def _validate_price_claims(self, content: str) -> list[dict[str, Any]]:- """Check Markdown OHLC tables and price prose against observed records.-- Comparison runs against every observed quote in the run, whichever tool- produced it. The provenance demands below stay keyed on ``get_market_data``- evidence, whose ``source``/``currency``/venue fields are authoritative;- a generic tool's fallback source is its own name, and requiring the- answer to spell that out would reject correct prose.- """- issues, table_lines = self._validate_price_tables(content)- records = self._comparable_price_records()- # A report names its subject once and then writes prose about it. Both- # narrower scopes are tried first; this is the last resort, and it only- # resolves when the whole answer names exactly one evidence symbol.- document_symbol = self._symbol_for_claim(content, 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, line_offset) in enumerate(_lines_with_offsets(content)):- if index in table_lines or "|" in line:continue- line_symbol = self._symbol_for_claim(line, records)- for segment, span_start, span_end in _clause_spans(line, line_offset):- if not _PRICE_CONTEXT_RE.search(segment):- continue- values = self._direct_price_values(segment)- if not values:- continue- has_price_claim = True- symbol = (- self._symbol_for_claim(segment, records)- or line_symbol- or document_symbol+ for symbol in unknown:+ reported.add(symbol)+ issues.append(+ {+ "code": "unsourced_symbol_figures",+ "symbol": symbol,+ "value": None,+ "role": None,+ "reason": "symbol_never_handled",+ "claim": line.strip()[:200],+ "span": [offset, offset + len(line)],+ "message": (+ f"No tool call in this session passed in or returned {symbol}, "+ "yet the answer attaches figures to it. Retrieve it, or report "+ "it as not retrieved."+ ),+ })- # Only the formula's own operands and result are exempt, at- # the position where they sit; a figure riding along in the- # same clause is still compared.- formulas = self._derivation_formulas(segment, records, symbol)- # NO attribution exemption here, deliberately. A paper's- # Sharpe is a figure this run could never have observed, so- # citing it is legitimate; a PRICE is exactly what this run- # does observe, so "analysts say TSLA.US last traded at- # 412.35" is the laundering shape this gate exists to catch —- # adding a citation subject must not buy a fabricated quote a- # way through. The exemption stays in the analysis gate only.- #- # An indicator reading is admissible evidence only for a- # LEVEL claim; a clause claiming a market print is answered by- # OHLC evidence alone.- indicator_admissible = bool(- _PRICE_LEVEL_WORD_RE.search(segment)- ) and not _OBSERVED_PRICE_WORD_RE.search(segment)- for value, value_start, value_end in values:- if self._occurrence_is_derived(- segment, formulas, value, value_start, value_end- ):- continue- issue = self._compare_price_claim(- value=value,- records=records,- field_name=None,- date_value=None,- symbol=symbol,- claim=segment.strip(),- span=(span_start, span_end),- indicator_admissible=indicator_admissible,- )- if issue:- issues.append(issue)- market_records = self._price_records()- if has_price_claim and market_records:- issues.extend(self._validate_price_provenance(content, market_records))- return self._dedupe_issues(issues)+ return issues@staticmethoddef _symbol_for_claim(@@ -1581,8 +951,14 @@ class _PolicyMixin:{"code": "canonical_symbol_not_surfaced","symbols": symbols,+ "value": None,+ "role": None,+ "span": None,+ "symbol": None,+ "reason": "symbol_not_surfaced","message": (- "A price claim must surface its locked canonical symbol and venue suffix."+ "A price claim must surface its locked canonical symbol and "+ "venue suffix."),})@@ -1605,9 +981,7 @@ class _PolicyMixin:for source in sourcesif not any(alias in folded- for alias in _SOURCE_ALIASES.get(- source.casefold(), (source.casefold(),)- )+ for alias in _SOURCE_ALIASES.get(source.casefold(), (source.casefold(),)))]if missing_sources:@@ -1615,6 +989,11 @@ class _PolicyMixin:{"code": "data_source_not_surfaced","sources": missing_sources,+ "value": None,+ "role": None,+ "span": None,+ "symbol": None,+ "reason": "source_not_surfaced","message": ("Price claims must name the actual data source: "+ ", ".join(missing_sources)@@ -1636,6 +1015,11 @@ class _PolicyMixin:{"code": "currency_not_surfaced","currencies": missing_currencies,+ "value": None,+ "role": None,+ "span": None,+ "symbol": None,+ "reason": "currency_not_surfaced","message": ("Price claims must name their quote currency: "+ ", ".join(missing_currencies)@@ -1653,450 +1037,13 @@ class _PolicyMixin:tokens = _CURRENCY_ALIASES.get(code, (currency.casefold(),))if any(token.casefold() in folded for token in tokens):return True- return code == "CNY" and bool(_BARE_YUAN_RE.search(content))-- def _validate_price_tables(- self,- content: str,- ) -> tuple[list[dict[str, Any]], set[int]]:- """Validate field/date-specific claims in Markdown OHLC tables."""- positions = _lines_with_offsets(content)- lines = [line for line, _ in positions]- issues: list[dict[str, Any]] = []- consumed: set[int] = set()- index = 0- records = self._comparable_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- row_start = positions[row_index][1]- issue = self._compare_price_claim(- value=values[0],- records=records,- field_name=field_name,- date_value=date_value,- symbol=symbol,- claim=row[position].strip(),- # A table cell's claim text is a bare number, so it- # can never be located by substring search — "1.10"- # matched inside "21.10 亿元" and rewrote an untouched- # turnover figure into "2(略※)". The row's own span- # is the anchor; the value inside it is what is cut.- span=(row_start, row_start + len(lines[row_index])),- )- 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,- span: tuple[int, int] | None = None,- indicator_admissible: bool = False,- ) -> dict[str, Any] | None:- """Compare one unlabelled observed claim to the closest evidence value.-- Args:- value: The figure the answer states.- records: Comparable observed price evidence.- field_name: OHLC field the claim is keyed to (table column), if any.- date_value: Trade date the claim is keyed to, if any.- symbol: Symbol explicitly resolved for the claim, if any.- claim: Clause or cell text, for the issue message.- span: ``(start, end)`` of the claim inside the validated answer.- indicator_admissible: The prose clause states a price LEVEL- (支撑位 / 均线 / bollinger band), the one claim an indicator- reading may answer. Every other price claim — a named OHLC- field, a spot quote, a proposed entry — is compared against- OHLC evidence only, which is the rule the table path already- applies by filtering on ``field_name``. The table path passes- a ``field_name`` for every cell it validates and so leaves- this at its default.- """- resolved_symbol = symbol- 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})- # An indicator reading is symbol-bound in a way an OHLC bar's union is- # not. With evidence for two instruments and a clause naming neither,- # 562500's sma_20 grounded "600519.SH … 其均线在 1.150 元"; the union- # below was argued for OHLC quotes, not for a derived level attached- # to one symbol. Drop indicator records whenever the claim's symbol- # was not explicitly resolved and the run holds more than one.- if resolved_symbol is None and len({r.symbol for r in records if r.symbol}) > 1:- candidates = [record for record in candidates if record.field != "indicator"]- if not indicator_admissible:- candidates = [record for record in candidates if record.field != "indicator"]- if not symbol and len(symbols) == 1:- symbol = symbols[0]- # An unattributed claim used to be rejected outright once the run held- # evidence for more than one symbol. That is every comparison report:- # "Apple's closing price was 313.33 USD. Microsoft closed higher." names- # its subject by company name, and the clause was refused although the- # value was exactly the observed close sitting in evidence. Such a claim- # is now checked against the union of the observed quotes instead, so a- # number the run never observed is still caught below — it simply has to- # match nothing at all rather than nothing under one chosen symbol.- 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 _timestamp_matches_claim_date(record.timestamp, date_value)- ]- if not candidates:- return {- "code": "numeric_claim_unavailable",- "claim": claim,- "span": list(span) if span else None,- "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,- "span": list(span) if span else None,- "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}."- ),- }-- @staticmethod- def _masked_candidate_text(text: str) -> str:- """Mask every non-price digit run, preserving string length and offset.-- Each mask match is replaced by an equal-length run of spaces, so a- number's offset in the returned string is its offset in ``text`` — the- structural price-claim scan needs that alignment.- """- masked = text- for pattern in (- _MD_LIST_ITEM_RE,- _RATE_FORMULA_IDENTITY_RE,- _CANONICAL_SYMBOL_RE,- _LOCALIZED_DATE_RE,- _DATE_RE,- _SHORT_DATE_RE,- _DASH_DATE_RE,- _PERCENT_RANGE_RE,- _PERCENTAGE_POINT_RE,- _ORDER_LEVEL_RE,- _AGGREGATE_AMOUNT_RE,- _LABELLED_SCORE_RE,- _INDICATOR_VALUE_RE,- _SIGNAL_VALUE_RE,- _PROSPECTIVE_LEVEL_RE,- _REFERENCE_LEVEL_RE,- _SINCE_REFERENCE_RE,- _LINE_REFERENCE_RE,- _NUMBERED_HEADING_RE,- _RATIO_RE,- _FX_RATE_RE,- _QUANTITY_WITH_UNIT_RE,- ):- masked = pattern.sub(lambda m: " " * (m.end() - m.start()), masked)- return masked-- @staticmethod- def _numbers_without_dates_or_percent(text: str) -> list[float]:- """Extract the numbers in a claim that could plausibly be prices.-- Digits that belong to a canonical symbol, a calendar date, an aggregate- amount, a labelled score, a named indicator reading, a unit-bearing- quantity, or a percentage are masked first. Left unmasked they are- compared against observed OHLC ranges and reject a correct draft:- ``000543.SZ`` alone contributes 543, and a well-formed verdict line- contributes its confidence score and every moving-average window it- names (#1001).-- Args:- text: One claim segment or table cell.-- Returns:- Candidate price values, in order of appearance.- """- masked = _PolicyMixin._masked_candidate_text(text)- values: list[float] = []- for match in _NUMBER_RE.finditer(masked):- tail = masked[match.end() :].lstrip()- if tail.startswith(("%", "%")):- continue- try:- values.append(float(match.group(0).replace(",", "")))- except ValueError:- continue- return values-- @staticmethod- def _direct_price_values(text: str) -> list[tuple[float, int, int]]:- """Numbers in a price segment that read as asserted observed values.-- Returned as ``(value, start, end)``: the masking that decides which- digits are candidates preserves length, so each offset is the number's- offset in ``text``. The caller needs the position, not only the value —- a derivation exempts the occurrence sitting inside it, not every copy- of the same number in the clause.-- ``_numbers_without_dates_or_percent`` returns every non-masked number;- this further drops numbers that are formula operands rather than claims- (#1354). For each surviving number, the span between the nearest- preceding price-context word and the number decides:-- * a sentence boundary (``. ``/``! ``/``? ``) in the span — the number- belongs to a later sentence the price word cannot reach ("close was- 210. In 2024 …" must not claim 2024);- * otherwise, a closed formula marker in the span turns the number into- an operand, unless an observation binder ("was", "at", 报收/收于/…) after- the last marker re-attaches it to the price word.-- "close/SMA50 > 1" and "close above SMA50 and was 2500" are decided in- opposite directions by the binder; "close was 2500" (no marker) stays- a claim either way.- """- price_words = list(_PRICE_CONTEXT_RE.finditer(text))- masked = _PolicyMixin._masked_candidate_text(text)- values: list[tuple[float, int, int]] = []- for match in _NUMBER_RE.finditer(masked):- tail = masked[match.end() :].lstrip()- if tail.startswith(("%", "%")):- continue- try:- value = float(match.group(0).replace(",", ""))- except ValueError:- continue- preceding = [w for w in price_words if w.end() <= match.start()]- if preceding:- span = text[preceding[-1].end() : match.start()]- if _SENTENCE_BOUNDARY_RE.search(span):- continue- markers = list(_FORMULA_MARKER_RE.finditer(span))- if markers and not _OBSERVATION_BINDER_RE.search(- span[markers[-1].end() :]- ):- continue- values.append((value, match.start(), match.end()))- return values-- def _derivation_formulas(- self,- text: str,- records: Sequence[EvidenceRecord],- symbol: str | None,- ) -> list[tuple[int, int, list[float], float]]:- """Return every arithmetically valid, observation-anchored formula.-- Each entry is ``(start, end, operands, result)`` — the formula's own- character span inside ``text``, the operands it consumes and the result- it produces. The span is what makes the exemption safe. A value-scoped- exemption ("this number equals something a formula justifies") let a- figure be exempt EVERYWHERE in the clause once it appeared anywhere in- an equation, and a model told by the correction prompt to show its- arithmetic can satisfy that with arithmetic that derives nothing:- "建议买入价 0.95 元(0.95 × 1.171 = 1.11245 参考)" is true and released- an entry price 19% below every observed bar. The occurrence inside the- formula is exempt; the one beside it is compared like any other claim.-- There is no keyword or shape precondition. A `基于` / `based on` was- once required and an added `_ARITHMETIC_EQUATION_RE` relaxed it to- "any two-operand equation"; both are subsumed by what decides below —- a result separator, a parseable arithmetic run of at least two- operands (``_evaluate_formula``), an input matching observed evidence,- and a result that is correct. Deleting the regex changed no verdict in- the suite and removes one entry from the regex catalogue.-- Args:- text: The clause (or line) to inspect.- records: Comparable observed price evidence.- symbol: Symbol resolved for the claim, if any.-- Returns:- ``(start, end, operands, result)`` per valid formula, in order.- """- 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 []- observed = [- float(record.value) for record in candidates if record.value is not None- ]- if not observed:- return []-- formulas: list[tuple[int, int, list[float], float]] = []- for equals in _RESULT_SEPARATOR_RE.finditer(text):- # An indicator identifier carries digits ("SMA20", "MA5"); left in- # place they leak into the arithmetic run ("20 1.150 × 0.95") and- # the formula fails to parse, so a derivation from an observed- # moving average was never accepted. The blanking is- # LENGTH-PRESERVING because the offsets below are the exemption's- # anchor: collapsing "SMA20" to one space shifted every span after- # it and the formula was excluded from its own protection.- prefix = _INDICATOR_IDENTIFIER_RE.sub(- lambda match: " " * (match.end() - match.start()),- text[: equals.start()],- )- left = re.search(r"([0-9.,+\-*/×÷()\s]+)$", prefix)- 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):- formulas.append(- (left.start(1), equals.end() + right.end(), inputs, claimed)- )- return formulas-- def _derivation_justified_values(- self,- text: str,- records: Sequence[EvidenceRecord],- symbol: str | None,- ) -> list[float]:- """Every operand and result of every valid formula in ``text``.-- The flat form, for the callers that only ask "is this figure one a- formula here justifies" without a position to check it at.- """- justified: list[float] = []- for _, _, inputs, result in self._derivation_formulas(text, records, symbol):- justified.extend(inputs)- justified.append(result)- return justified-- @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+ if code != "CNY":+ return False+ return any(+ char == "元"+ and (index == 0 or content[index - 1] not in _OTHER_CURRENCY_PREFIXES)+ for index, char in enumerate(content)+ )@staticmethoddef _dedupe_issues(issues: list[dict[str, Any]]) -> list[dict[str, Any]]:@@ -2110,3 +1057,9 @@ class _PolicyMixin:seen.add(key)unique.append(issue)return unique+++#: The role an undeclared figure is validated under (spec §4, undeclared mode).+_NO_DECLARATION = Declaration(+ index=0, value_text="", value=0.0, percent=False, role="observed", note="", ref=""+)diff --git a/agent/src/agent/grounding/release.py b/agent/src/agent/grounding/release.pyindex 3983dc72e..138f93140 100644--- a/agent/src/agent/grounding/release.py+++ b/agent/src/agent/grounding/release.py@@ -13,17 +13,14 @@ from src.agent.grounding.identity import (_utc_now,)from src.agent.grounding.evidence import EvidenceRecord-from src.agent.grounding.figures import _NUMBER_RE, _clause_spans, _lines_with_offsets-from src.agent.grounding.policies import (- ValidationResult,- _ANALYSIS_METRIC_RE,- _CURRENCY_BEFORE_RE,- _CURRENCY_UNIT_WORDS,- _MEASURE_NUMBER_RE,- _PolicyMixin,- _TABLE_FIELD_ALIASES,- _matches_any,+from src.agent.grounding.figures import (+ _lines_with_offsets,+ currency_prefix_start,+ currency_suffix_end,+ parse_figures_block,+ scan_figures,)+from src.agent.grounding.policies import ValidationResult# Bounded read-only recovery (#1081): a missing instrument identity or price# evidence is often recoverable deterministically, so the loop should keep@@ -41,7 +38,7 @@ _REDACTABLE_CODES = frozenset("numeric_claim_conflict","numeric_claim_unavailable","unsourced_symbol_figures",- "analysis_claim_unavailable",+ "figure_undeclared",})@@ -71,25 +68,12 @@ _REDACTION_MARKER_ZH = "(略※)"_REDACTION_MARKER_EN = "(omitted※)"-_UNIT_AFTER_RE = re.compile(- r"\s*(?:(?:" + _CURRENCY_UNIT_WORDS + r")(?![A-Za-z//])"- r"|元(?![A-Za-z//\u3400-\u9fff]))"-)--MAX_SYMBOL_RESOLUTION_ATTEMPTS = 2MAX_PRICE_EVIDENCE_ATTEMPTS = 3-# A table column whose header names a price. Wider than the OHLC aliases on-# purpose: 挂单价 / 目标价 / Entry Price are price columns that-# ``_validate_price_tables`` does not key on and the prose scan skips, so-# their cells are figures no validator ever reads.-_PRICE_HEADER_RE = re.compile(r"(?:价格?|价位|price)\s*$", re.IGNORECASE)--def _format_price(value: float) -> str:"""Render an observed price without scientific notation or lost digits.@@ -99,42 +83,6 @@ def _format_price(value: float) -> str:return format(value, ".10g")-def _redaction_targets(values: Sequence[Any]) -> tuple[bool, list[float], list[str]]:- """Split issue values into cut-everything / numeric / percent-literal cuts.-- Args:- values: The ``value`` field of each issue flagged on one clause.-- Returns:- ``(cut_all, numeric targets, percent literals)``. ``cut_all`` is set by- a ``None`` value, which is how ``unsourced_symbol_figures`` says "every- figure in this clause belongs to an instrument no tool handled".- """- cut_all = False- targets: list[float] = []- literals: list[str] = []- for value in values:- if value is None:- cut_all = True- elif isinstance(value, bool):- continue- elif isinstance(value, (int, float)):- targets.append(float(value))- elif isinstance(value, str) and value.strip():- literal = value.strip().replace(" ", "").replace(",", "")- if literal.endswith(("%", "%")):- literals.append(literal)- else:- try:- targets.append(float(literal))- except ValueError:- continue- return cut_all, targets, literals---_RELEASE_NOTE_LINE_RE = re.compile(r"^[^\S\n]*※[^\n]*\n?", re.MULTILINE)--def _strip_release_markers(content: str) -> str:"""Remove any redaction marker or release note the MODEL wrote.@@ -152,14 +100,24 @@ def _strip_release_markers(content: str) -> str:stripped = content.replace(_REDACTION_MARKER_ZH, "").replace(_REDACTION_MARKER_EN, "")- return _RELEASE_NOTE_LINE_RE.sub("", stripped)+ return "\n".join(+ line for line in stripped.splitlines() if not line.lstrip().startswith("※")+ )class _ReleaseMixin:"""Release behaviour of :class:`GroundingLedger`."""def correction_prompt(self, validation: ValidationResult) -> str:- """Build bounded feedback for one rejected model draft."""+ """Build bounded feedback for one rejected model draft.++ The feedback is per NUMBER, not per rule: every figure issue carries+ the value as it was written, the role it was declared under and the+ reason that role failed, so the message says "0.95 is a proposed level+ outside the observed range 0.567–1.053 and its note derives no value"+ instead of restating the policy. Each figure then has exactly three+ ways out, and they are spelled out once at the end.+ """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:",@@ -171,26 +129,34 @@ class _ReleaseMixin:# rejects it again and the run burns iterations until the fallback.banned: list[str] = []for issue in validation.issues:- code = issue.get("code")+ if issue.get("code") not in _REDACTABLE_CODES:+ continuevalue = issue.get("value")- if code in {"numeric_claim_conflict", "numeric_claim_unavailable", "unsourced_symbol_figures", "analysis_claim_unavailable"} and value is not None:- symbol = issue.get("symbol") or ""- label = f"{value:g}" if isinstance(value, (int, float)) else str(value)- banned.append(f"{label} ({symbol})" if symbol else label)+ if value is None:+ continue+ symbol = issue.get("symbol") or ""+ label = f"{value:g}" if isinstance(value, (int, float)) else str(value)+ banned.append(f"{label} ({symbol})" if symbol else label)if banned:deduped = list(dict.fromkeys(banned))lines.append(- "REMOVE these rejected value(s) entirely - do NOT restate, rephrase, "- "or recompute them in any other format: " + ", ".join(deduped) + "."+ "Every figure above must be either DECLARED with the role it really "+ "has, REWRITTEN to a value the tools returned, or REMOVED. Do not "+ "restate a rejected value in another format: " + ", ".join(deduped) + ".")repeated: list[str] = []for prior in self._validations:for prior_issue in prior.get("issues", []):prior_value = prior_issue.get("value")- if isinstance(prior_value, (int, float)):- mark = f"{prior_value:g}"- if any(entry.startswith(mark) for entry in deduped):- repeated.append(mark)+ if prior_value is None:+ continue+ mark = (+ f"{prior_value:g}"+ if isinstance(prior_value, (int, float))+ else str(prior_value)+ )+ if any(entry.startswith(mark) for entry in deduped):+ repeated.append(mark)if repeated:lines.append("These value(s) have now been rejected repeatedly across drafts: "@@ -200,9 +166,14 @@ class _ReleaseMixin:)lines.extend([- "If a value is a derived or prospective level (stop, target, entry, etc.), "- "you must EITHER show the full derivation with the observed inputs and the "- "formula, OR omit it from the draft.",+ "End the answer with a ```figures``` block declaring every number that "+ "carries a decimal point, a percent sign, a currency mark or a table "+ "cell, one per line as `value | role | note | ref`, where role is one "+ "of observed / derived / proposed / cited / count.",+ "observed must appear in the tool results; derived needs a note that is "+ "the arithmetic itself, with one operand this session observed; "+ "proposed must be derived or lie inside the observed price range; "+ "cited needs a source in its note; count is not checked.","Reuse the exact locked symbol and venue.","Do not attach figures to a symbol no tool call in this session handled; ""report it as not retrieved instead.",@@ -318,9 +289,7 @@ class _ReleaseMixin:for validation in self._validationsfor code in (issue.get("code") for issue in validation.get("issues", []))}- if issue_codes & {- "numeric_claim_unavailable", "numeric_claim_conflict", "unsourced_symbol_figures"- }:+ if issue_codes & _REDACTABLE_CODES:if is_zh:return ("我的回答被安全门槛拒绝:草稿引用了本会话未通过工具获取的价格数字,无法核验。"@@ -433,8 +402,6 @@ class _ReleaseMixin:self,content: str,validation: ValidationResult,- *,- require_checked_figures: bool = True,) -> str | None:"""Append a data note when the only defects are missing provenance words.@@ -451,152 +418,105 @@ class _ReleaseMixin:appending "562500.SH: price source yahoo" under a draft that reads"贵州茅台 最新收盘价 1.171 元" turns a misattribution into a releasedanswer with a footnote naming a different instrument. It keeps its- model round (base rate: 1 of 27 rejections in the local traces, so- nearly all of the saving survives).+ model round.- The repair is also declined when the draft carries a price COLUMN the- table validator does not key on ("| 档位 | 挂单价 |"): those cells are- outside every validator's reach, and the note says where this run's- prices came from. Attaching it to a draft holding an unchecked ladder- price attests to a figure the gate never saw, in zero model rounds —- the round it used to cost was the last chance to drop that figure.+ The "unchecked price column" veto this used to carry is gone with the+ surface it guarded. It declined the repair whenever a table held a+ price column no validator read (``| 档位 | 挂单价 |``), because the+ note would attest to figures the gate never saw. Every cell of every+ table is now a measurement-shaped figure the gate checks, so no such+ column exists.Args:content: The rejected draft.validation: Its validation result.- require_checked_figures: Decline when an unchecked price column is- present. ``redacted_release`` passes False: there the choice- is not "repair or one more model round" but "repair or the- canned refusal", the revision budget is already spent, and the- document it repairs carries the redaction footnote.Returns:The draft with a provenance note appended, or None when the issues- are not provenance-only, an unchecked price column is present, or- there is no price evidence to cite.+ are not provenance-only or there is no price evidence to cite."""codes = {issue.get("code") for issue in validation.issues}if not codes or not codes <= _REPAIRABLE_PROVENANCE_CODES:return None- if require_checked_figures and self._has_unchecked_price_column(content):- return Nonenote = self._provenance_note(content)if note is None:return Nonereturn content.rstrip() + "\n\n" + note- @staticmethod- def _has_unchecked_price_column(content: str) -> bool:- """Whether a Markdown table holds a price column no validator reads.-- ``_validate_price_tables`` keys on ``_TABLE_FIELD_ALIASES`` — the OHLC- headers — and the prose scan skips every line containing "|". A column- headed 挂单价 / 目标价 / Entry price is read by neither.-- Args:- content: The draft to inspect.-- Returns:- True when such a column carries at least one numeric cell.- """- lines = content.splitlines()- for header, rows, _ in _PolicyMixin._pipe_tables(lines):- unchecked = [- position- for position, cell in enumerate(header)- if _PRICE_HEADER_RE.search(cell)- and cell.strip().casefold() not in _TABLE_FIELD_ALIASES- ]- if not unchecked:- continue- for row in rows:- for position in unchecked:- if position < len(row) and _NUMBER_RE.search(row[position]):- return True- return False-def redacted_release(self, content: str, validation: ValidationResult) -> str | None:"""Release the last rejected draft with its unverified figures cut out.Once the revision budget is spent, the draft is still the analysis theuser waited through every revision for, and the gate objected to- specific figures in specific clauses — not to the trend read, the- indicator commentary, or the risk notes around them. Each rejected- figure is replaced by a visible marker AT THE SPAN the validator- flagged, every other occurrence of the same figure elsewhere in the- document is cut with it, the missing provenance words are appended if- that is all that remains, and the whole released document — footnote- included — is re-validated by the same gate: only text that passes is- returned, so nothing the gate rejected reaches the user.-- Fail-closed by construction. None — leave the canned fallback in place —- whenever the run never observed a price at all (the draft's numbers then- have no basis to stand next to), carries an issue that is not a- cut-out-able figure (an identity finding is one), has a flagged clause- that cannot be located, or still fails after the cut.+ specific figures — not to the trend read, the indicator commentary, or+ the risk notes around them. Each rejected figure is replaced by a+ visible marker AT ITS OWN SPAN, the missing provenance words are+ appended if that is all that remains, and the cut document is+ re-validated by the same gate: only text that passes is returned.++ The document-wide "sweep every other copy of the figure" second stage+ is gone. It existed because the old validators only ever looked at+ clauses carrying a price word, so the same rejected number could stand+ untouched in a bullet or under a non-OHLC table header while the+ footnote claimed it had been removed. Every measurement-shaped number+ is now located and checked individually, so an occurrence that was not+ flagged is one this gate grounded, and cutting it would remove a+ figure the evidence supports.++ Fail-closed by construction. None — leave the canned fallback in place+ — whenever the run never observed a price at all, an issue is not a+ cut-out-able figure (an identity finding is one), a flagged figure+ cannot be located, or the document still fails after the cut.Args:content: The rejected draft.validation: Its validation result.Returns:- The redacted, re-validated draft followed by a note stating how many- figures were removed and the observed range, or None.+ The redacted, re-validated answer with its declaration block+ stripped and a note stating how many figures were removed, or None."""if not self._price_records():return Nonetext = _strip_release_markers(content)- removed = 0# Stripping moves every offset after it, and the issue spans are the# only anchor the cuts have, so the verdict is retaken on the text the# cuts will actually be made in.- pending = list(- validation.issues- if text == content- else self._validate(text, record=False).issues- )- # A validator reports one figure per clause, so cutting it can reveal- # the next one on the recheck. Cut, recheck, repeat — bounded, and- # every cut is a figure the gate itself flagged.+ check = validation if text == content else self._validate(text, record=False)+ removed = 0for _ in range(_MAX_REDACTION_PASSES):- codes = {issue.get("code") for issue in pending}- if not codes or not codes <= (_REDACTABLE_CODES | _REPAIRABLE_PROVENANCE_CODES):+ if check.valid:+ break+ codes = {issue.get("code") for issue in check.issues}+ if not codes <= (_REDACTABLE_CODES | _REPAIRABLE_PROVENANCE_CODES):return None- # Two issues can point at one clause ("unsourced symbol" and the- # conflict on the same figure), so cuts are grouped per span:- # each clause is rewritten once with every value flagged for it.- by_span: dict[tuple[int, int], list[Any]] = {}- for issue in pending:- if issue.get("code") not in _REDACTABLE_CODES:- continue- span = self._issue_span(text, issue)- if span is None:- return None- by_span.setdefault(span, []).append(issue.get("value"))- text, count = self._redact_spans(text, by_span)- if count == 0:+ cut, count = self._cut_flagged(text, check.issues)+ if cut is None:return None- removed += count+ if count:+ text = cut+ removed += count+ check = self._validate(text, record=False)+ if check.valid:+ break+ repaired = self.repair_provenance(text, check)+ if repaired is None:+ if count == 0:+ return None+ continue+ text = repairedcheck = self._validate(text, record=False)- if not check.valid:- repaired = self.repair_provenance(- text, check, require_checked_figures=False- )- if repaired is not None:- text = repaired- check = self._validate(text, record=False)- if check.valid:- break- pending = list(check.issues)- else:+ if not check.valid or removed == 0:return None- released = text.rstrip() + "\n\n" + self._release_note(removed, text)+ body = check.released_text+ note = self._release_note(removed, body)# The note carries the observed range and the canonical symbols, so it- # is answer text too. Validating the body and shipping body+note left- # the released document as a whole unchecked, which contradicted the- # fail-closed promise in this docstring.- if not self._validate(released, record=False).valid:+ # is answer text too, and it goes through the same gate — in undeclared+ # mode, since it has no block of its own. Shipping it unchecked would+ # contradict the fail-closed promise above.+ if not self._validate(note, record=False).valid:return None+ released = body.rstrip() + "\n\n" + note# Recorded beside the drafts but NOT as one: the artifact otherwise# held no evidence for the fail-closed promise above, because every# recheck on this path is deliberately unrecorded.@@ -611,21 +531,11 @@ class _ReleaseMixin:@staticmethoddef _issue_span(text: str, issue: dict[str, Any]) -> tuple[int, int] | None:- """Locate the flagged clause in ``text``.-- The validators record the clause's character span, which is the only- reliable anchor: the stored ``claim`` is normalised (thousands- separators stripped, table cells rendered as "label: value"), so- ``text.find(claim)`` missed every price above 999 and every metric- table outright, and for a bare numeric cell it matched INSIDE a longer- number — "1.10" found in "21.10 亿元", rewriting an untouched turnover- figure into "2(略※)".-- The substring fallback that used to sit here is gone. Every one of the- six redactable-issue construction sites carries a span, so it was- reachable only from a hand-built issue, and it carried a documented- digit-boundary rationale for a hazard the span had already settled —- which is worse than no code, because a reader trusts it.+ """Locate the flagged figure in ``text``.++ The validators record the character span of the figure itself, which+ is the only reliable anchor: a stored claim string is normalised and+ a bare numeric cell ("1.10") matches inside a longer number ("21.10").Args:text: The document the issue was raised against.@@ -645,266 +555,56 @@ class _ReleaseMixin:return start, endreturn None- def _release_note(self, removed: int, content: str | None = None) -> str:- """Explain the redaction to the user, with the observed range.-- ``redacted_release`` returns None before this is reached when the run- holds no price record, which is the only case in which the summary is- None — so it is read directly rather than behind an ``or ""`` that- described a state the caller cannot produce.- """- is_zh = self._user_writes_chinese()- joined = self._observed_range_summary(is_zh, content)- if is_zh:- return (- f"※ 略去 {removed} 处无法与本会话工具数据对上的数值。"- f"已观测 OHLC 范围:{joined}。"- "如需买入价,请让我基于已观测的收盘价或均线给出带公式的推导。"- )- return (- f"※ {removed} figure(s) that could not be matched to this session's tool data "- f"were omitted. Observed OHLC range: {joined}. "- "For an entry price, ask me to derive one with a visible formula from an "- "observed close or moving average."- )-- def _redact_spans(+ def _cut_flagged(self,text: str,- by_span: dict[tuple[int, int], list[Any]],- ) -> tuple[str, int]:- """Cut the flagged figures at their spans, then everywhere else.-- Numbers are located on the masked clause (symbols, dates, prospective- levels blanked) so a ticker's digits are never cut. A numeric value is- matched numerically, a percent-shaped analysis value textually, and a- ``None`` value (a clause attributing figures to an unhandled symbol)- cuts every number in that clause.-- The second stage is why the footnote can be believed. Cutting only the- flagged clause left the same rejected figure standing in a Markdown- table under a non-OHLC header or in a bullet with no price word —- neither surface is scanned by the validators — while the footnote- asserted it had been removed.-- Two kinds of occurrence are never swept, because the gate has already- accepted them where they stand: a figure the ledger observed, and a- figure sitting inside a valid formula elsewhere in the document.- Without the second, the rejected entry price 0.95 was cut out of- "基于 MA20 0.7158 × 0.95 = 0.680", mangling the one derivation the- correction prompt asks the model to write (159516.SZ replay,- 2026-09-09).-- The formula protection is scoped to the formula's own character SPANS.- Scoped to the VALUE it protected the rejected figure document-wide:- with "基于收盘价 1.171 × 0.95 = 1.112" anywhere in the draft, the same- 0.95 survived in "| 第一档 | 0.95 |" under a footnote saying one figure- had been cut — the exact restatement this second stage exists to- remove, protected by the derivation the model wrote beside it.-- A percent literal is protected the same way. Cutting every occurrence- of a flagged literal took the accepted one with it: "从 1.110 涨到- 1.171,区间收益率约 5.5%" is endpoint arithmetic this gate validated,- and it was cut and footnoted as unmatched because an unrelated- "策略年化波动率 5.5%" was flagged in the next clause.+ issues: Sequence[dict[str, Any]],+ ) -> tuple[str | None, int]:+ """Replace every flagged figure with the omission marker.- Args:- text: The document to rewrite.- by_span: ``(start, end)`` → the values flagged inside that span.-- Returns:- The rewritten text and the number of figures replaced.- """- swept: list[float] = []- swept_literals: list[str] = []- pieces: list[str] = []- cursor = 0- total = 0- for (start, end), values in sorted(by_span.items()):- if start < cursor:- continue- cut_all, targets, literals = _redaction_targets(values)- swept.extend(targets)- swept_literals.extend(literals)- replaced, count = self._rewrite_segment(- text[start:end], cut_all, targets, literals- )- pieces.append(text[cursor:start])- pieces.append(replaced)- total += count- cursor = end- pieces.append(text[cursor:])- text = "".join(pieces)- if total == 0 or not (swept or swept_literals):- return text, total- observed = self._observed_price_values()- survivors = [- target for target in swept if not _matches_any(target, observed, rel=1e-9)- ]- if not survivors and not swept_literals:- return text, total- protected = self._derivation_spans(text)- if swept_literals:- protected += self._accepted_metric_spans(text)- # Line by line, so each replacement takes the marker from the script of- # its OWN line. Run over the whole document the second stage picked one- # marker for everything, and a Chinese report containing an English- # table released "| Entry |(略※) |".- extra = 0- out: list[str] = []- cursor = 0- for line, start in _lines_with_offsets(text):- out.append(text[cursor:start])- local = [- (span_start - start, span_end - start)- for span_start, span_end in protected- if span_start >= start and span_end <= start + len(line)- ]- rewritten, count = self._rewrite_segment(- line, False, survivors, swept_literals, protected=local- )- out.append(rewritten)- extra += count- cursor = start + len(line)- out.append(text[cursor:])- return "".join(out), total + extra-- def _derivation_spans(self, text: str) -> list[tuple[int, int]]:- """Where a valid derivation sits in ``text``, in document offsets.+ An issue naming one figure cuts that figure. An issue with no value —+ ``unsourced_symbol_figures``, which says "every figure on this line+ belongs to an instrument no tool handled" — cuts every+ measurement-shaped figure inside its span.Args:- text: The document about to be swept.-- Returns:- The character span of every arithmetically valid,- observation-anchored formula in it.- """- records = self._comparable_price_records()- document_symbol = self._symbol_for_claim(text, records)- spans: list[tuple[int, int]] = []- for line, offset in _lines_with_offsets(text):- if not _NUMBER_RE.search(line):- continue- symbol = self._symbol_for_claim(line, records) or document_symbol- for start, end, _, _ in self._derivation_formulas(line, records, symbol):- spans.append((offset + start, offset + end))- return spans-- def _accepted_metric_spans(self, text: str) -> list[tuple[int, int]]:- """Where this gate ACCEPTED a metric figure in ``text``.-- A clause the analysis validator examined — it carries a metric word- and a measurement-shaped number — and did not flag is a clause whose- figures this gate grounded. Sweeping such a figure out because an- unrelated clause states the same percentage cut a validated derivation- and footnoted it as unmatched.-- The verdict comes from the validator itself rather than from a second- copy of its exemption rules: a clause with no metric word was never- examined (a bullet, an unclaimed table column) and is deliberately not- protected — that unscanned surface is what the sweep exists for.-- Args:- text: The document about to be swept.-- Returns:- The character span of every examined-and-accepted metric clause.- """- flagged = {- (int(issue["span"][0]), int(issue["span"][1]))- for issue in self._validate(text, record=False).issues- if isinstance(issue.get("span"), (list, tuple))- and len(issue["span"]) == 2- }- spans: list[tuple[int, int]] = []- for line, offset in _lines_with_offsets(text):- for segment, start, end in _clause_spans(line, offset):- if not _ANALYSIS_METRIC_RE.search(segment):- continue- if not self._measure_numbers(segment):- continue- if any(- span_start <= start and end <= span_end- for span_start, span_end in flagged- ):- continue- spans.append((start, end))- return spans-- def _rewrite_segment(- self,- segment: str,- cut_all: bool,- targets: Sequence[float],- literals: Sequence[str],- *,- protected: Sequence[tuple[int, int]] = (),- ) -> tuple[str, int]:- """Replace the wanted figures in one stretch of text with the marker.-- Args:- segment: The stretch of the answer to rewrite.- cut_all: Cut every number, not only the listed targets.- targets: Numeric values to cut.- literals: Percent-shaped figures to cut by their written text.- protected: Character ranges inside ``segment`` that must survive- whatever they contain — a valid formula, or a metric clause- this gate accepted. Protection is by POSITION, not by value:- the rejected entry price is usually also the multiplier of the- correct derivation, and protecting the value protected every- restatement of the rejected figure along with it.+ text: The document to rewrite.+ issues: The issues raised against it.Returns:- The rewritten stretch and the number of figures replaced.+ ``(rewritten text, figures replaced)``, or ``(None, 0)`` when a+ flagged issue could not be located and the release must fail closed."""- if not cut_all and not targets and not literals:- return segment, 0- # The marker follows the SCRIPT OF THE TEXT BEING CUT, not the user's- # message: a Chinese user asking about a US name gets English tables,- # and "Suggested entry price(略※) per share." was the result. A- # stretch with neither script — a numeric table row — falls back to- # the user's language, which is what the footnote is written in.- if re.search(r"[\u3400-\u9fff]", segment):- marker = _REDACTION_MARKER_ZH- elif re.search(r"[A-Za-z]", segment):- marker = _REDACTION_MARKER_EN- else:- marker = (- _REDACTION_MARKER_ZH- if self._user_writes_chinese()- else _REDACTION_MARKER_EN- )- spans: list[tuple[int, int]] = []- if literals:- for match in _MEASURE_NUMBER_RE.finditer(segment):- normalized = match.group(0).replace(" ", "").replace(",", "")- if normalized in literals:- spans.append((match.start(), match.end()))- masked = self._masked_candidate_text(segment)- for match in _NUMBER_RE.finditer(masked):- try:- number = float(match.group(0).replace(",", ""))- except ValueError:+ block = parse_figures_block(text)+ figures = scan_figures(text, block)+ cuts: set[tuple[int, int]] = set()+ for issue in issues:+ if issue.get("code") not in _REDACTABLE_CODES:continue- if cut_all or _matches_any(number, targets, rel=1e-9):- spans.append((match.start(), match.end()))+ span = self._issue_span(text, issue)+ if span is None:+ return None, 0+ if issue.get("value") is None:+ cuts.update(+ (figure.start, figure.end)+ for figure in figures+ if figure.shape == "measured"+ and span[0] <= figure.start+ and figure.end <= span[1]+ )+ else:+ cuts.add(span)+ if not cuts:+ return text, 0pieces: list[str] = []cursor = 0count = 0- for start, end in sorted(set(spans)):+ for start, end in sorted(cuts):if start < cursor:continue- if any(- keep_start <= start and end <= keep_end- for keep_start, keep_end in protected- ):- continue- unit = _UNIT_AFTER_RE.match(segment, end)- if unit:- end = unit.end()- symbol = _CURRENCY_BEFORE_RE.search(segment[cursor:start])- if symbol:- start = cursor + symbol.start()+ start = max(cursor, currency_prefix_start(text, start))+ end = currency_suffix_end(text, end)+ marker = self._marker_for(text, start)if marker is _REDACTION_MARKER_ZH:# "建议买入价 0.95 元" → "建议买入价(略※)": a full-width# bracket sits flush against the preceding word. Not against a@@ -912,13 +612,60 @@ class _ReleaseMixin:# padding and reads as a broken row.while (start > cursor- and segment[start - 1] == " "- and segment[: start - 1].rstrip(" ")[-1:] != "|"+ and text[start - 1] == " "+ and text[:start - 1].rstrip(" ")[-1:] not in {"|", ""}):start -= 1- pieces.append(segment[cursor:start])+ pieces.append(text[cursor:start])pieces.append(marker)cursor = endcount += 1- pieces.append(segment[cursor:])+ pieces.append(text[cursor:])return "".join(pieces), count++ def _marker_for(self, text: str, position: int) -> str:+ """Pick the omission marker in the script of the line being cut.++ A Chinese user asking about a US name gets English tables, and running+ one marker over the whole document released+ "Suggested entry price(略※) per share." A stretch with neither script+ — a numeric table row — falls back to the user's language, which is+ what the footnote is written in.+ """+ line = ""+ for candidate, start in _lines_with_offsets(text):+ if start <= position <= start + len(candidate):+ line = candidate+ break+ if any("\u3400" <= char <= "\u9fff" for char in line):+ return _REDACTION_MARKER_ZH+ if any(char.isascii() and char.isalpha() for char in line):+ return _REDACTION_MARKER_EN+ return (+ _REDACTION_MARKER_ZH+ if self._user_writes_chinese()+ else _REDACTION_MARKER_EN+ )++ def _release_note(self, removed: int, content: str | None = None) -> str:+ """Explain the redaction to the user, with the observed range.++ ``redacted_release`` returns None before this is reached when the run+ holds no price record, which is the only case in which the summary is+ None — so it is read directly rather than behind an ``or ""`` that+ described a state the caller cannot produce.+ """+ is_zh = self._user_writes_chinese()+ joined = self._observed_range_summary(is_zh, content)+ if is_zh:+ return (+ f"※ 略去 {removed} 处无法与本会话工具数据对上的数值。"+ f"已观测 OHLC 范围:{joined}。"+ "如需买入价,请让我基于已观测的收盘价或均线给出带公式的推导。"+ )+ return (+ f"※ {removed} figure(s) that could not be matched to this session's tool data "+ f"were omitted. Observed OHLC range: {joined}. "+ "For an entry price, ask me to derive one with a visible formula from an "+ "observed close or moving average."+ )diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.pyindex 4baf81c88..085ef2188 100644--- a/agent/tests/test_agent_grounding.py+++ b/agent/tests/test_agent_grounding.py@@ -1340,7 +1340,9 @@ def test_price_validation_ignores_symbol_date_and_quantity_digits(tmp_path: Pathfor draft in ("000543.SZ 截至 8 月 3 日收盘价 8.20 CNY(source: tencent)",- "000543.SZ 买入价 8.20 CNY(100 股成本 820 CNY;source: tencent)",+ "000543.SZ 买入价 8.20 CNY(100 股成本 820 CNY;source: tencent)\n\n"+ "```figures\n8.20 | observed | close | prices\n"+ "820 | derived | 100 × 8.20 | prices\n```","000543.SZ 建议持有 1–4 周,买入价 8.20 CNY(source: tencent)",):result = ledger.validate_final_answer(draft)@@ -1362,11 +1364,13 @@ def test_price_validation_still_rejects_a_quote_outside_observed_range(def test_price_validation_ignores_score_indicator_and_window_digits(tmp_path: Path,) -> None:- """Confidence scores, indicator readings, and lookback windows are not prices (#1001).+ """A conviction score, a window length and a lookback are bare integers.A well-formed verdict line carries a conviction score, the moving-average- windows it cites, and an oscillator reading. Compared against an OHLC range- every one of them contradicts it, which rejected drafts that were correct.+ windows it cites and a horizon. Every one of them used to be compared+ against the OHLC range unless a mask named it — a labelled-score mask, a+ quantity-with-unit mask, an indicator-name mask. None of them is+ measurement-shaped, so none of them is checked now and no mask is needed."""ledger = _screened_ledger(tmp_path)@@ -1377,144 +1381,93 @@ def test_price_validation_ignores_score_indicator_and_window_digits(# The hyphenated English compound the quantity mask used to stall on."000543.SZ 现价 8.20 CNY 距 52-week high 有距离(source: tencent)","000543.SZ 收盘价 8.20 CNY 低于其 20/50/200-day 均线(source: tencent)",- # An indicator reading sharing a clause with a genuine quote.- "000543.SZ 现价 8.20 CNY 而 RSI 46.7(source: tencent)",):result = ledger.validate_final_answer(draft)assert result.valid is True, (draft, result.issues)-def test_price_validation_ignores_formula_variable_digits(tmp_path: Path) -> None:- """A price word used as a formula variable is not an asserted price (#1354).+def test_an_indicator_reading_is_checked_against_the_call_it_names(+ tmp_path: Path,+) -> None:+ """An RSI reading is a number like any other: declared, and then verified.- The gate uses one structural rule, not a catalogue of phrasings: a number- after a price word is a claimed value only when nothing formula-like sits- between them. A closed marker set — comparison/division operators or an- indicator identifier followed by digits — marks the number an operand; an- observation binder ("was", "at", 报收/收于/…) after that marker re-attaches it- to the price word, so "close above SMA50 and was 2500" stays a claim while- "close/SMA50 > 1" claims nothing. An ASCII sentence boundary (" . ") ends- the price word's reach, so a bare year two sentences later is not claimed.+ It used to be masked by NAME — "RSI 46.7" was exempt because "rsi" was in+ a list — so a fabricated oscillator reading was never checked at all. It is+ measurement-shaped, so it must be declared; a ``ref`` naming the call that+ produced it scopes the check to that call's own results."""ledger = _screened_ledger(tmp_path)+ ledger.ingest_tool_result(+ tool_name="technical_indicators",+ arguments={"symbol": "000543.SZ"},+ result=json.dumps(+ {"ok": True, "symbol": "000543.SZ", "indicators": {"rsi_14": 46.7}}+ ),+ call_id="ti1",+ success=True,+ )- for draft in (- # Division + comparison: window and threshold, not a price.- "000543.SZ close/SMA50 > 1 时买入(source: tencent)",- # Signal value after a signal word / arrow / 触发.- "000543.SZ close acima da EMA30 dispara sinal +1(source: tencent)",- "000543.SZ close above EMA20 -> +1(source: tencent)",- "000543.SZ 收盘价上穿MA20 触发 +1 信号(source: tencent)",- # Plain comparison against a level, not a quote.- "000543.SZ close > 1 时买入(source: tencent)",- # Indicator reading with a directional connective.- "000543.SZ close/SMA50 > 1 and RSI below 30(source: tencent)",- # Colon after the signal word (ASCII '.' is not a clause separator,- # so "Sinal: +1" can share a clause with the price word).- "000543.SZ close acima da EMA30. Sinal: +1(source: tencent)",- # Indicator identifier + digits between the price word and the number,- # even when the operator is spelled out in prose.- "000543.SZ close vs SMA20 maior que 1(source: tencent)",- "000543.SZ close minus SMA20 fallen below 0(source: tencent)",- ):- result = ledger.validate_final_answer(draft)- assert result.valid is True, (draft, result.issues)+ grounded = ledger.validate_final_answer(+ "000543.SZ 现价 8.20 CNY 而 RSI 46.7(source: tencent)\n\n"+ "```figures\n"+ "8.20 | observed | close | prices\n"+ "46.7 | observed | rsi_14 | ti1\n"+ "```"+ )+ assert grounded.valid is True, grounded.issues- # Strict-narrowing bar: the formula language must not launder an observed- # value. Verified adversarially; each shape stays a claim.- for launder in (- # no operator, no indicator digits: the plain claim- "000543.SZ close was 2500(source: tencent)",- # digit-carrying connector bridging to an indicator- "000543.SZ close was 2500 and SMA50 2450(source: tencent)",- # observation verb trailing the formula in the same clause- "000543.SZ close above SMA50 and was 2500 yesterday(source: tencent)",- # at-attached level trailing the formula- "000543.SZ close above SMA50 at 2450(source: tencent)",- # equality claim, not a formula- "000543.SZ close = 2500(source: tencent)",- # second price word after a comma stays gated- "000543.SZ close above SMA50, and closed at 2500 yesterday(source: tencent)",- # Chinese observation syntax- "000543.SZ 收盘价报收 2500(source: tencent)",- # multi-digit value after a signal word is a price, not a signal- "000543.SZ close signal 2500(source: tencent)",- # "above" with a price word is a claim, not an indicator reading- "000543.SZ close above 2500(source: tencent)",- ):- result = ledger.validate_final_answer(launder)- assert result.valid is False, launder- assert "numeric_claim_conflict" in {issue["code"] for issue in result.issues}---def test_direct_price_values_structural_rule() -> None:- """The structural rule decides operand vs. claim at the number level (#1354)."""- def extract(text: str) -> list[float]:- """Values only; the production path also reads each figure's offset."""- return [value for value, _, _ in GroundingLedger._direct_price_values(text)]-- # Formula operands — a marker between the price word and the number.- for text in (- "close/SMA50 > 1.0",- "close acima da EMA30 dispara sinal +1",- "收盘价上穿MA20 触发 +1 信号",- "close/SMA50 > 1 and RSI below 30",- "close vs SMA20 maior que 1",- "close minus SMA20 fallen below 0",- # CJK-adjacent indicator (no ASCII space): the marker's \b must not- # treat a CJK letter as a word character, or 上穿MA20 is invisible.- "收盘价上穿SMA20 2500",- ):- assert extract(text) == [], text- # Observed values — no marker, or an observation binder after the marker.- assert extract("close was 2500") == [2500.0]- assert extract("close above 2500") == [2500.0]- assert extract("close = 2500") == [2500.0]- assert extract("close above SMA50 and was 2500 yesterday") == [2500.0]- assert extract("close above SMA50 at 2450") == [2450.0]- assert extract("收盘价报收 2500") == [2500.0]- # Sentence boundary: the price word cannot reach a later sentence.- assert extract("close was 210. In 2024 the market rallied") == [210.0]- assert extract("close. Sinal: 2500") == []+ invented = ledger.validate_final_answer(+ "000543.SZ 现价 8.20 CNY 而 RSI 71.2(source: tencent)\n\n"+ "```figures\n"+ "8.20 | observed | close | prices\n"+ "71.2 | observed | rsi_14 | ti1\n"+ "```"+ )+ assert invented.valid is False+ assert [issue["value"] for issue in invented.issues] == ["71.2"]def test_price_validation_ignores_short_dates_and_percent_ranges(tmp_path: Path,) -> None:- """A year-less date and a percentage range are not prices (#983).+ """A year-less date is a pair of bare integers; a percentage is declared.- Taken from the trace attached to #983: "8/5 收盘 5.97" contributed 8 and 5,- and "1–2%" contributed its lower bound, because the percent tail check only- masks the number the sign touches.+ Taken from the trace attached to #983: "8/5 收盘 5.97" contributed 8 and 5+ as candidate prices. Neither is measurement-shaped, so neither is checked+ and the short-date mask is gone. The percentage beside it IS+ measurement-shaped and states a distance the run did not observe, so it is+ declared rather than masked."""ledger = _screened_ledger(tmp_path)for draft in ("000543.SZ 8/5 收盘价 8.20 CNY(source: tencent)",- "000543.SZ 现价 8.20 CNY,距阻力位仅 1–2%(source: tencent)",- "000543.SZ 现价 8.20 CNY,距阻力位仅 1-2%(source: tencent)",+ "000543.SZ 现价 8.20 CNY,距阻力位仅 1–2%(source: tencent)\n\n"+ "```figures\n8.20 | observed | close | prices\n"+ "1% | count | 区间下界\n2% | count | 区间上界\n```",):result = ledger.validate_final_answer(draft)assert result.valid is True, (draft, result.issues)-def test_numbers_without_dates_or_percent_masks_cjk_glued_iso_dates() -> None:- """An ISO date running into CJK text is one date, not three prices (#1122).+def test_an_undeclared_percentage_is_reported_not_masked(tmp_path: Path) -> None:+ """The lower side: a percentage with no declaration is named, not ignored.- ``\b`` is Unicode-aware, so CJK letters count as word characters and- ``(2026-07-14最低)`` had no boundary after ``14`` -- the date survived and- contributed 2026/7/14 as candidate prices. ``re.ASCII`` restores the byte- boundary so the whole date masks while a genuine quote beside it stays.+ A percentage-range mask made "距阻力位仅 1–2%" invisible, and with it every+ other percentage written the same way. The figure is now reported by value+ so the correction prompt can ask for the one declaration that settles it."""- assert (- GroundingLedger._numbers_without_dates_or_percent("若跌破观测支撑位0.980 CNY (2026-07-14最低)")- == []- )- assert (- GroundingLedger._numbers_without_dates_or_percent("收盘价 8.20 CNY 自2026-07-14以来最低")- == [8.2]+ ledger = _screened_ledger(tmp_path)++ result = ledger.validate_final_answer(+ "000543.SZ 现价 8.20 CNY,年化波动率 41%(source: tencent)\n\n"+ "```figures\n8.20 | observed | close | prices\n```")+ assert result.valid is False+ assert [issue["code"] for issue in result.issues] == ["figure_undeclared"]+ assert [issue["value"] for issue in result.issues] == ["41%"]+def test_iso_date_running_into_cjk_text_is_still_masked(tmp_path: Path) -> None:"""The end-to-end gate no longer rejects a correct report over a glued date (#1122)."""@@ -1540,17 +1493,17 @@ def test_short_date_mask_does_not_swallow_a_plain_ratio(tmp_path: Path) -> None:assert result.valid is Falseassert [issue["code"] for issue in result.issues] == ["numeric_claim_conflict"]- assert [issue["value"] for issue in result.issues] == [42.0]+ assert [issue["value"] for issue in result.issues] == ["42.00"]-def test_masked_window_does_not_shield_a_wrong_quote_in_the_same_clause(+def test_a_bare_integer_beside_a_wrong_quote_does_not_shield_it(tmp_path: Path,) -> None:- """The new masks are span-local: a bad quote beside one is still caught (#1001).+ """The lower side of the shape rule (#1001).- This is the lower side of the guard. Masking ``52-week`` must remove only- the window length; a contradicted price in the same clause has to survive- the mask and reject the draft, or the fix would have bought precision by+ Leaving a window length or a conviction score unchecked must remove only+ that number; a contradicted price in the same sentence has to survive and+ reject the draft, or the relaxation would have bought precision bysilencing the check it exists to run."""ledger = _screened_ledger(tmp_path)@@ -1558,11 +1511,11 @@ def test_masked_window_does_not_shield_a_wrong_quote_in_the_same_clause(for draft in ("000543.SZ 52-week high 之下,收盘价 42.00 CNY(source: tencent)","000543.SZ CONFIDENCE: 6 REASON: 收盘价 42.00 CNY(source: tencent)",- "000543.SZ RSI 46.7,收盘价 42.00 CNY(source: tencent)",):result = ledger.validate_final_answer(draft)assert result.valid is False, draftassert [issue["code"] for issue in result.issues] == ["numeric_claim_conflict"], draft+ assert [issue["value"] for issue in result.issues] == ["42.00"], draftdef test_screening_run_reaches_a_final_answer_through_the_agent_loop(@@ -1594,7 +1547,9 @@ def test_screening_run_reaches_a_final_answer_through_the_agent_loop(assert market.calls == 1validation = agent._grounding.validate_final_answer(- "000543.SZ 买入价 8.20 CNY(100 股成本 820 CNY;source: tencent)"+ "000543.SZ 买入价 8.20 CNY(100 股成本 820 CNY;source: tencent)\n\n"+ "```figures\n8.20 | observed | close | prices\n"+ "820 | derived | 100 × 8.20 | prices\n```")assert validation.valid is True, validation.issues@@ -1657,229 +1612,6 @@ def test_a_date_that_names_a_different_day_is_still_unavailable(tmp_path: Path)assert "numeric_claim_unavailable" in {issue["code"] for issue in result.issues}-# ----------------------------------------------------------------------------# #983: a trading plan quotes levels it does not claim to have observed.-#-# The committee report attached to that issue was refused for its own entry-# triggers and target zones. With no price evidence yet in the parent session-# they came back as numeric_claim_unavailable; once the run fetched prices the-# same numbers came back as numeric_claim_conflict. One false positive, two-# codes.-# -----------------------------------------------------------------------------_PLAN_LEVELS_FROM_983 = [- "- **转多信号:** 收盘 ≥6.45 且量 ≥35M手",- "- **转空强化:** 收盘 <5.36 且 3 日不收复 → 年线 4.63 成目标区",- "| B 破位空 | 任意收盘 <5.36 | 收盘 ≥5.75 且量 ≥20M手 |",- "目标位 6.80,止损 5.20",- "若收盘 5.36 则减仓",- "target price 6.80 with stop-loss 5.20",-]--[email protected]("segment", _PLAN_LEVELS_FROM_983, ids=range(len(_PLAN_LEVELS_FROM_983)))-def test_plan_levels_are_not_read_as_observed_price_claims(segment: str) -> None:- """A trigger, a target and a hypothesis assert nothing about observed data."""- assert GroundingLedger._numbers_without_dates_or_percent(segment) == []---# The other side of the same guard. Every entry here is an assertion about what-# the instrument did, and each must survive the mask above — otherwise the-# relaxation is a way to state a price without being checked.-_ASSERTIONS_THAT_MUST_STAY_CHECKED = [- ("8/5 收盘 5.97", [5.97]),- ("现价 5.97", [5.97]),- ("收盘价为 6.03", [6.03]),- ("the close was 6.03", [6.03]),- # Span-local: the target is masked, the quote beside it is not.- ("现价 5.97,目标位 6.45", [5.97]),- # A conditional opener must not reach back over a quote already made.- ("收盘 6.03,若跌破 5.36 减仓", [6.03]),- ("开盘 6.80 最高 7.18 最低 6.68", [6.80, 7.18, 6.68]),-]--- "segment,expected",- _ASSERTIONS_THAT_MUST_STAY_CHECKED,- ids=[c[0][:24] for c in _ASSERTIONS_THAT_MUST_STAY_CHECKED],-)-def test_plan_level_mask_leaves_observed_quotes_checked(- segment: str, expected: list[float],-) -> None:- assert GroundingLedger._numbers_without_dates_or_percent(segment) == expected---# A currency token between the anchor and the number used to break every-# prospective branch: "收盘 <$2.86" left 2.86 to be compared against observed-# OHLC, "目标位 $6.80" left 6.8, and "trigger at $119.68" left 119.68. These-# are levels, not observed quotes, so each must mask entirely.-_CURRENCY_PREFIXED_PLAN_LEVELS = [- "收盘 <$2.86",- "目标位 $6.80,止损位 C$5.20",- "trigger at $119.68",- "支撑位 $190.12",- "target price of $6.80",- "收盘 ≥ $135 且低点 > $119.68",-]--- "segment", _CURRENCY_PREFIXED_PLAN_LEVELS, ids=range(len(_CURRENCY_PREFIXED_PLAN_LEVELS))-)-def test_currency_prefixed_plan_levels_are_not_read_as_observed_prices(segment: str) -> None:- """A currency-prefixed trigger or target is prospective, not observed."""- assert GroundingLedger._numbers_without_dates_or_percent(segment) == []---# A historical reference names a price the instrument once traded at. The-# SPCX.US weekly plan quoted "6/16 ATH 225.64" next to the 8/12 high 149.60;-# 225.64 fell outside the session's observed OHLC range (105.11–149.6) and was-# rejected as a conflict even though it is a reference, not a current quote.-_REFERENCE_LEVEL_SEGMENTS = [- ("8/12 高 149.60 为 6/16 ATH 225.64 以来最高", [149.60]),- ("8/12 高 149.60 为 6/16 历史高点 225.64 以来最高", [149.60]),- ("8/12 高 149.60 为 6/16 all-time high 225.64 以来最高", [149.60]),- ("52W 高 543.14", []),- ("52-week low of $190.12", []),- ("52W low (C$7.27)", []),- ("历史最低 $60.82", []),- ("ATH (C$7.31)", []),-]--- "segment,expected",- _REFERENCE_LEVEL_SEGMENTS,- ids=[c[0][:28] for c in _REFERENCE_LEVEL_SEGMENTS],-)-def test_reference_levels_are_not_read_as_observed_price_claims(- segment: str, expected: list[float],-) -> None:- """An ATH/52-week/historical extreme is a reference, not a current quote."""- assert GroundingLedger._numbers_without_dates_or_percent(segment) == expected---# A validation report cites a plan file by line number ("~line 206",-# "第 206 行"). The number is a document location, not a price, and was-# compared against observed OHLC as a claim before this mask existed.-_LINE_REFERENCE_SEGMENTS = [- "**文档 ~line 206「8/12 高 149.60 为 6/16 ATH 225.64 以来最高」不成立",- "line 206",- "lines 206-208",- "第 206 行",- "第 206–208 行",- "行 206",-]--- "segment", _LINE_REFERENCE_SEGMENTS, ids=range(len(_LINE_REFERENCE_SEGMENTS))-)-def test_line_number_references_are_not_read_as_price_claims(segment: str) -> None:- """A line citation is a document location, not an observed price."""- if segment.startswith("**文档"):- # The quoted 149.60 beside the line citation stays checked.- assert GroundingLedger._numbers_without_dates_or_percent(segment) == [149.6]- else:- assert GroundingLedger._numbers_without_dates_or_percent(segment) == []---# Validation summaries count findings: "1 项事实错误", "2 项不一致", and-# "16 个交易日" are count nouns, not prices. The count survived extraction-# and was rejected against the observed OHLC range before 项/个交易日 joined-# the quantity units.-_COUNT_NOUN_SEGMENTS = [- ("- ❌ **1 项事实错误**:", []),- ("⚠️ **2 项不一致**", []),- ("3 项", []),- ("16 个交易日", []),- # 149.60 is masked here too: "高点高于 149.60" is a comparison level.- ("6/17–7/10 有 16 个交易日高点高于 149.60", []),-]--- "segment,expected",- _COUNT_NOUN_SEGMENTS,- ids=[c[0][:22] for c in _COUNT_NOUN_SEGMENTS],-)-def test_count_nouns_are_not_read_as_price_claims(- segment: str, expected: list[float],-) -> None:- """项/个交易日 counts are quantities, not prices."""- assert GroundingLedger._numbers_without_dates_or_percent(segment) == expected---_SINCE_REFERENCE_SEGMENTS = [- ("正确为 7/10(150.57)以来最高", []),- ("收 146.15 为 7/9(收 152.16)以来最高", [146.15]),- ("highest since 7/10 (150.57)", []),- # The current bar's own high is not a since-reference and stays checked.- ("8/12 高 149.60 为 6/16 ATH 225.64 以来最高", [149.6]),-]--- "segment,expected",- _SINCE_REFERENCE_SEGMENTS,- ids=[c[0][:24] for c in _SINCE_REFERENCE_SEGMENTS],-)-def test_since_references_are_not_read_as_observed_price_claims(- segment: str, expected: list[float],-) -> None:- """A date-anchored "highest since" value is a reference, not a quote."""- assert GroundingLedger._numbers_without_dates_or_percent(segment) == expected---_NUMBERED_HEADING_SEGMENTS = [- "### 6. 关键价位/旁证核验",- "## 12. 结论",- "# 3. 身份与数据源",- "### 8/13 周中判定",- # The section number masks; the observed quote beside it stays checked.- ("### 6. 8/12 高 149.60 为 6/16 ATH 以来最高", [149.6]),-]--- "segment", _NUMBERED_HEADING_SEGMENTS, ids=range(len(_NUMBERED_HEADING_SEGMENTS))-)-def test_numbered_headings_are_not_read_as_price_claims(segment: str) -> None:- """A markdown heading number is a section index, not a price."""- if isinstance(segment, tuple):- segment, expected = segment- assert GroundingLedger._numbers_without_dates_or_percent(segment) == expected- else:- assert GroundingLedger._numbers_without_dates_or_percent(segment) == []---_RATIO_AND_FX_SEGMENTS = [- ("TO 报价实际是按 6:1 平价锚定的", []),- ("25/25 行 OHLCV、25/25 项派生百分比、7/7 日 CDR 6:1 折算", []),- ("远小于当前 USD/CAD≈1.36 的量级", []),- ("汇率 1.36", []),- # `EUR/USD` is this project's canonical forex symbol, so an asserted pair- # rate is a quote and stays checked; only an approximated conversion basis- # is masked. Masking both would let an invented FX rate through the gate.- ("usd/cad=1.36", [1.36]),- ("USD/CAD 1.36", [1.36]),- ("USD/CAD ≈ 1.36", []),-]--- "segment,expected",- _RATIO_AND_FX_SEGMENTS,- ids=[c[0][:24] for c in _RATIO_AND_FX_SEGMENTS],-)-def test_ratios_and_fx_rates_are_not_read_as_price_claims(- segment: str, expected: list[float],-) -> None:- """A conversion ratio or forex rate is not an instrument quote."""- assert GroundingLedger._numbers_without_dates_or_percent(segment) == expected--def test_plan_level_mask_does_not_shield_a_wrong_quote_end_to_end(tmp_path: Path) -> None:"""The end-to-end gate still rejects a fabricated quote beside a plan level."""ledger = _screened_ledger(tmp_path)@@ -1893,15 +1625,37 @@ def test_plan_level_mask_does_not_shield_a_wrong_quote_end_to_end(tmp_path: Pathdef test_plan_level_alone_reaches_a_valid_answer(tmp_path: Path) -> None:- """A plan stated without quoting an observed price passes the numeric gate."""+ """A proposed level passes inside the observed range, or with a derivation.++ This replaces the prospective-level mask, which exempted any number a+ target/stop/trigger word introduced and therefore exempted any number at+ all once the model used the right word. A proposed level is now checked:+ it is anchored either by the range this session actually observed, or by+ arithmetic on it.+ """ledger = _screened_ledger(tmp_path)- result = ledger.validate_final_answer(- "000543.SZ 收盘价 8.20 CNY(source: tencent)。"- "转多信号:收盘 ≥9.10;转空强化:收盘 <7.40 且 3 日不收复 → 目标位 6.90。"+ inside_range = ledger.validate_final_answer(+ "000543.SZ 收盘价 8.20 CNY(source: tencent)。转多信号:收盘 ≥8.40。\n\n"+ "```figures\n8.20 | observed | close | prices\n"+ "8.40 | proposed | 转多触发\n```")+ assert inside_range.valid is True, inside_range.issues- assert result.valid is True, result.issues+ derived_outside = ledger.validate_final_answer(+ "000543.SZ 收盘价 8.20 CNY(source: tencent)。目标位 9.02。\n\n"+ "```figures\n8.20 | observed | close | prices\n"+ "9.02 | proposed | 8.20 × 1.10 | prices\n```"+ )+ assert derived_outside.valid is True, derived_outside.issues++ unanchored = ledger.validate_final_answer(+ "000543.SZ 收盘价 8.20 CNY(source: tencent)。目标位 42.00。\n\n"+ "```figures\n8.20 | observed | close | prices\n"+ "42.00 | proposed | 目标\n```"+ )+ assert unanchored.valid is False+ assert [issue["reason"] for issue in unanchored.issues] == ["outside_observed_range"]def _spcx_us_ledger(tmp_path: Path) -> GroundingLedger:@@ -1983,28 +1737,75 @@ def _spcx_us_ledger(tmp_path: Path) -> GroundingLedger:def test_reference_level_and_currency_thresholds_pass_end_to_end(tmp_path: Path) -> None:- """The SPCX.US verdict prose passes once references and thresholds mask."""+ """The SPCX.US verdict prose passes once its figures are declared.++ Every number here used to need a mask of its own: an ATH mask for 225.64,+ a currency-prefixed-threshold mask for $135 and $119.68, a since-reference+ mask for the whole clause. The historical extreme is now a cited figure —+ the run never observed June — and the thresholds are bare integers or+ proposed levels.+ """ledger = _spcx_us_ledger(tmp_path)result = ledger.validate_final_answer("SPCX.US 8/10 收 138.74 USD、8/12 高 149.60 USD(source: yahoo)。""8/12 高 149.60 为 6/16 ATH 225.64 以来最高;"- "8/10 收盘 138.74 ≥ $135 且 ≥ $119.68 触发成立。"+ "8/10 收盘 138.74 高于 $135.00 且高于 $119.68。\n\n"+ "```figures\n"+ "138.74 | observed | close 2026-08-10 | prices\n"+ "149.60 | observed | high 2026-08-12 | prices\n"+ "225.64 | cited | 6/16 盘中历史高点,本会话未取\n"+ "135.00 | proposed | 阈值\n"+ "119.68 | proposed | 阈值\n"+ "```")assert result.valid is True, result.issues+def test_a_historical_extreme_may_not_pose_as_an_observed_print(+ tmp_path: Path,+) -> None:+ """The lower side: 225.64 is admissible as a citation, never as a quote.++ The reference-level mask exempted it from the price comparison entirely,+ which also exempted anything else an "ATH"/"52W" spelling introduced. The+ same number declared observed is now compared against the run's own bars+ and rejected.+ """+ ledger = _spcx_us_ledger(tmp_path)++ result = ledger.validate_final_answer(+ "SPCX.US 8/12 高 149.60 USD(source: yahoo),历史高点 225.64 USD。\n\n"+ "```figures\n"+ "149.60 | observed | high | prices\n"+ "225.64 | observed | ATH | prices\n"+ "```"+ )++ assert result.valid is False+ assert [issue["value"] for issue in result.issues] == ["225.64"]+ assert [issue["reason"] for issue in result.issues] == ["not_in_referenced_call"]++def test_validation_summary_with_counts_and_line_cites_passes_end_to_end(tmp_path: Path,) -> None:- """A validation verdict naming counts and line citations passes the gate."""+ """A verdict naming counts and line citations passes with no mask at all.++ "1 项事实错误", "~line 206" and "16 个交易日" each had a mask written for+ them. All three are bare integers, so all three are simply not checked.+ """ledger = _spcx_us_ledger(tmp_path)result = ledger.validate_final_answer("SPCX.US 核验(USD, source: yahoo):❌ 1 项事实错误 — ""文档 ~line 206「8/12 高 149.60 为 6/16 ATH 以来最高」不成立,"- "6/17–7/10 有 16 个交易日高点高于 149.60,正确为 7/10(150.57)以来最高。"+ "6/17–7/10 有 16 个交易日高点高于 149.60,正确为 7/10(150.57)以来最高。\n\n"+ "```figures\n"+ "149.60 | observed | high 2026-08-12 | prices\n"+ "150.57 | cited | 7/10 盘中高点,本会话未取\n"+ "```")assert result.valid is True, result.issues@@ -2371,10 +2172,10 @@ def test_fullwidth_parentheses_do_not_split_symbol_from_figure(def test_unsourced_symbol_without_a_figure_stays_silent(tmp_path: Path) -> None:"""#1260 guard arm: figure co-presence is what the gate checks.- The regression test above pins that the gate fires when symbol and figure- share a clause. This arm pins the inverse: an unsourced symbol with NO- nearby figure must not fire unsourced_symbol_figures, so the gate's- figure-presence guard (_numbers_without_dates_or_percent) cannot be+ The regression test above pins that the gate fires when a symbol and a+ figure share a line. This arm pins the inverse: an unsourced symbol with+ NO measurement-shaped figure beside it must not fire+ unsourced_symbol_figures, so the check's figure-presence guard cannot bedropped without this test failing."""ledger = GroundingLedger(@@ -2629,182 +2430,38 @@ def test_markdown_list_marker_mask_does_not_weaken_contradiction_check(codes = [issue["code"] for issue in result.issues]assert "numeric_claim_conflict" in codes- assert [issue["value"] for issue in result.issues if issue["code"] == "numeric_claim_conflict"] == [42.0]--- "segment",- [- "买入股数 = 初始资金 × (1 - 单边成本率) / 期初收盘价",- "期末市值 = 买入股数 × 期末收盘价 × (1 - fee_rate)",- "net proceeds = shares * closing price * (1 - transaction_rate)",- ],-)-def test_rate_formula_identity_is_not_read_as_a_price(segment: str) -> None:- """The identity in ``1 - rate`` is arithmetic, not a one-unit quote."""- assert GroundingLedger._numbers_without_dates_or_percent(segment) == []---def test_rate_formula_mask_does_not_hide_an_observed_one_unit_quote() -> None:- """A genuine price of 1 remains checked outside a rate expression."""- assert GroundingLedger._numbers_without_dates_or_percent("closing price = 1 CNY") == [1.0]+ assert [+ issue["value"] for issue in result.issues+ if issue["code"] == "numeric_claim_conflict"+ ] == ["42.00"]-def test_in_text_decimal_survives_list_marker_mask(+def test_in_text_decimal_is_never_read_as_a_list_marker(tmp_path: Path,) -> None:- """An ordinary decimal like 1.5 (digit after the dot) is never a list marker (#BUGS-1).+ """An ordinary decimal like 1.5 (digit after the dot) is not an ordinal.- The mask only matches a digit run at line start followed by "." or ")" and- whitespace, so a genuine in-text decimal must remain a candidate price.+ The line-leading ordinal exemption requires punctuation followed by+ whitespace, so a genuine in-text decimal stays a figure the gate checks —+ and a proposed level far under the observed range is rejected rather than+ swallowed by the exemption."""ledger = _screened_ledger(tmp_path)- symbol = "000543.SZ"-- for draft in (- f"{symbol} 目标价 1.5 CNY,收盘价 8.20 CNY(source: tencent)",- f"{symbol} 变动 0.03 CNY,收盘价 8.20 CNY(source: tencent)",- ):- result = ledger.validate_final_answer(draft)- assert result.valid is True, (draft, result.issues)---def test_order_level_prices_are_not_observed_quotes(tmp_path: Path) -> None:- """GTC order limits (100 @ $3.50) are prospective, not observed prices.-- Regression for the RXRX run: the draft "两档 GTC (100 @ $3.50 / 100 @ $4.00)- 均未触发 (周高 $3.42 < $3.50)" was rejected with numeric_claim_conflict for- 100, 3.5 and 4.0 against the observed OHLC range. Order levels are levels,- like targets/stops, and share counts are quantities - neither is a claim- about an observed quote.- """- raw = tmp_path / "data" / "raw"- raw.mkdir(parents=True)- (raw / "RXRX_US.csv").write_text(- "Date,Open,High,Low,Close\n"- "2026-08-07,3.25,3.26,3.18,3.20\n"- "2026-08-08,3.10,3.42,3.05,3.35\n",- encoding="utf-8",- )- ledger = GroundingLedger(- run_dir=tmp_path,- user_message="请分析 RXRX.US 并更新周报",- )- ledger.ingest_tool_result(- tool_name="search_symbol",- arguments={"query": "RXRX"},- result=json.dumps({- "ok": True,- "data": {- "candidates": [- {"symbol": "RXRX.US", "name": "Recursion Pharmaceuticals", "market": "us",- "type": "equity", "exchange": "NMS", "source": "yahoo"},- ]- },- }),- call_id="lock1",- success=True,- )-- answer = (- "RXRX.US(yahoo,USD)本周高 $3.42。订单: 两档 GTC (100 @ $3.50 / 100 @ $4.00) "- "均未触发 (周高 $3.42 < $3.50) — 价格推断未成交。"- )- result = ledger.validate_final_answer(answer)- assert result.valid is True, result.issues- # A genuinely fabricated close is still rejected.- fabricated = ledger.validate_final_answer(- "RXRX.US(yahoo,USD)本周高 $3.42。另: 收盘 2.50 已确认。"- )- assert fabricated.valid is False- assert any(- issue["code"] == "numeric_claim_conflict" for issue in fabricated.issues- )---def test_dash_form_trading_day_is_a_date_but_a_price_range_is_not() -> None:- """A report writes the day as "08-10(一)"; a target still writes "10-20 元".-- The dash carries both meanings, so the mask splits them: a zero-padded- month reads as a date on its own, October through December need a weekday- or session marker, and a range with neither stays checkable.- """- extract = GroundingLedger._numbers_without_dates_or_percent-- assert extract("08-10(一) 收盘 8.20 CNY") == [8.2]- assert extract("08-10盘中最低 8.20 CNY") == [8.2]- assert extract("08-10 close 8.20 USD") == [8.2]- assert extract("10-20(周一)盘中 8.20 CNY") == [8.2]-- # No date marker and no zero-padded month: an ordinary quoted range, and- # masking it would stop checking a claim the ledger exists to check.- assert extract("区间 8-10 元") == [8.0, 10.0]- assert extract("跌 12-25 元") == [12.0, 25.0]---def test_a_level_stated_as_a_range_masks_both_bounds(tmp_path: Path) -> None:- """Masking only the lower bound left a negative upper bound behind.-- The separator touches the second number, so "目标价 10-20 元" used to- reduce to "-20" — and a negative price is outside every OHLC window, which- made a correct draft impossible to pass rather than merely unchecked.- """- extract = GroundingLedger._numbers_without_dates_or_percent-- for draft in ("目标价 10-20 元", "支撑位 8-10 元", "阻力位 12.0~13.5", "52周高 15.0-16.0"):- assert extract(draft) == [], draft-- # A single-value level is unchanged, and an observed quote beside a ranged- # level is still extracted and checked.- assert extract("止损位 7.5 元") == []- assert extract("目标价 10-20 元,现价 8.20 CNY") == [8.2]-- ledger = _screened_ledger(tmp_path)result = ledger.validate_final_answer(- "000543.SZ 收盘价 8.20 CNY,目标价 10-20 元(source: tencent)"+ "000543.SZ 目标价 1.5 CNY,收盘价 8.20 CNY(source: tencent)\n\n"+ "```figures\n8.20 | observed | close | prices\n"+ "1.5 | proposed | 目标\n```")- assert result.valid is True, result.issues---def test_an_order_line_is_an_instruction_not_an_observation(tmp_path: Path) -> None:- """"100 @ $3.50" states where a limit sits; 100 was never a price at all.-- A GTC summary in a weekly update was read as two observed quotes and- rejected against the session's range, which is the same category error the- target/stop masks already prevent.- """- extract = GroundingLedger._numbers_without_dates_or_percent-- for draft in (- "GTC 100 @ $3.50",- "buy 100 @ $3.50 GTC",- "挂单 100 股 @ 4.00",- "限价单 100 @ 3.50",- "委托价 3.50",- ):- assert extract(draft) == [], draft-- # 买入价/卖出价 stay OUT of the label set: in running prose they name the- # price a report says it observed, and masking them let an ungrounded- # quote through the gate.- assert extract("买入价 0.881") == [0.881]-- # There is no bare "@ <price>" branch either. Dates are masked before this- # runs, so an observed close written "2026-08-10 @ 8.20" would reach the- # order mask as "@ 8.20" and stop being checked at all.- assert extract("收盘 2026-08-10 @ 8.20") == [8.2]-- # An observed quote standing beside an order line is still checked, and a- # bare handle carries no price to mask.- assert extract("现价 8.20 CNY,挂单 100 @ 8.50") == [8.2]- assert extract("联系 @user 获取") == []+ assert result.valid is False+ assert [issue["value"] for issue in result.issues] == ["1.5"]- ledger = _screened_ledger(tmp_path)- result = ledger.validate_final_answer(- "000543.SZ 收盘价 8.20 CNY,挂单 100 股 @ 12.00(source: tencent)"+ in_range = ledger.validate_final_answer(+ "000543.SZ 变动 0.03 CNY,收盘价 8.20 CNY(source: tencent)\n\n"+ "```figures\n8.20 | observed | close | prices\n"+ "0.03 | derived | 8.50 - 8.47 | prices\n```")- assert result.valid is True, result.issues+ assert in_range.valid is True, in_range.issuesdef test_a_report_style_date_cell_still_matches_its_evidence_row() -> None:@@ -2962,9 +2619,7 @@ def test_backtest_metrics_rejected_when_analysis_tool_failed()assert bad.valid is False, bad.issues- assert any(- issue["code"] == "analysis_claim_unavailable" for issue in bad.issues- )+ assert {issue["code"] for issue in bad.issues} == {"numeric_claim_unavailable"}def test_backtest_metrics_rejected_when_no_analysis_result(@@ -2982,9 +2637,10 @@ def test_backtest_metrics_rejected_when_no_analysis_result()assert bad.valid is False, bad.issues- assert any(- issue["code"] == "analysis_claim_unavailable" for issue in bad.issues- )+ assert {issue["code"] for issue in bad.issues} == {"numeric_claim_unavailable"}+ assert [issue["value"] for issue in bad.issues] == [+ "18.2%", "-9.4%", "1.21", "58%",+ ]def test_backtest_metrics_accepted_after_successful_backtest(@@ -3103,23 +2759,31 @@ def test_partially_unsupported_analysis_metrics_are_rejected()assert bad.valid is False, bad.issues- assert any(- issue["code"] == "analysis_claim_unavailable" for issue in bad.issues- )+ assert [issue["value"] for issue in bad.issues] == ["-9.4%"]++def test_forecast_probability_is_declared_not_phrased(tmp_path: Path) -> None:+ """A forecast is a role the model declares, not a word it writes.-def test_forecast_probability_is_not_a_measured_claim(tmp_path: Path) -> None:- """#1336 gates measured facts, not forward-looking forecasts."""+ "预计" used to buy a clause-wide exemption for free, so any measured+ metric written after it went unchecked. The figure must now be declared+ ``count`` — the role for a number this run does not claim to have measured+ — and an undeclared one is reported.+ """ledger = GroundingLedger(run_dir=tmp_path,user_message="明天市场会怎么样",)- good = ledger.validate_final_answer(- "预计明日上涨概率 70%,波动率可能放大。"+ declared = ledger.validate_final_answer(+ "预计明日上涨概率 70%,波动率可能放大。\n\n"+ "```figures\n70% | count | 主观判断,非本会话测得\n```")+ assert declared.valid is True, declared.issues- assert good.valid is True, good.issues+ undeclared = ledger.validate_final_answer("预计明日上涨概率 70%,波动率可能放大。")+ assert undeclared.valid is False+ assert [issue["value"] for issue in undeclared.issues] == ["70%"]def test_valid_price_does_not_launder_unsupported_analysis_metric(@@ -3145,7 +2809,7 @@ def test_valid_price_does_not_launder_unsupported_analysis_metric()assert result.valid is False, result.issues- assert any(issue["code"] == "analysis_claim_unavailable" for issue in result.issues)+ assert [issue["value"] for issue in result.issues] == ["18.2%"]def test_successful_backtest_only_supports_metrics_in_its_artifact(@@ -3197,23 +2861,24 @@ def test_skipped_analysis_result_does_not_authorize_metrics(tmp_path: Path) -> Nassert result.valid is False, result.issues-def test_integer_historical_window_claim_is_rejected(tmp_path: Path) -> None:- """Categorical claims about all historical windows need evidence too."""- ledger = GroundingLedger(run_dir=tmp_path, user_message="分析策略")+def test_analysis_definition_is_declared_not_phrased(tmp_path: Path) -> None:+ """A threshold convention is a citation, not a measurement of this session.- result = ledger.validate_final_answer("所有历史 12 个月窗口均实现正收益。")-- assert result.valid is False, result.issues- assert any(issue["code"] == "analysis_claim_unavailable" for issue in result.issues)---def test_analysis_definition_is_not_rejected(tmp_path: Path) -> None:- """A threshold definition is not a measured result from this session."""+ "通常被认为" used to exempt the clause outright. The convention is now+ stated as what it is — a figure taken from outside this run — and an+ undeclared one is reported instead of being waved through by its framing.+ """ledger = GroundingLedger(run_dir=tmp_path, user_message="什么是夏普比率?")- result = ledger.validate_final_answer("夏普比率大于 1.0 通常被认为较好。")+ declared = ledger.validate_final_answer(+ "夏普比率大于 1.0 通常被认为较好。\n\n"+ "```figures\n1.0 | cited | 行业惯例阈值\n```"+ )+ assert declared.valid is True, declared.issues- assert result.valid is True, result.issues+ undeclared = ledger.validate_final_answer("夏普比率大于 1.0 通常被认为较好。")+ assert undeclared.valid is False+ assert [issue["value"] for issue in undeclared.issues] == ["1.0"]def test_forecast_table_cell_does_not_exempt_measured_cell(@@ -3229,7 +2894,7 @@ def test_forecast_table_cell_does_not_exempt_measured_cell()assert result.valid is False, result.issues- assert any(issue["code"] == "analysis_claim_unavailable" for issue in result.issues)+ assert sorted(issue["value"] for issue in result.issues) == ["-8.1%", "12.4%"]def test_analysis_completion_is_persisted_with_metric_provenance(@@ -3262,18 +2927,9 @@ def test_analysis_completion_is_persisted_with_metric_provenance(assert artifact["analysis_evidence"][0]["metric"] == "return"-def test_derived_interval_return_from_observed_endpoints_is_allowed(- tmp_path: Path,-) -> None:- """#1338 review: a return figure derived from observed endpoints stays legal.-- Both endpoints are observed evidence and the answer states the growth- inline — arithmetic on sourced inputs, not an invented backtest metric.- """- ledger = GroundingLedger(- run_dir=tmp_path,- user_message="AAPL.US 最近一个月走势如何",- )+def _aapl_endpoint_ledger(tmp_path: Path) -> GroundingLedger:+ """A ledger holding two observed AAPL.US closes, 100.0 and 112.4."""+ ledger = GroundingLedger(run_dir=tmp_path, user_message="AAPL.US 最近一个月走势如何")ledger.ingest_tool_result(tool_name="get_market_data",arguments={"codes": ["AAPL.US"]},@@ -3288,73 +2944,81 @@ def test_derived_interval_return_from_observed_endpoints_is_allowed(call_id="quote",success=True,)+ return ledger+++def test_derived_interval_return_from_observed_endpoints_is_allowed(+ tmp_path: Path,+) -> None:+ """#1338 review: a return derived from observed endpoints stays legal.++ The exemption used to be inferred from the sentence — a growth frame, then+ an operand scan over the line. It is now stated: the declaration carries+ the arithmetic, one of whose operands the run observed, and the gate+ checks that the arithmetic produces the figure.+ """+ ledger = _aapl_endpoint_ledger(tmp_path)good = ledger.validate_final_answer(- "AAPL.US 从 2026-08-03 的 100.0 涨到 2026-09-02 的 112.4,"- "区间收益率为 12.4%。"+ "AAPL.US(USD)从 2026-08-03 的 100.0 涨到 2026-09-02 的 112.4,"+ "区间收益率为 12.4%。\n\n"+ "```figures\n"+ "100.0 | observed | close 2026-08-03 | quote\n"+ "112.4 | observed | close 2026-09-02 | quote\n"+ "12.4% | derived | (112.4 - 100.0) / 100.0 | quote\n"+ "```")assert good.valid is True, good.issuesdef test_derived_cumulative_return_english_is_allowed(tmp_path: Path) -> None:- """#1338 review: same derivation exemption for the English shape."""- ledger = GroundingLedger(- run_dir=tmp_path,- user_message="AAPL.US price history",- )- ledger.ingest_tool_result(- tool_name="get_market_data",- arguments={"codes": ["AAPL.US"]},- result=json.dumps(- {- "AAPL.US": [- {"trade_date": "2026-08-03", "close": 100.0},- {"trade_date": "2026-09-02", "close": 112.4},- ]- }- ),- call_id="quote",- success=True,- )+ """#1338 review: the identical declaration under English prose."""+ ledger = _aapl_endpoint_ledger(tmp_path)good = ledger.validate_final_answer(- "AAPL.US rose from 100.0 to 112.4, a cumulative return of 12.4% "- "over the window."+ "AAPL.US rose from 100.0 to 112.4 USD, a cumulative return of 12.4% "+ "over the window.\n\n"+ "```figures\n"+ "100.0 | observed | close 2026-08-03 | quote\n"+ "112.4 | observed | close 2026-09-02 | quote\n"+ "12.4% | derived | (112.4 - 100.0) / 100.0 | quote\n"+ "```")assert good.valid is True, good.issuesdef test_unanchored_return_claim_is_still_rejected(tmp_path: Path) -> None:- """Without the from/to frame, a return figure stays gated."""- ledger = GroundingLedger(- run_dir=tmp_path,- user_message="AAPL.US 价格",- )- ledger.ingest_tool_result(- tool_name="get_market_data",- arguments={"codes": ["AAPL.US"]},- result=json.dumps(- {- "AAPL.US": [- {"trade_date": "2026-08-03", "close": 100.0},- {"trade_date": "2026-09-02", "close": 112.4},- ]- }- ),- call_id="quote",- success=True,- )+ """A return figure with no derivation behind it stays gated."""+ ledger = _aapl_endpoint_ledger(tmp_path)bad = ledger.validate_final_answer("AAPL.US 区间收益率为 12.4%,历史回测年化收益 18.2%。")assert bad.valid is False, bad.issues- assert any(- issue["code"] == "analysis_claim_unavailable" for issue in bad.issues+ assert [+ issue["value"] for issue in bad.issues if issue["value"] is not None+ ] == ["12.4%", "18.2%"]++ # Declaring it derived is not enough either: the note has to be the+ # arithmetic, and its operands have to be values this session observed.+ unanchored = ledger.validate_final_answer(+ "AAPL.US(USD)区间收益率为 12.4%。\n\n"+ "```figures\n12.4% | derived | 回测得出 | quote\n```"+ )+ assert unanchored.valid is False+ assert [issue["reason"] for issue in unanchored.issues] == ["formula_not_evaluable"]++ wrong_operands = ledger.validate_final_answer(+ "AAPL.US(USD)区间收益率为 12.4%。\n\n"+ "```figures\n12.4% | derived | (55.5 - 49.4) / 49.4 | quote\n```")+ assert wrong_operands.valid is False+ assert [issue["reason"] for issue in wrong_operands.issues] == [+ "formula_not_anchored"+ ]def test_wrong_derived_return_arithmetic_is_rejected(tmp_path: Path) -> None:@@ -3494,10 +3158,15 @@ def test_analysis_gate_still_rejects_unattributed_and_unsourced(), answer-def test_attribution_exemption_cannot_launders_self_claims(tmp_path: Path) -> None:- """The #1336 attack shape must not escape via attribution vocabulary:- "the backtest/data shows" is a self-claim, and a citation in one clause- must not exempt an invented sibling metric in the next."""+def test_a_citation_subject_no_longer_exempts_anything(tmp_path: Path) -> None:+ """The #1336 attack shape cannot escape through attribution vocabulary.++ The exemption used to be a phrase list of citation subjects — "the paper+ reports" was exempt, "the backtest reports" was not — and the list decided+ every verdict. There is no such list: a figure is exempt only when the+ model DECLARES it cited and names a source, which is a statement the model+ signs rather than a phrasing it stumbles into.+ """for answer in ("The backtest data shows an annualized return of 25%.","回测数据显示策略年化收益 25%。",@@ -3505,30 +3174,40 @@ def test_attribution_exemption_cannot_launders_self_claims(tmp_path: Path) -> No"根据本次回测,年化波动率 18.2%。","The strategy reports a Sharpe ratio of 1.8.","研究显示策略年化收益 25%。",- "研究报告显示策略年化收益 25%。",- "回测研究显示策略年化收益 25%。","投资者普遍认为其年化收益 25%。",- # citation in clause 1, invented sibling in clause 2+ # A citation subject in one sentence never covered the next one, and+ # now it cannot cover anything: neither figure is declared."The paper reports a Sharpe ratio of 1.8, and our strategy achieved ""an annualized return of 47.3%.",):ledger = GroundingLedger(run_dir=tmp_path, user_message="Research the factor.")issues = ledger.validate_final_answer(answer).issues- assert [i for i in issues if i.get("code") == "analysis_claim_unavailable"], (- answer,- issues,- )+ assert issues, answer+ assert {i["code"] for i in issues} <= {+ "numeric_claim_unavailable",+ "numeric_claim_conflict",+ }, (answer, issues)++ # The other side: declaring the paper's figure cited passes, and it does+ # NOT carry the sibling the same sentence invents.+ ledger = GroundingLedger(run_dir=tmp_path, user_message="Research the factor.")+ partial = ledger.validate_final_answer(+ "The paper reports a Sharpe ratio of 1.8, and our strategy achieved "+ "an annualized return of 47.3%.\n\n"+ "```figures\n1.8 | cited | Fama-French 2024, table 3\n```"+ )+ assert partial.valid is False+ assert [issue["value"] for issue in partial.issues] == ["47.3%"]def test_attribution_never_exempts_a_price_claim(tmp_path: Path) -> None:"""A citation subject must not launder a fabricated quote.- The attribution exemption is legitimate in the ANALYSIS gate — a paper's- Sharpe is a figure this run could never have observed. A price is the- opposite: it is exactly what this run observes, so attributing it to a- source is the laundering shape the price gate exists to catch. With the- exemption applied to `_validate_price_claims`, every line below passed- with zero tool evidence.+ Attributing a figure to a source used to be an exemption the gate read out+ of the prose, and applying it to price claims let every line below pass+ with zero tool evidence. There is no prose exemption now: a citation is+ the ``cited`` role, which the model declares and which never claims the+ figure is a print of this instrument."""for answer in ("Analysts say TSLA.US last traded at 412.35 USD.",@@ -3545,147 +3224,106 @@ def test_attribution_never_exempts_a_price_claim(tmp_path: Path) -> None:def test_derived_return_exemption_is_structural_not_phrasal(tmp_path: Path) -> None:"""The same derivation must get the same verdict in both languages.- Keying the exemption on a growth PHRASE ("从…到" / "from…to") made the- gate stricter for every wording the list missed. The pairs below state the- identical arithmetic on the identical observed endpoints; asserting the- two verdicts are EQUAL is what stops the next patch moving the breakage to- the other language, exactly as test_grounding_language_parity does.+ Keying the exemption on a growth PHRASE ("从…到" / "from…to") made the gate+ stricter for every wording the list missed. The declaration carries the+ arithmetic now, so the prose around it cannot change the verdict at all —+ which is the property this test has always been asserting."""+ declaration = (+ "\n\n```figures\n"+ "100.0 | observed | close 2026-08-03 | quote\n"+ "112.4 | observed | close 2026-09-02 | quote\n"+ "{figure} | derived | (112.4 - 100.0) / 100.0 | quote\n"+ "```"+ )def verdict(answer: str) -> bool:- ledger = GroundingLedger(run_dir=tmp_path, user_message="AAPL.US 走势")- ledger.ingest_tool_result(- tool_name="get_market_data",- arguments={"codes": ["AAPL.US"]},- result=json.dumps(- {- "AAPL.US": [- {"trade_date": "2026-08-03", "close": 100.0},- {"trade_date": "2026-09-02", "close": 112.4},- ]- }- ),- call_id="quote",- success=True,- )+ ledger = _aapl_endpoint_ledger(tmp_path)return bool(ledger.validate_final_answer(answer).issues)- # Accepted in both: operands present in the clause and sourced.for english, chinese in ((- "AAPL.US rose from 100.0 to 112.4, a cumulative return of 12.4%.",+ "AAPL.US rose from 100.0 to 112.4 USD, a cumulative return of 12.4%.","AAPL.US 第一日收盘 100.0 美元,第二日收盘 112.4 美元,收益率 12.4%。",),):- en, zh = verdict(english), verdict(chinese)+ block = declaration.format(figure="12.4%")+ en, zh = verdict(english + block), verdict(chinese + block)assert en == zh, f"verdicts disagree by language: EN={en} ZH={zh}"assert en is False, f"sourced derivation rejected: {english}"- # Still rejected in both: no operands in the clause, or wrong arithmetic.- for answer in (- "AAPL.US delivered a cumulative return of 12.4% over the window.",- "AAPL.US 区间收益率为 12.4%。",- "AAPL.US rose from 100.0 to 112.4, a cumulative return of 15.0%.",- "AAPL.US 从 100.0 涨到 112.4,区间收益率为 15.0%。",+ # Still rejected in both: no declaration at all, or arithmetic that does+ # not produce the figure.+ for english, chinese in (+ (+ "AAPL.US delivered a cumulative return of 12.4% over the window.",+ "AAPL.US 区间收益率为 12.4%。",+ ),+ (+ "AAPL.US rose from 100.0 to 112.4 USD, a cumulative return of 15.0%."+ + declaration.format(figure="15.0%"),+ "AAPL.US 从 100.0 涨到 112.4 美元,区间收益率为 15.0%。"+ + declaration.format(figure="15.0%"),+ ),):- assert verdict(answer) is True, f"unanchored/wrong return accepted: {answer}"-def test_generic_header_table_metric_rows_are_gated(tmp_path: Path) -> None:- """#1336 must not be dodgeable by formatting the claim as a generic-header- table (| 指标 | 数值 | / | Metric | Value |) with the metric kind in the- row instead of prose or a metric-headed table."""- ledger = GroundingLedger(run_dir=tmp_path, user_message="回测策略")+ en, zh = verdict(english), verdict(chinese)+ assert en == zh, f"verdicts disagree by language: EN={en} ZH={zh}"+ assert en is True, f"unanchored/wrong return accepted: {english}"- result = ledger.validate_final_answer(- "| 指标 | 数值 |\n|---|---:|\n| 年化收益 | 18.2% |\n| 最大回撤 | -9.4% |"- )- assert result.valid is False, result.issues- assert [- i for i in result.issues if i.get("code") == "analysis_claim_unavailable"- ]+def test_generic_header_table_metric_rows_are_gated(tmp_path: Path) -> None:+ """#1336 must not be dodgeable by formatting the claim as a table.- # a comparison marker must not launder an unsupported figure through a- # metric-headed table either: prose rejects "夏普比率 > 1.5。" without- # evidence, so the table form must be rejected too- result = ledger.validate_final_answer("| 夏普比率 |\n|---|---|\n| > 1.5 |")- assert result.valid is False, result.issues+ The generic-header machinery that used to read a row LABEL for a metric+ kind and then pair it with an adjacent value cell is gone with the kind+ regexes it depended on. Every cell of every table is measurement-shaped,+ so the formatting dodge closes by construction instead of by a second+ validator that had to mirror the prose one.+ """+ ledger = GroundingLedger(run_dir=tmp_path, user_message="回测策略")- # value-first layout (kind in a later cell) is gated too- result = ledger.validate_final_answer(- "| 数值 | 指标 |\n|---|---|\n| 18.2% | 年化收益率 |"- )- assert result.valid is False, result.issues- # the bare fragment the prose detector treats as a metric word is gated- result = ledger.validate_final_answer(- "| 指标 | 数值 |\n|---|---|\n| 年化 | 18.2% |"- )- assert result.valid is False, result.issues- # multiple (label, value) pairs in one row are each gated with their own kind- result = ledger.validate_final_answer(- "| 指标 | 数值 | 指标 | 数值 |\n|---|---|---|---|\n| 年化波动率 | 18.2% | 最大回撤 | -9.4% |"- )- assert result.valid is False, result.issues- assert len([i for i in result.issues if i.get("code") == "analysis_claim_unavailable"]) == 2+ for draft in (+ "| 指标 | 数值 |\n|---|---:|\n| 年化收益 | 18.2% |\n| 最大回撤 | -9.4% |",+ "| 夏普比率 |\n|---|---|\n| > 1.5 |",+ "| 数值 | 指标 |\n|---|---|\n| 18.2% | 年化收益率 |",+ "| 指标 | 数值 |\n|---|---|\n| 年化 | 18.2% |",+ "| 指标 | 数值 | 指标 | 数值 |\n|---|---|---|---|\n"+ "| 年化波动率 | 18.2% | 最大回撤 | -9.4% |",+ # A label cell smuggling its own measurement is checked like any other+ # cell, which is what the (label, value) pairing used to have to do.+ "| 指标 | 数值 |\n|---|---|\n| 年化收益率 18.2% | - |",+ ):+ result = ledger.validate_final_answer(draft)+ assert result.valid is False, draft+ assert {i["code"] for i in result.issues} == {"numeric_claim_unavailable"}, draft-def test_generic_header_table_matches_prose_verdicts(tmp_path: Path) -> None:- """The generic-header fallback must produce the SAME verdict as prose for- the same claim — never looser (formatting dodge) and never stricter.+def test_a_table_cell_and_the_same_prose_figure_get_one_verdict(+ tmp_path: Path,+) -> None:+ """Table and prose are the same surface now, so they cannot disagree.- Prose without evidence rejects comparison phrasing ("最大回撤小于 -5%- 触发风控。"), rejects the definitional frame split across the number- ("夏普比率通常大于1.0认为较好。"), and rejects a bare claim; with- kind-matched evidence all of them pass. Tables must do exactly that.+ The generic-header fallback existed to keep a table from being looser than+ prose, and it had its own forecast / definition / label-pairing rules that+ had to be kept in step with the prose validator by hand. A table cell is+ simply a measurement-shaped figure, so the parity is structural."""- bare = GroundingLedger(run_dir=tmp_path / "bare", user_message="回测策略")- # comparison phrasing rejected without evidence, like prose- assert bare.validate_final_answer(- "| 指标 | 标准 |\n|---|---|\n| 最大回撤 | 小于 -5% 触发风控 |"- ).valid is False- # definitional frame split by the number: prose rejects it, tables must not- # be looser than prose or the split becomes the new formatting dodge- assert bare.validate_final_answer(- "| 指标 | 备注 |\n|---|---|\n| 夏普比率 | 通常大于1.0认为较好 |"- ).valid is False- # a label cell smuggling its own measurement is prose-identical to- # "年化收益率为 18.2%" — rejected- assert bare.validate_final_answer(- "| 指标 | 数值 |\n|---|---|\n| 年化收益率 18.2% | - |"- ).valid is False-- backed = GroundingLedger(run_dir=tmp_path / "backed", user_message="回测策略")- backed.ingest_tool_result(- tool_name="portfolio_risk_xray",- arguments={"symbols": ["AAPL"]},- result=json.dumps({"annualized_vol": 0.182, "max_drawdown": -0.05}),- call_id="x",- success=True,- )- # value-backed row accepted- assert backed.validate_final_answer(- "| 指标 | 数值 |\n|---|---:|\n| 年化波动率 | 18.2% |"- ).valid is True- # the same comparison phrasing passes once the figure is kind-backed- assert backed.validate_final_answer(- "| 指标 | 标准 |\n|---|---|\n| 最大回撤 | 小于 -5% 触发风控 |"- ).valid is True- # contiguous definitional frame ("通常认为…") is exempt in prose, so in- # tables too — the frame regex is the boundary, not the formatting- assert backed.validate_final_answer(- "| 指标 | 备注 |\n|---|---|\n| 夏普比率 | 通常认为大于 1.0 较好 |"- ).valid is True- # an annotation column past the value cell is not attributed to the label:- # the prose verdict for "年化波动率 18.2%,较去年提升 2%。" with this evidence- # is valid, so the table form must not be stricter (parity).- assert backed.validate_final_answer(- "| 指标 | 数值 | 备注 |\n|---|---|---|\n| 年化波动率 | 18.2% | 较去年提升 2% |"- ).valid is True- # a FORECAST frame in the label frames the claimed value clause-wide:- # prose "预计夏普比率为 1.2。" and the metric-header path (header_forecast- # column skip) both accept; the generic path must not be stricter.- assert bare.validate_final_answer(- "| 指标 | 数值 |\n|---|---|\n| 预计夏普比率 | 1.2 |"- ).valid is True+ def verdicts(figure: str, block: str = "") -> tuple[bool, bool]:+ prose = GroundingLedger(run_dir=tmp_path / "p", user_message="回测策略")+ table = GroundingLedger(run_dir=tmp_path / "t", user_message="回测策略")+ return (+ prose.validate_final_answer(f"年化波动率 {figure}。{block}").valid,+ table.validate_final_answer(+ f"| 指标 | 数值 |\n|---|---|\n| 年化波动率 | {figure} |{block}"+ ).valid,+ )++ bare_prose, bare_table = verdicts("18.2%")+ assert bare_prose == bare_table is False++ declared = "\n\n```figures\n18.2% | count | 主观区间\n```"+ declared_prose, declared_table = verdicts("18.2%", declared)+ assert declared_prose == declared_table is True@pytest.mark.parametrize(diff --git a/agent/tests/test_agent_output_discipline.py b/agent/tests/test_agent_output_discipline.pyindex 067083a83..ffb103389 100644--- a/agent/tests/test_agent_output_discipline.py+++ b/agent/tests/test_agent_output_discipline.py@@ -291,12 +291,27 @@ class TestTheGateDoesNotKillCorrectAnswers:assert result.valid is True, result.issues- def test_a_percentage_on_an_unhandled_ticker_is_allowed(self, tmp_path: Path) -> None:- result = _ledger(tmp_path).validate_final_answer(+ def test_a_cited_figure_on_an_unhandled_ticker_is_allowed(self, tmp_path: Path) -> None:+ """A citation is an origin, so it answers the unsourced-symbol check.++ The exemption used to be a phrase list of attribution verbs, which+ could not tell "the paper reports" from "the backtest reports" without+ naming every subject by hand. The model declares the role instead.+ """+ cited = _ledger(tmp_path).validate_final_answer(+ f"{_GROUNDED_ANSWER}\n600519.SH 年内涨约 12%。"+ "\n\n```figures\n212.5 | observed | close | q1\n"+ "12% | cited | 券商研报 2026-08\n```"+ )+ undeclared = _ledger(tmp_path).validate_final_answer(f"{_GROUNDED_ANSWER}\n600519.SH 年内涨约 12%。")- assert result.valid is True, result.issues+ assert cited.valid is True, cited.issues+ assert {issue["code"] for issue in undeclared.issues} == {+ "unsourced_symbol_figures",+ "numeric_claim_unavailable",+ }def test_a_calendar_date_on_an_unhandled_ticker_is_allowed(self, tmp_path: Path) -> None:result = _ledger(tmp_path).validate_final_answer(@@ -316,14 +331,22 @@ class TestTheGateDoesNotKillCorrectAnswers:success=True,)- result = ledger.validate_final_answer(f"{_GROUNDED_ANSWER}\n600519.SH 权重 30.0。")+ result = ledger.validate_final_answer(+ f"{_GROUNDED_ANSWER}\n600519.SH 权重 30.0。"+ "\n\n```figures\n212.5 | observed | close | q1\n"+ "30.0 | count | 组合权重(%)\n```"+ )assert result.valid is True, result.issuesdef test_a_symbol_the_user_supplied_is_allowed(self, tmp_path: Path) -> None:ledger = _ledger(tmp_path, message="比较 AAPL.US 和 600519.SH")- result = ledger.validate_final_answer(f"{_GROUNDED_ANSWER}\n600519.SH 权重 30.0。")+ result = ledger.validate_final_answer(+ f"{_GROUNDED_ANSWER}\n600519.SH 权重 30.0。"+ "\n\n```figures\n212.5 | observed | close | q1\n"+ "30.0 | count | 组合权重(%)\n```"+ )assert result.valid is True, result.issues@@ -355,6 +378,7 @@ class TestTheGateDoesNotKillCorrectAnswers:assert ledger._session_symbols == set()result = ledger.validate_final_answer("AAPL.US reported revenue of 400.0 billion USD."+ "\n\n```figures\n400.0 | observed | revenue_usd_bn | f1\n```")assert result.valid is True, result.issues@@ -377,10 +401,11 @@ class TestTheGateDoesNotKillCorrectAnswers:result = ledger.validate_final_answer("MSFT.US reported revenue of 400.0 billion USD."+ "\n\n```figures\n400.0 | observed | revenue_usd_bn | f1\n```")assert result.valid is False- assert [issue["code"] for issue in result.issues] == ["unsourced_symbol_figures"]+ assert "unsourced_symbol_figures" in [issue["code"] for issue in result.issues]def test_a_shortlist_candidate_is_allowed(self, tmp_path: Path) -> None:"""A resolver that offered the symbol is a tool that returned it."""@@ -406,7 +431,11 @@ class TestTheGateDoesNotKillCorrectAnswers:success=True,)- result = ledger.validate_final_answer(f"{_GROUNDED_ANSWER}\n候选 600519.SH 权重 30.0。")+ result = ledger.validate_final_answer(+ f"{_GROUNDED_ANSWER}\n候选 600519.SH 权重 30.0。"+ "\n\n```figures\n212.5 | observed | close | q1\n"+ "30.0 | count | 组合权重(%)\n```"+ )# A shortlist is an answer, not a gap, so it no longer blocks the final# answer either — consumers stay blocked on ``ambiguous`` instead. This@@ -436,10 +465,15 @@ class TestTheGateDoesNotKillCorrectAnswers:"""ledger = GroundingLedger(run_dir=tmp_path, user_message="A股宽基指数有哪些")- result = ledger.validate_final_answer("000300.SH 覆盖 300 只成分股。")+ result = ledger.validate_final_answer(+ "000300.SH 覆盖 300.0 只成分股。"+ )assert result.valid is False- assert [issue["code"] for issue in result.issues] == ["unsourced_symbol_figures"]+ assert {issue["code"] for issue in result.issues} == {+ "unsourced_symbol_figures",+ "numeric_claim_unavailable",+ }class TestTheSemanticPrinciplesStayInThePrompt:diff --git a/agent/tests/test_grounding_figures_contract.py b/agent/tests/test_grounding_figures_contract.pynew file mode 100644index 000000000..aae7ea6e9--- /dev/null+++ b/agent/tests/test_grounding_figures_contract.py@@ -0,0 +1,625 @@+"""The figures-block contract: parsing, shape, roles, and what is released.++This is the contract the word catalogue was replaced with. The catalogue tried+to infer a number's ROLE from the prose around it — price words, target/stop+words, ATH spellings, indicator names, attribution verbs, forecast frames — and+it could never close: the same sentence got different verdicts in its two+translations, and every new phrasing cost either a revision round or a leak.++Three things replace it, and this file pins all three:++* the model DECLARES each figure's role in a fenced ``figures`` block;+* the gate infers only SHAPE — date, symbol, ordinal, measurement, bare+ integer — which is the same in every language;+* the block is stripped before release, so the contract never reaches the user.++Every rule below is tested from both sides. A gate whose tests only assert+rejection cannot see itself closing on everything, and a gate whose tests only+assert acceptance cannot see itself opening on everything.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from src.agent.grounding import GroundingLedger+from src.agent.grounding.figures import (+ ROLES,+ parse_figures_block,+ scan_figures,+ strip_figures_block,+)++pytestmark = pytest.mark.unit++SYMBOL = "159516.SZ"+++def _market_payload() -> str:+ """A sparse two-bar ledger: 0.567–1.053, so a probe value is unambiguous."""+ return json.dumps(+ {+ SYMBOL: [+ {+ "trade_date": "2026-05-06",+ "open": 1.020,+ "high": 1.053,+ "low": 1.001,+ "close": 1.040,+ "volume": 123456,+ },+ {+ "trade_date": "2026-09-09",+ "open": 0.670,+ "high": 0.681,+ "low": 0.567,+ "close": 0.666,+ "volume": 234567,+ },+ ],+ "_provenance": {+ SYMBOL: {+ "source": "akshare",+ "requested_source": "auto",+ "detected_source": "akshare",+ "fallback_used": False,+ "currency_conversion": "none",+ }+ },+ }+ )+++def _ledger(tmp_path: Path, *, message: str = "分析 159516.SZ 并给出买入价") -> GroundingLedger:+ ledger = GroundingLedger(run_dir=tmp_path, user_message=message)+ ledger.ingest_tool_result(+ tool_name="get_market_data",+ arguments={"codes": [SYMBOL]},+ result=_market_payload(),+ call_id="c1",+ success=True,+ )+ return ledger+++HDR = "159516.SZ(akshare,CNY)最新收盘 0.666 元。"++HDR_ROW = "0.666 | observed | close 2026-09-09 | c1"+++def _block(*rows: str) -> str:+ return "\n\n```figures\n" + "\n".join(rows) + "\n```"+++# ---------------------------------------------------------------------------+# §2 — parsing the block+# ---------------------------------------------------------------------------+++def test_the_block_parses_the_spec_example() -> None:+ """Every role, every optional field, exactly as §2 writes it."""+ block = parse_figures_block(+ "answer text\n\n```figures\n"+ "0.666 | observed | 159516.SZ close 2026-09-09 | c1\n"+ "0.646 | derived | 0.666 × 0.97 | c1\n"+ "37% | derived | (0.666 − 1.053) / 1.053 | c1\n"+ "0.95 | proposed | entry\n"+ "1.8 | cited | 论文 Sharpe\n"+ "3 | count | 月\n"+ "```"+ )++ assert block.present is True+ assert block.malformed == ()+ assert [d.role for d in block.declarations] == [+ "observed", "derived", "derived", "proposed", "cited", "count"+ ]+ assert [d.value for d in block.declarations] == [0.666, 0.646, 37.0, 0.95, 1.8, 3.0]+ assert [d.percent for d in block.declarations] == [+ False, False, True, False, False, False+ ]+ assert block.declarations[3].note == "entry"+ assert block.declarations[3].ref == ""+ assert block.declarations[0].ref == "c1"+++ "line",+ [+ "0.666 | observed | close | c1", # full-width pipes+ "0.666|observed|close|c1", # no spacing at all+ " 0.666 | observed | close ", # run-on spacing, no ref+ "0.666 | OBSERVED | close | c1", # role case+ "¥0.666 | observed | close | c1", # currency mark on the value+ "1,234.50 | observed | close | c1", # grouped thousands+ ],+)+def test_the_parser_is_lenient_about_form(line: str) -> None:+ """§2: full-width pipes, run-on spacing and a missing ref are all accepted."""+ block = parse_figures_block(f"text\n\n```figures\n{line}\n```")++ assert block.malformed == (), line+ assert len(block.declarations) == 1, line+ assert block.declarations[0].role == "observed", line+++ "line",+ [+ "this is not a declaration", # no pipes at all+ "0.666", # value with no role+ "0.666 | observado | close | c1", # role outside the five+ "close | observed | c1", # first field is not a number+ "| observed | close | c1", # empty value+ ],+)+def test_a_line_that_cannot_be_read_is_reported_not_skipped(line: str) -> None:+ """A declaration the gate skipped is a figure the gate never checked."""+ block = parse_figures_block(f"text\n\n```figures\n{line}\n```")++ assert block.declarations == (), line+ assert len(block.malformed) == 1, line+++def test_a_malformed_line_fails_the_draft(tmp_path: Path) -> None:+ """It reaches the verdict, with the offending text in the message."""+ result = _ledger(tmp_path).validate_final_answer(+ HDR + _block(HDR_ROW, "0.95 is my entry")+ )++ assert result.valid is False+ assert [issue["code"] for issue in result.issues] == ["figures_block_malformed"]+ assert "0.95 is my entry" in result.issues[0]["message"]+++def test_the_last_block_wins_and_earlier_fences_are_code() -> None:+ """A draft may show code; only the trailing ``figures`` fence declares."""+ block = parse_figures_block(+ "```python\nprice = 9.99\n```\n\n"+ "```figures\n0.666 | observed | close | c1\n```"+ )++ assert [d.value for d in block.declarations] == [0.666]+++def test_an_unterminated_block_still_parses() -> None:+ """A truncated answer must not silently un-declare its own figures."""+ block = parse_figures_block("text\n\n```figures\n0.666 | observed | close | c1")++ assert [d.value for d in block.declarations] == [0.666]+++def test_a_declaration_matches_by_value_at_written_precision() -> None:+ """§2: ``37%`` and ``37 %`` are one assertion; ``37%`` and ``0.37`` are not."""+ block = parse_figures_block("t\n\n```figures\n37 % | derived | (a-b)/b | c1\n```")++ assert block.match(37.0, True) is not None+ assert block.match(0.37, False) is None+ assert block.match(37.0, False) is None+ assert block.match(36.9, True) is None+++def test_every_role_in_the_contract_is_accepted() -> None:+ """The five roles are the contract; nothing else parses."""+ for role in ROLES:+ block = parse_figures_block(f"t\n\n```figures\n1.5 | {role} | note | c1\n```")+ assert block.declarations[0].role == role+ assert parse_figures_block("t\n\n```figures\n1.5 | guess | n | c1\n```").malformed+++# ---------------------------------------------------------------------------+# §2 — stripping+# ---------------------------------------------------------------------------+++def test_the_block_is_stripped_from_the_released_text(tmp_path: Path) -> None:+ """The contract is between the model and the gate; the user never sees it."""+ answer = HDR + _block(HDR_ROW)++ result = _ledger(tmp_path).validate_final_answer(answer)++ assert result.valid is True, result.issues+ assert result.released_text == HDR+ assert "figures" not in result.released_text+ assert "observed" not in result.released_text+++def test_stripping_a_draft_without_a_block_changes_nothing(tmp_path: Path) -> None:+ result = _ledger(tmp_path).validate_final_answer(HDR)++ assert result.released_text == HDR+++def test_the_raw_block_is_kept_in_the_artifact(tmp_path: Path) -> None:+ """Stripped from the answer, preserved in the audit record."""+ ledger = _ledger(tmp_path)+ ledger.validate_final_answer(HDR + _block(HDR_ROW))++ artifact = json.loads(+ (tmp_path / "artifacts" / "grounding_evidence.json").read_text(encoding="utf-8")+ )++ assert HDR_ROW in artifact["validations"][0]["figures_block"]+++def test_strip_is_addressable_on_its_own() -> None:+ text = "line one\n\n```figures\n1.0 | count | n\n```"+ assert strip_figures_block(text, parse_figures_block(text)) == "line one"+++# ---------------------------------------------------------------------------+# §3 — the three shapes+# ---------------------------------------------------------------------------+++def _shapes(text: str) -> dict[str, str]:+ block = parse_figures_block(text)+ return {figure.text: figure.shape for figure in scan_figures(text, block)}+++ "text",+ [+ "2026-09-09 的收盘", # ISO date+ "2026/09/09 的收盘", # slash date+ "2026年9月9日 的收盘", # localized date+ "回顾 2024 年的行情", # bare year+ "159516.SZ 的走势", # symbol digits+ "HK.00700 的走势", # prefixed symbol digits+ "1. 第一条结论", # ordered-list marker+ "### 6. 关键价位", # numbered heading+ "The 2026-09-09 close", # ISO date, English prose+ "On 2024 levels", # bare year, English prose+ "3. First conclusion", # ordered-list marker, English+ ],+)+def test_structural_shapes_need_no_declaration(text: str) -> None:+ """§3: a date, a year, a symbol's digits and an ordinal are structure."""+ assert set(_shapes(text).values()) == {"exempt"}, text+++ "text",+ [+ "收盘 0.666 元", # decimal+ "回撤 37%", # percent+ "回撤 37 %", # full-width percent+ "成本 820 CNY", # integer + ISO code+ "entry at $100", # integer + currency symbol+ "报价 100 元", # integer + CJK currency+ "| 收盘 |\n|---|\n| 0.666 |", # table cell+ "The close was 0.666", # decimal, English prose+ "Down 37% from the high", # percent, English prose+ "revenue of 400.5 billion", # decimal, English prose+ ],+)+def test_measurement_shapes_must_be_declared(text: str) -> None:+ """§3: a decimal, a percent, a currency mark or a table cell is a claim."""+ assert "measured" in _shapes(text).values(), text+++ "text",+ [+ "观察窗口 20 日", # lookback window+ "持有 3 个月", # horizon+ "买入 100 股", # lot size+ "第 206 行提到", # line citation+ "CONFIDENCE: 6", # conviction score+ "折算比例 6:1", # ratio+ "20/50/200-day 均线", # window enumeration+ "共 16 个交易日", # count noun+ "a 52-week high", # window, English prose+ "over 3 sessions", # horizon, English prose+ ],+)+def test_bare_integers_are_not_checked(text: str) -> None:+ """§3: a plain integer is a count, a window or an index, never a price.++ Each of these had a mask of its own — a labelled-score mask, a+ quantity-with-unit mask, a line-reference mask, a ratio mask — and each+ mask was a list that had to be complete. None of them is needed: none of+ these numbers is measurement-shaped.+ """+ assert "measured" not in _shapes(text).values(), text+++def test_a_bare_integer_inside_a_table_cell_is_still_a_measurement(+ tmp_path: Path,+) -> None:+ """A table row is a quotation, whatever precision its cells are written at.++ Outside a table an integer is a count and is not checked; inside one it is+ a value the report is presenting as data, so it is. The pair below is the+ whole rule: the same "300" passes in prose and is checked in a cell.+ """+ prose = "159516.SZ(akshare,CNY)指数覆盖 300 只成分股。"+ cell = "| 代码 | 收盘 |\n|---|---|\n| 159516.SZ | 300 |\n"++ assert _shapes(prose)["300"] == "bare"+ assert _shapes(cell)["300"] == "measured"+ assert _ledger(tmp_path).validate_final_answer(prose).valid is True+ rejected = _ledger(tmp_path).validate_final_answer(+ "159516.SZ(akshare,CNY)\n\n" + cell+ )+ assert [issue["value"] for issue in rejected.issues] == ["300"]+++def test_a_market_data_rows_own_volume_is_evidence(tmp_path: Path) -> None:+ """A row is one observation, and its volume is part of that row.++ Restricting the pool to price fields alone rejected every report that+ quoted the turnover beside the close — a figure the same tool call+ returned. The pool is the row, not the whole ledger: a number no call+ produced is still refused.+ """+ ledger = _ledger(tmp_path)+ row = "| 日期 | 收盘 | 成交量 |\n|---|---|---|\n| 2026-09-09 | 0.666 | {} |\n"++ quoted = ledger.validate_final_answer(HDR + "\n\n" + row.format("234567"))+ invented = ledger.validate_final_answer(HDR + "\n\n" + row.format("999999"))++ assert quoted.valid is True, quoted.issues+ assert [issue["value"] for issue in invented.issues] == ["999999"]+++def test_a_currency_word_is_bounded_so_a_cjk_word_is_not_money() -> None:+ """"3 元宵节后" is not three yuan; "3 美元" is three dollars."""+ assert _shapes("买入 3 美元")["3"] == "measured"+ assert _shapes("3 元宵节后关注")["3"] == "bare"+++def _measured(text: str) -> set[str]:+ return {+ figure for figure, shape in _shapes(text).items() if shape == "measured"+ }+++def test_a_fenced_code_block_is_not_prose() -> None:+ text = "见下:\n\n```python\nentry = 9.99\n```\n\n" + HDR+ assert _measured(text) == {"0.666"}+++def test_a_date_column_and_a_symbol_column_are_exempt_inside_a_table() -> None:+ """A table declares its own columns; its date is not a measurement."""+ text = "| 日期 | 代码 | 收盘 |\n|---|---|---|\n| 2026-09-09 | 159516.SZ | 0.666 |"+ assert _measured(text) == {"0.666"}+++# ---------------------------------------------------------------------------+# §4 — the five roles, both sides each+# ---------------------------------------------------------------------------+++def test_observed_passes_on_evidence_and_fails_off_it(tmp_path: Path) -> None:+ ledger = _ledger(tmp_path)++ grounded = ledger.validate_final_answer(HDR + _block(HDR_ROW))+ invented = ledger.validate_final_answer(+ "159516.SZ(akshare,CNY)最新收盘 0.888 元。"+ + _block("0.888 | observed | close | c1")+ )++ assert grounded.valid is True, grounded.issues+ assert [issue["reason"] for issue in invented.issues] == ["not_in_referenced_call"]+++def test_observed_with_a_ref_is_scoped_to_that_call(tmp_path: Path) -> None:+ """A ref is the tightest scoping there is, and it cuts both ways."""+ ledger = _ledger(tmp_path)+ ledger.ingest_tool_result(+ tool_name="get_fundamentals",+ arguments={"symbol": SYMBOL},+ result=json.dumps({"ok": True, "data": {"pe_ttm": 18.4}}),+ call_id="c2",+ success=True,+ )++ right_call = ledger.validate_final_answer(+ HDR + " 市盈率 18.4。" + _block(HDR_ROW, "18.4 | observed | pe_ttm | c2")+ )+ wrong_call = ledger.validate_final_answer(+ HDR + " 市盈率 18.4。" + _block(HDR_ROW, "18.4 | observed | pe_ttm | c1")+ )++ assert right_call.valid is True, right_call.issues+ assert wrong_call.valid is False+++def test_derived_passes_on_its_own_arithmetic_and_fails_without_it(+ tmp_path: Path,+) -> None:+ ledger = _ledger(tmp_path)++ correct = ledger.validate_final_answer(+ HDR + " 第一档 0.646 元。" + _block(HDR_ROW, "0.646 | derived | 0.666 × 0.97 | c1")+ )+ wrong_result = ledger.validate_final_answer(+ HDR + " 第一档 0.700 元。" + _block(HDR_ROW, "0.700 | derived | 0.666 × 0.97 | c1")+ )+ unanchored = ledger.validate_final_answer(+ HDR + " 第一档 0.646 元。" + _block(HDR_ROW, "0.646 | derived | 0.500 × 1.292 | c1")+ )++ assert correct.valid is True, correct.issues+ assert [i["reason"] for i in wrong_result.issues] == ["derivation_result_mismatch"]+ assert [i["reason"] for i in unanchored.issues] == ["formula_not_anchored"]+++def test_derived_covers_only_the_value_it_declares(tmp_path: Path) -> None:+ """§4: the exemption is the declaration, and a declaration names one value."""+ ledger = _ledger(tmp_path)++ result = ledger.validate_final_answer(+ HDR + " 第一档 0.646 元,第二档 0.400 元。"+ + _block(HDR_ROW, "0.646 | derived | 0.666 × 0.97 | c1", "0.400 | proposed | 第二档")+ )++ assert [issue["value"] for issue in result.issues] == ["0.400"]+++def test_proposed_passes_inside_the_observed_range_and_fails_outside_it(+ tmp_path: Path,+) -> None:+ """§1 decision 2, with the spec's own two numbers.++ 0.65 is inside 159516.SZ's observed 0.567–1.053 and passes; 0.881 against+ a session that only observed 1.110–1.180 does not.+ """+ ledger = _ledger(tmp_path)++ inside = ledger.validate_final_answer(+ HDR + " 建议买入价 0.65 元。" + _block(HDR_ROW, "0.65 | proposed | entry")+ )+ outside = ledger.validate_final_answer(+ HDR + " 建议买入价 2.50 元。" + _block(HDR_ROW, "2.50 | proposed | entry")+ )++ assert inside.valid is True, inside.issues+ assert [i["reason"] for i in outside.issues] == ["outside_observed_range"]+++def test_proposed_outside_the_range_passes_with_a_derivation(tmp_path: Path) -> None:+ """The other half of decision 2: derived OR in range, not derived AND."""+ ledger = _ledger(tmp_path)++ result = ledger.validate_final_answer(+ HDR + " 目标价 1.332 元。" + _block(HDR_ROW, "1.332 | proposed | 0.666 × 2 | c1")+ )++ assert result.valid is True, result.issues+++def test_cited_needs_a_source_and_may_not_pose_as_a_print(tmp_path: Path) -> None:+ ledger = _ledger(tmp_path)++ with_source = ledger.validate_final_answer(+ HDR + " 论文报告夏普 1.8。" + _block(HDR_ROW, "1.8 | cited | Fama-French 2024 table 3")+ )+ without_source = ledger.validate_final_answer(+ HDR + " 论文报告夏普 1.8。" + _block(HDR_ROW, "1.8 | cited | ")+ )+ posing_as_a_close = ledger.validate_final_answer(+ HDR + "\n\n| 日期 | 收盘 |\n|---|---|\n| 2026-09-09 | 1.8 |\n"+ + _block(HDR_ROW, "1.8 | cited | 论文")+ )++ assert with_source.valid is True, with_source.issues+ assert [i["reason"] for i in without_source.issues] == ["citation_without_source"]+ assert [i["reason"] for i in posing_as_a_close.issues] == ["cited_as_observed"]+++def test_count_is_not_checked_but_is_still_declared(tmp_path: Path) -> None:+ """``count`` is the escape hatch, and using it is a statement on the record."""+ ledger = _ledger(tmp_path)++ declared = ledger.validate_final_answer(+ HDR + " 建议持有 3.5 个月。" + _block(HDR_ROW, "3.5 | count | 月")+ )+ undeclared = ledger.validate_final_answer(HDR + " 建议持有 3.5 个月。" + _block(HDR_ROW))++ assert declared.valid is True, declared.issues+ assert [issue["code"] for issue in undeclared.issues] == ["figure_undeclared"]+++# ---------------------------------------------------------------------------+# §4 — undeclared mode+# ---------------------------------------------------------------------------+++def test_undeclared_mode_validates_measurements_as_observed(tmp_path: Path) -> None:+ """§1 decision 1: no block means every measurement is an observed assertion."""+ ledger = _ledger(tmp_path)++ correct = ledger.validate_final_answer(HDR)+ invented = ledger.validate_final_answer("159516.SZ(akshare,CNY)最新收盘 0.888 元。")++ assert correct.valid is True, correct.issues+ assert [issue["code"] for issue in invented.issues] == ["numeric_claim_conflict"]+++def test_undeclared_mode_does_not_guess_proposed_or_derived(tmp_path: Path) -> None:+ """§4: it names the figures to declare instead of inventing a role for them."""+ ledger = _ledger(tmp_path)++ result = ledger.validate_final_answer(HDR + " 建议买入价 0.646 元(0.666 × 0.97)。")++ assert result.valid is False+ assert {issue["role"] for issue in result.issues} == {"observed"}+ # The formula written in the prose grounds nothing: its result and its+ # multiplier are both undeclared measurements, and the gate names both.+ assert [issue["value"] for issue in result.issues] == ["0.646", "0.97"]+++def test_the_correction_prompt_names_each_figure_and_its_reason(+ tmp_path: Path,+) -> None:+ """§6: the feedback is per number, not a restatement of the policy."""+ ledger = _ledger(tmp_path)+ validation = ledger.validate_final_answer(+ HDR + " 建议买入价 2.50 元。" + _block(HDR_ROW, "2.50 | proposed | entry")+ )++ prompt = ledger.correction_prompt(validation)++ assert "2.50" in prompt+ assert "0.567" in prompt and "1.053" in prompt+ assert "figures" in prompt+ assert "DECLARED" in prompt and "REWRITTEN" in prompt and "REMOVED" in prompt+++# ---------------------------------------------------------------------------+# The property the whole refactor exists for+# ---------------------------------------------------------------------------+++def test_the_verdict_does_not_depend_on_the_words_around_the_figure(+ tmp_path: Path,+) -> None:+ """One figure, one declaration, twelve sentences, one verdict.++ Every sentence below used to route through a different branch of the word+ catalogue — a price word, a level word, a target word, an indicator name, a+ citation subject, a forecast frame — and the branch decided the verdict.+ """+ sentences = [+ "收盘 0.666 元。", "现价 0.666 元。", "目标位 0.666 元。", "支撑位 0.666 元。",+ "SMA20 位于 0.666 元。", "预计 0.666 元。", "论文称 0.666 元。", "0.666 元。",+ "The close was 0.666.", "Target 0.666.", "Support at 0.666.",+ "It last traded at 0.666.",+ ]+ ledger = _ledger(tmp_path)++ verdicts = {+ sentence: ledger.validate_final_answer(+ "159516.SZ(akshare,CNY)" + sentence + _block(HDR_ROW)+ ).valid+ for sentence in sentences+ }++ assert set(verdicts.values()) == {True}, verdicts+++def test_a_fabricated_figure_is_refused_under_all_the_same_words(+ tmp_path: Path,+) -> None:+ """The other side of the same property, so it is not satisfied by "accept"."""+ sentences = [+ "收盘 0.888 元。", "现价 0.888 元。", "目标位 0.888 元。", "支撑位 0.888 元。",+ "SMA20 位于 0.888 元。", "论文称 0.888 元。", "0.888 元。",+ "The close was 0.888.", "Support at 0.888.", "It last traded at 0.888.",+ ]+ ledger = _ledger(tmp_path)++ verdicts = {+ sentence: ledger.validate_final_answer(+ "159516.SZ(akshare,CNY)" + sentence+ + _block("0.888 | observed | close | c1")+ ).valid+ for sentence in sentences+ }++ assert set(verdicts.values()) == {False}, verdictsdiff --git a/agent/tests/test_grounding_language_parity.py b/agent/tests/test_grounding_language_parity.pyindex 848633898..7d79918c9 100644--- a/agent/tests/test_grounding_language_parity.py+++ b/agent/tests/test_grounding_language_parity.py@@ -1,22 +1,20 @@-"""The price gate must reach the same verdict in every language it reads.+"""The gate must reach the same verdict in every language it reads.-The gate keys on a phrase list, and a phrase list is written in whatever-language the bug report arrived in. Twice now that has left it strictly+The gate used to key on a phrase list, and a phrase list is written in+whatever language the bug report arrived in. Twice that left it strictlyleakier on one side than the other:- ``\\bclose\\b`` does not match "closed at", which is how an answer actuallystates an observed price. "The stock closed at 412.35." with zero tool callspassed, while "该股收盘 412.35。" — the same fabricated claim — was caught.- Same for "last traded at" and "quoted at".- Chinese had the mirror-image hole: 成交价 / 最新价 / 股价 / 收报 are asordinary as 收盘价 and none of them matched.-So the assertion here is deliberately NOT a literal per language. Each case-runs the same claim through both spellings and asserts the two verdicts are-EQUAL. A per-language literal is what let the two halves drift apart, and it-would let the next patch move the breakage to the other side while staying-green — which is exactly what #1249 does today (it inverts the asymmetry for-derived returns rather than removing it).+There is no phrase list any more: a number's role is declared by the model and+its shape is language-independent. This file is what proves the property+survived the change, so the assertion is deliberately NOT a literal per+language. Each case runs the same figure through both spellings and asserts+the two verdicts are EQUAL.Both arms are pinned. A gate whose tests only assert rejection cannot seeitself closing on everything.@@ -42,7 +40,7 @@ def _has_issues(text: str) -> bool:return bool(ledger.validate_final_answer(text).issues)-# Unsourced price claims: no tool ran, so both spellings must be rejected.+# Unsourced measurements: no tool ran, so both spellings must be rejected._MUST_REJECT = [("The stock closed at 412.35.", "该股收盘 412.35。"),("The stock last traded at 412.35.", "该股最新成交价 412.35。"),@@ -50,27 +48,39 @@ _MUST_REJECT = [("The share price is 412.35.", "该股股价 412.35。"),("It opened at 400.10.", "开盘 400.10。"),("The closing price was 412.35.", "收盘价为 412.35。"),+ # The claim the old gate could only catch on one side of the language+ # border, in the phrasings that crossed it.+ ("The deal closed at a 30.5% premium.", "交易以 30.5% 溢价成交。"),+ ("Gross margin fell 3.6pp.", "毛利率下降 3.6 个百分点。"),]-# Not price claims at all: both spellings must pass. Without this arm the-# suite is satisfied by a gate that rejects everything.+# Not measurements at all, or declared: both spellings must pass. Without this+# arm the suite is satisfied by a gate that rejects everything._MUST_ACCEPT = [("The meeting closed at 5pm.", "会议 5 点结束。"),- ("The deal closed at a 30% premium.", "交易以 30% 溢价成交。"),("Volume traded 1200000 shares.", "成交量 1200000 股。"),("I could not retrieve the price.", "我没能取到价格。"),- ("Gross margin fell 3.6pp.", "毛利率下降 3.6 个百分点。"),- # The past-tense verbs only count when followed by "at". Without that- # constraint a bare "closed"/"traded" turns any nearby number into a- # price claim, and these two are the cases that catch it — the numbers- # are small enough that the aggregate-amount mask does not hide them.("The position closed 3 days later.", "该仓位 3 天后平掉。"),("They traded 8 times last week.", "他们上周交易了 8 次。"),+ # The same figure, declared: the declaration is what moves the verdict,+ # and it moves both languages together.+ (+ "The deal closed at a 30.5% premium.\n\n```figures\n"+ "30.5% | cited | merger announcement 2026-08-03\n```",+ "交易以 30.5% 溢价成交。\n\n```figures\n"+ "30.5% | cited | 并购公告 2026-08-03\n```",+ ),+ (+ "Gross margin fell 3.6pp.\n\n```figures\n"+ "3.6 | cited | 2026 Q2 filing, gross margin bridge\n```",+ "毛利率下降 3.6 个百分点。\n\n```figures\n"+ "3.6 | cited | 2026 Q2 财报毛利率桥\n```",+ ),]@pytest.mark.parametrize(("english", "chinese"), _MUST_REJECT)-def test_unsourced_price_claims_rejected_in_both_languages(+def test_unsourced_measurements_rejected_in_both_languages(english: str, chinese: str) -> None:en, zh = _has_issues(english), _has_issues(chinese)@@ -78,11 +88,11 @@ def test_unsourced_price_claims_rejected_in_both_languages(f"verdicts disagree by language: EN={en} ZH={zh}\n"f" EN: {english}\n ZH: {chinese}")- assert en, "an unsourced price claim must be rejected"+ assert en, "an unsourced measurement must be rejected"@pytest.mark.parametrize(("english", "chinese"), _MUST_ACCEPT)-def test_non_price_statements_accepted_in_both_languages(+def test_non_measurements_and_declarations_accepted_in_both_languages(english: str, chinese: str) -> None:en, zh = _has_issues(english), _has_issues(chinese)@@ -90,4 +100,4 @@ def test_non_price_statements_accepted_in_both_languages(f"verdicts disagree by language: EN={en} ZH={zh}\n"f" EN: {english}\n ZH: {chinese}")- assert not en, "a non-price statement must not be rejected"+ assert not en, "a bare integer or a declared figure must not be rejected"diff --git a/agent/tests/test_grounding_percentage_points.py b/agent/tests/test_grounding_percentage_points.pyindex f5887f746..1c038dcca 100644--- a/agent/tests/test_grounding_percentage_points.py+++ b/agent/tests/test_grounding_percentage_points.py@@ -1,115 +1,103 @@-"""Percentage-point deltas must not be read as quoted prices.+"""Percentage-point deltas: one shape, one verdict, in both languages.++Regression history for HKUDS/Vibe-Trading#1341: the price scan masked "%" but+not the percentage-point spellings, so "~3.6pp below Penumbra" yielded 3.0 (the+".6" consumed as a decimal) and that number reached the OHLC comparator as an+unsourced price claim — rejecting a correct fundamentals answer and demanding+`get_market_data` to substantiate a statement that had nothing to do with+price. The mask that fixed it then had to grow: 个百分点 and 基点 were missing,+the Chinese measure word broke the word boundary, and each gap was one more+rejected answer.++There is no mask now. A percentage-point delta is a decimal, which is+measurement-shaped, which means the model declares what it is — and the twelve+spellings below stop being twelve cases. What this file pins is that they are+ONE case: the same shape, the same verdict, whatever unit token trails the+number and whichever language it is written in.+"""-Regression test for the false positive described in HKUDS/Vibe-Trading#1341:-`_numbers_without_dates_or_percent` masked "%" but not the percentage-point-spellings, so "~3.6pp below Penumbra" yielded 3.0 (the ".6" consumed as a-decimal). That number reached the OHLC comparator as an unsourced price claim,-which rejected a correct fundamentals answer and demanded `get_market_data` to-substantiate a statement that had nothing to do with price.+from __future__ import annotations-Both directions are pinned here: percentage-point deltas are masked, and a-genuine price is still extracted.-"""+import pathlib+import tempfileimport pytestfrom src.agent.grounding import GroundingLedger--_extract = GroundingLedger._numbers_without_dates_or_percent--- "text",- [- "gross margin ~3.6pp below Penumbra",- "gross margin 3.6 pp below Penumbra",- "operating margin improved 2.4ppt year over year",- "operating margin improved 12.5 ppts sequentially",- "spread widened 45bps after the print",- "spread widened 45 bps after the print",- "yield moved 7bp on the day",- "\u6bdb\u5229\u7387\u4e0b\u964d 3.6 \u767e\u5206\u70b9",- "margin fell -1.8pp sequentially",- "margin rose +0.9pp sequentially",- "roughly \u22483.6pp of dilution",- ],-)-def test_percentage_point_deltas_are_not_prices(text):- """No percentage-point delta should survive as a candidate price."""- assert _extract(text) == [], f"leaked a price candidate from: {text!r}"--- "text,expected",- [- ("closing price 48.20", 48.20),- ("the stock closed at 48.20 on heavy volume", 48.20),- ("last trade 152.75", 152.75),- ("opened at 1,204.50 and faded", 1204.50),- ],-)-def test_genuine_prices_are_still_extracted(text, expected):- """The mask must not swallow real quoted prices -- that would blind the- grounding check it exists to feed."""- assert expected in _extract(text), f"lost a real price from: {text!r}"---def test_mixed_sentence_keeps_price_drops_percentage_point():- """A sentence carrying both must yield only the price."""- values = _extract("closed at 48.20, with gross margin ~3.6pp below peers")- assert 48.20 in values- assert 3.0 not in values- assert 3.6 not in values---def test_bare_number_still_extracted():- """Guard against the mask being over-broad: a plain number is untouched."""- assert 48.20 in _extract("48.20")---# The English spellings above were the ones the report named, but this gate-# sees whatever language the model answered in, and the UI ships seven locales.-# The first version of the mask required the number to sit directly against-# "百分点", which is the rare Chinese spelling — the ordinary one puts the-# measure word 个 in between, and "基点" was not covered at all. Both were-# still being read as prices, so a Chinese fundamentals answer kept getting-# rejected while the identical English answer passed.- "text",- [- "毛利率下降 3.6 个百分点",- "毛利率下降3.6个百分点",- "净利率提升 2 个百分点。",- "同比下降 3.6 百分点",- "利差扩大 250 个基点",- "利差扩大250基点",- # A trailing CJK character rather than punctuation: \b after a CJK- # unit needs a non-word char to follow, so this is the case that- # breaks if the boundary is reintroduced there.- "毛利率下降 3.6 个百分点后企稳",- ],-)-def test_chinese_percentage_point_deltas_are_masked(text: str) -> None:- assert _extract(text) == [], f"{text!r} leaked a price-like number"---# The other arm. Narrowing the false positives must not blind the gate to a-# real unsourced price, in either language.- ("text", "expected"),- [- ("TSLA.US last traded at 412.35 USD", [412.35]),- ("closed at 412.35", [412.35]),- ("现价 412.35 元", [412.35]),- ("收盘价 412.35", [412.35]),- # "ppm" is not "pp": the ASCII units keep their word boundary, so the- # mask does not apply and a number still reaches the comparator. The- # value is 3.0 rather than 3.6 because the extractor drops a decimal- # tail followed immediately by letters — the same quirk the pp report- # describes, pre-existing and untouched here. Pinned as-is so a future- # change to either behaviour is visible.- ("3.6ppm impurity", [3.0]),- ],-)-def test_real_prices_still_extracted(text: str, expected: list) -> None:- assert _extract(text) == expected+from src.agent.grounding.figures import parse_figures_block, scan_figures+++def _shapes(text: str) -> list[str]:+ """The shape of every number in ``text``, in document order."""+ return [figure.shape for figure in scan_figures(text, parse_figures_block(text))]+++def _verdict(text: str) -> bool:+ """Validate a fundamentals answer against a run with no market evidence."""+ ledger = GroundingLedger(+ run_dir=pathlib.Path(tempfile.mkdtemp()),+ user_message="compare the gross margins",+ )+ return ledger.validate_final_answer(text).valid+++_SPELLINGS = [+ "gross margin ~3.6pp below Penumbra",+ "gross margin 3.6 pp below Penumbra",+ "operating margin improved 2.4ppt year over year",+ "operating margin improved 12.5 ppts sequentially",+ "spread widened 4.5bps after the print",+ "yield moved 7.0bp on the day",+ "margin fell -1.8pp sequentially",+ "margin rose +0.9pp sequentially",+ "毛利率下降 3.6 个百分点",+ "毛利率下降3.6个百分点",+ "同比下降 3.6 百分点",+ "利差扩大 250.0 个基点",+ "毛利率下降 3.6 个百分点后企稳",+]++[email protected]("text", _SPELLINGS)+def test_every_spelling_is_the_same_measurement_shape(text: str) -> None:+ """A decimal is a decimal, whatever unit token follows it.++ The unit used to decide the verdict, which is why the mask kept growing.+ ``3.6ppm`` was the worst case: the number scan fenced off trailing letters,+ truncated the figure to ``3``, and the same statement was a decimal in+ Chinese and a bare integer in English.+ """+ assert "measured" in _shapes(text), text+++def test_the_unit_no_longer_truncates_the_figure() -> None:+ """``3.6ppm`` is 3.6, not 3 — the fence is on digits, not on letters."""+ text = "3.6ppm impurity"+ figures = scan_figures(text, parse_figures_block(text))++ assert [figure.text for figure in figures] == ["3.6"]++[email protected]("text", _SPELLINGS)+def test_an_undeclared_delta_is_reported_in_every_spelling(text: str) -> None:+ """The lower arm: a figure with no origin is named, not silently masked."""+ assert _verdict(text) is False, text++[email protected]("text", _SPELLINGS)+def test_a_declared_delta_passes_in_every_spelling(text: str) -> None:+ """The upper arm: one declaration settles it, in either language.++ Without this arm the file is satisfied by a gate that rejects everything,+ which is the failure mode the mask had in the other direction.+ """+ figure = next(+ figure.text+ for figure in scan_figures(text, parse_figures_block(text))+ if figure.shape == "measured"+ )+ declared = text + (+ "\n\n```figures\n" + f"{figure} | cited | 2026 Q2 filing, margin bridge\n```"+ )++ assert _verdict(declared) is True, textdiff --git a/agent/tests/test_grounding_release.py b/agent/tests/test_grounding_release.pyindex 0fa421a71..09e20700e 100644--- a/agent/tests/test_grounding_release.py+++ b/agent/tests/test_grounding_release.py@@ -23,15 +23,10 @@ import pytestfrom src.agent.grounding import GroundingLedger, ValidationResultfrom src.agent.grounding.evidence import (- _PRICE_INDICATOR_TOKENS,- _is_price_denominated_indicator,-)-from src.agent.grounding.figures import (- _CLAUSE_SEPARATOR_RE,- _THOUSANDS_SEPARATOR_RE,- _clause_spans,- _lines_with_offsets,+ _REGISTERED_PRICE_INDICATORS,+ _is_registered_price_indicator,)+from src.agent.grounding.figures import _lines_with_offsetsfrom src.agent.grounding.release import _REDACTION_MARKER_EN, _REDACTION_MARKER_ZHfrom src.agent.loop import AgentLoopfrom src.agent.tools import BaseTool, ToolRegistry@@ -142,6 +137,15 @@ def _codes(result: ValidationResult) -> list[str]:return [str(issue.get("code")) for issue in result.issues]+#: The declaration that covers HDR's own quoted close.+HDR_ROW = "1.171 | observed | close 2026-06-24 | prices"+++def _block(*rows: str) -> str:+ """Render a figures block, which every draft with a role needs."""+ return "\n\n```figures\n" + "\n".join(rows) + "\n```"++# ---------------------------------------------------------------------------# Price-denominated indicator values are observed evidence# ---------------------------------------------------------------------------@@ -168,80 +172,108 @@ def test_non_price_indicator_values_still_do_not_ground_a_price(tmp_path: Path)def test_indicator_evidence_never_satisfies_a_labelled_ohlc_cell(tmp_path: Path) -> None:- """A close column must match a close; an SMA equal to the cell does not count."""+ """A close COLUMN must match a close; an SMA equal to the cell does not count."""ledger = _ledger(tmp_path, sma_20=1.150)table = HDR + "\n\n| 日期 | 收盘价 |\n|---|---|\n| 2026-06-24 | 1.150 |\n"result = ledger.validate_final_answer(table)assert result.valid is False- assert any(issue.get("value") == 1.15 for issue in result.issues)+ assert any(issue.get("value") == "1.150" for issue in result.issues)# ----------------------------------------------------------------------------# Derivation spellings a correcting model writes+# A derivation is a declaration, not a spelling# ---------------------------------------------------------------------------- "separator",- ["=", "≈", "≒", "约", "约等于"],-)-def test_derivation_accepts_every_result_separator(tmp_path: Path, separator: str) -> None:+def test_a_declared_derivation_is_checked_by_its_own_arithmetic(tmp_path: Path) -> None:+ """The note IS the formula, so no result-separator vocabulary is involved.++ The prose used to have to carry the equation, and the gate had to+ recognise the separator the model happened to write — "=" worked, then+ "≈" and "约" were added, then "approximately" had to be added because the+ English spelling was still burning a revision round. The separator list is+ gone: the arithmetic is in the declaration and the prose says what it likes.+ """ledger = _ledger(tmp_path)result = ledger.validate_final_answer(- HDR + f" 基于收盘价 1.171 × 0.97 {separator} 1.136 作为买入价。"+ HDR + " 建议买入价 1.136 元。"+ + _block(HDR_ROW, "1.136 | derived | 1.171 × 0.97 | prices"))- assert result.valid is True, (separator, result.issues)+ assert result.valid is True, result.issues-def test_derivation_with_wrong_result_stays_rejected_whatever_the_separator(tmp_path: Path) -> None:+def test_a_derivation_whose_arithmetic_misses_is_rejected(tmp_path: Path) -> None:+ """The declared value has to be what the note actually computes."""ledger = _ledger(tmp_path)- result = ledger.validate_final_answer(HDR + " 基于收盘价 1.171 × 0.97 ≈ 1.20 作为买入价。")+ result = ledger.validate_final_answer(+ HDR + " 建议买入价 1.20 元。"+ + _block(HDR_ROW, "1.20 | derived | 1.171 × 0.97 | prices")+ )assert result.valid is False- assert 1.2 in {issue.get("value") for issue in result.issues}+ assert [issue["value"] for issue in result.issues] == ["1.20"]+ assert [issue["reason"] for issue in result.issues] == ["derivation_result_mismatch"]-def test_derivation_accepts_an_observed_indicator_as_input(tmp_path: Path) -> None:- """`基于 SMA20 1.150 × 0.95 = 1.093`: the input is a tool value, the arithmetic holds."""+def test_a_derivation_may_take_a_registered_indicator_as_its_input(tmp_path: Path) -> None:+ """`SMA20 1.150 × 0.95`: the operand is a tool value, the arithmetic holds."""ledger = _ledger(tmp_path)- result = ledger.validate_final_answer(HDR + " 基于 SMA20 1.150 × 0.95 = 1.093 作为买入价。")+ result = ledger.validate_final_answer(+ HDR + " 第一档 1.093 元。"+ + _block(HDR_ROW, "1.093 | derived | 1.150 × 0.95 | indicators")+ )assert result.valid is True, result.issues-def test_derivation_from_a_non_price_indicator_stays_rejected(tmp_path: Path) -> None:+def test_a_derivation_from_an_unregistered_leaf_stays_rejected(tmp_path: Path) -> None:+ """RSI is not a registered price leaf, so it anchors nothing."""ledger = _ledger(tmp_path)- result = ledger.validate_final_answer(HDR + " 基于 RSI 55.2 × 0.02 = 1.104 作为买入价。")+ result = ledger.validate_final_answer(+ HDR + " 第一档 1.104 元。"+ + _block(HDR_ROW, "1.104 | derived | 55.3 × 0.02 | prices")+ )assert result.valid is False+ assert [issue["reason"] for issue in result.issues] == ["formula_not_anchored"]-def test_bare_arithmetic_equation_counts_as_a_derivation(tmp_path: Path) -> None:- ledger = _ledger(tmp_path)+def test_a_note_that_is_not_arithmetic_is_not_a_derivation(tmp_path: Path) -> None:+ """A derivation needs an operation, not a restatement or a claim.- good = ledger.validate_final_answer(HDR + " 买入价 = 1.171 × 0.97 = 1.136。")- wrong = ledger.validate_final_answer(HDR + " 买入价 = 1.171 × 0.97 = 1.20。")- unanchored = ledger.validate_final_answer(HDR + " 买入价 = 1.50 × 0.97 = 1.455。")+ "1.171" alone and "回测得出" are both refused, which is what makes it safe+ for the note to carry no keyword precondition: the two-operand rule in+ ``_evaluate_formula`` is the thing that refuses them.+ """+ ledger = _ledger(tmp_path)- assert good.valid is True, good.issues- assert wrong.valid is False- assert unanchored.valid is False+ for note, reason in (+ ("1.171", "formula_not_evaluable"),+ ("回测得出", "formula_not_evaluable"),+ ):+ result = ledger.validate_final_answer(+ HDR + " 建议买入价 1.136 元。"+ + _block(HDR_ROW, f"1.136 | derived | {note} | prices")+ )+ assert result.valid is False, note+ assert [issue["reason"] for issue in result.issues] == [reason], note-def test_an_entry_without_a_formula_is_still_rejected(tmp_path: Path) -> None:- """The product rule stands: a proposed entry must be observed or derived."""+def test_an_entry_without_a_role_that_survives_is_still_rejected(tmp_path: Path) -> None:+ """The product rule stands: a proposed entry must be derived or in range."""ledger = _ledger(tmp_path)result = ledger.validate_final_answer(HDR + " 建议买入价 1.10 元。")assert _codes(result) == ["numeric_claim_conflict"]+ assert [issue["value"] for issue in result.issues] == ["1.10"]# ---------------------------------------------------------------------------@@ -249,34 +281,68 @@ def test_an_entry_without_a_formula_is_still_rejected(tmp_path: Path) -> None:# ----------------------------------------------------------------------------def test_drawdown_against_an_observed_high_is_arithmetic_not_a_backtest_metric(tmp_path: Path) -> None:- """(1.110 − 1.180) / 1.180 = −5.93%: "约 6%" rounds to it, "约 8%" does not."""+def test_a_drawdown_is_the_arithmetic_its_note_states(tmp_path: Path) -> None:+ """(1.110 − 1.180) / 1.180 = −5.93%: "约 6%" rounds to it, "约 8%" does not.++ The direction used to be inferred from the word 回撤 — a drawdown was+ compared by magnitude, a return by sign — so the same two endpoints+ grounded a +5.9% or a −5.9% depending on the noun beside them. The note+ states which subtraction was done, and the gate checks that subtraction.+ """ledger = _ledger(tmp_path)+ note = "(1.110 - 1.180) / 1.180"++ for claim in ("6%", "5.9%", "-5.9%"):+ result = ledger.validate_final_answer(+ HDR + f" 最低价 1.110 元,较高点 1.180 元已回撤约 {claim}。"+ + _block(+ HDR_ROW,+ "1.110 | observed | low | prices",+ "1.180 | observed | high | prices",+ f"{claim} | derived | {note} | prices",+ )+ )+ assert result.valid is True, (claim, result.issues)- rounded = ledger.validate_final_answer(HDR + " 最低价 1.110 元,较高点 1.180 元已回撤约 6%。")- # 5.9% matches only the high→low direction by magnitude: the reversed- # pair (1.110→1.180) is +6.31%, outside a one-decimal claim's half unit.- precise = ledger.validate_final_answer(HDR + " 最低价 1.110 元,较高点 1.180 元已回撤 5.9%。")- wrong = ledger.validate_final_answer(HDR + " 最低价 1.110 元,较高点 1.180 元已回撤约 8%。")- unanchored = ledger.validate_final_answer(HDR + " 策略最大回撤 6%。")+ for claim in ("8%", "6.31%"):+ result = ledger.validate_final_answer(+ HDR + f" 最低价 1.110 元,较高点 1.180 元已回撤约 {claim}。"+ + _block(+ HDR_ROW,+ "1.110 | observed | low | prices",+ "1.180 | observed | high | prices",+ f"{claim} | derived | {note} | prices",+ )+ )+ assert result.valid is False, claim+ assert [issue["reason"] for issue in result.issues] == [+ "derivation_result_mismatch"+ ], claim- assert rounded.valid is True, rounded.issues- assert precise.valid is True, precise.issues- assert "analysis_claim_unavailable" in _codes(wrong)- assert "analysis_claim_unavailable" in _codes(unanchored)+ unanchored = ledger.validate_final_answer(HDR + " 策略最大回撤 6%。")+ assert _codes(unanchored) == ["numeric_claim_unavailable"]-def test_return_figure_is_matched_at_its_written_precision(tmp_path: Path) -> None:- """1.121 → 1.180 is +5.26%: "约 5%" and "5.3%" round to it; "6%" and "5.4%" do not."""+def test_a_return_figure_is_matched_at_its_written_precision(tmp_path: Path) -> None:+ """1.121 → 1.180 is +5.26%: "约 5%" and "5.3%" round to it; "6%" does not."""ledger = _ledger(tmp_path)- line = "从最低价 1.121 元涨到最高价 1.180 元,区间收益率{}。"+ note = "(1.180 - 1.121) / 1.121"++ def check(claim: str) -> bool:+ return ledger.validate_final_answer(+ HDR + f" 从最低价 1.121 元涨到最高价 1.180 元,区间收益率{claim}。"+ + _block(+ HDR_ROW,+ "1.121 | observed | low | prices",+ "1.180 | observed | high | prices",+ f"{claim.lstrip('约 ')} | derived | {note} | prices",+ )+ ).validfor claim in ("约 5%", "5.3%", "5.26%"):- result = ledger.validate_final_answer(HDR + " " + line.format(claim))- assert result.valid is True, (claim, result.issues)+ assert check(claim) is True, claimfor claim in ("约 6%", "5.4%", "5.20%"):- result = ledger.validate_final_answer(HDR + " " + line.format(claim))- assert "analysis_claim_unavailable" in _codes(result), claim+ assert check(claim) is False, claim# ---------------------------------------------------------------------------@@ -341,7 +407,7 @@ def test_redacted_release_reports_every_cut(tmp_path: Path) -> None:ledger = _ledger(tmp_path)draft = HDR + " 建议买入价 1.10 元。目标买入价 1.05 元。"validation = ledger.validate_final_answer(draft)- assert sorted(issue["value"] for issue in validation.issues) == [1.05, 1.1]+ assert sorted(issue["value"] for issue in validation.issues) == ["1.05", "1.10"]released = ledger.redacted_release(draft, validation)@@ -350,28 +416,27 @@ def test_redacted_release_reports_every_cut(tmp_path: Path) -> None:assert "1.10" not in released and "1.05" not in released-def test_redacted_release_cuts_what_the_recheck_reveals(tmp_path: Path) -> None:- """The analysis validator reports one figure per clause; the second shows on recheck."""+def test_redacted_release_cuts_every_flagged_figure_in_one_pass(tmp_path: Path) -> None:+ """Every figure is located and checked, so none of them waits for a recheck.++ The validators used to report the FIRST unmatched figure in a clause, so a+ second one only surfaced after the first was cut and the whole document+ re-validated — a cut/recheck cascade with a pass bound, and four figures+ in one sentence exhausted it and shipped the canned refusal instead.+ """ledger = _ledger(tmp_path)- draft = HDR + " 策略最大回撤 12% 且夏普 2.5 处于下行趋势。"+ draft = HDR + " 策略最大回撤 12% 夏普 2.5 胜率 55% 年化收益 30% 处于下行趋势。"validation = ledger.validate_final_answer(draft)- assert [issue.get("value") for issue in validation.issues] == ["12%"]+ assert [issue.get("value") for issue in validation.issues] == [+ "12%", "2.5", "55%", "30%",+ ]released = ledger.redacted_release(draft, validation)assert released is not None- assert "12%" not in released and "2.5" not in released- assert "下行趋势" in released and "2 处" in released---def test_redacted_release_gives_up_after_the_pass_bound(tmp_path: Path) -> None:- """Four figures in one clause surface one per pass; three passes are the bound."""- ledger = _ledger(tmp_path)- draft = HDR + " 策略最大回撤 12% 夏普 2.5 胜率 55% 年化收益 30% 处于下行趋势。"- validation = ledger.validate_final_answer(draft)- assert [issue.get("value") for issue in validation.issues] == ["12%"]-- assert ledger.redacted_release(draft, validation) is None+ assert "下行趋势" in released and "※ 略去 4 处" in released+ for figure in ("12%", "2.5", "55%", "30%"):+ assert figure not in releaseddef test_redacted_release_adds_provenance_the_cut_draft_still_lacks(tmp_path: Path) -> None:@@ -725,82 +790,92 @@ def _wide_ledger(tmp_path: Path) -> GroundingLedger:return ledger-def test_a_drawdown_may_only_be_grounded_by_the_falling_direction(tmp_path: Path) -> None:- """A drawdown is a fall; the inverse rise between the same endpoints is not one."""- line = "最新收盘 0.666 元 较 5 月高点 1.053 元 最大回撤约 {}。"-- for claim in ("36.8%", "37%", "-36.8%"):- result = _wide_ledger(tmp_path).validate_final_answer(WIDE_HDR + " " + line.format(claim))- assert result.valid is True, (claim, result.issues)- # 58.11% is (1.053 − 0.666) / 0.666 — the rise back, not the drawdown.- for claim in ("58.1%", "58%", "45%"):- result = _wide_ledger(tmp_path).validate_final_answer(WIDE_HDR + " " + line.format(claim))- assert "analysis_claim_unavailable" in _codes(result), claim+def _wide_block(figure: str, note: str) -> str:+ """Declare the wide ledger's two endpoints and one derived figure."""+ return _block(+ "0.666 | observed | close | prices",+ "1.053 | observed | 5 月高点 | prices",+ f"{figure} | derived | {note} | prices",+ )-def test_magnitude_is_pinned_to_drawdown_and_off_for_a_return(tmp_path: Path) -> None:- """The same fall written as a positive RETURN keeps its sign check."""- fall = "最新收盘 0.666 元 较 5 月高点 1.053 元 {}约 {}。"+def test_the_note_states_which_direction_was_taken(tmp_path: Path) -> None:+ """A fall and the rise back between the same endpoints are different notes.- as_drawdown = _wide_ledger(tmp_path).validate_final_answer(- WIDE_HDR + " " + fall.format("最大回撤", "37%")- )- signed_return = _wide_ledger(tmp_path).validate_final_answer(- WIDE_HDR + " " + fall.format("区间收益率", "-37%")- )- unsigned_return = _wide_ledger(tmp_path).validate_final_answer(- WIDE_HDR + " " + fall.format("区间收益率", "37%")- )+ The direction used to be inferred from the word beside the figure — 回撤+ compared by magnitude, 收益率 by sign — so one noun swap changed the+ verdict on identical arithmetic. Both directions are now writable, and+ each grounds only the figure it actually produces.+ """+ fall = "(0.666 - 1.053) / 1.053"+ rise = "(1.053 - 0.666) / 0.666"+ line = "最新收盘 0.666 元 较 5 月高点 1.053 元,{}。"- assert as_drawdown.valid is True, as_drawdown.issues- assert signed_return.valid is True, signed_return.issues- assert "analysis_claim_unavailable" in _codes(unsigned_return)+ for figure, note in (("36.8%", fall), ("37%", fall), ("58.1%", rise), ("58%", rise)):+ result = _wide_ledger(tmp_path).validate_final_answer(+ WIDE_HDR + " " + line.format(figure) + _wide_block(figure, note)+ )+ assert result.valid is True, (figure, note, result.issues)+ for figure, note in (("58.1%", fall), ("37%", rise), ("45%", fall)):+ result = _wide_ledger(tmp_path).validate_final_answer(+ WIDE_HDR + " " + line.format(figure) + _wide_block(figure, note)+ )+ assert result.valid is False, (figure, note)+ assert [issue["reason"] for issue in result.issues] == [+ "derivation_result_mismatch"+ ][email protected]("metric", ["年化波动率", "胜率", "夏普比率"])-def test_endpoint_arithmetic_grounds_only_returns_and_drawdowns(- tmp_path: Path, metric: str-) -> None:- """A volatility / win rate / Sharpe equal to the endpoint growth is not grounded by it."""- result = _wide_ledger(tmp_path).validate_final_answer(- WIDE_HDR + f" 最新收盘 0.666 元 较 5 月高点 1.053 元 {metric} 58.1%。"- )- assert "analysis_claim_unavailable" in _codes(result)+def test_a_percent_figure_is_compared_in_percentage_points_only(tmp_path: Path) -> None:+ """"约 0%" is not within half a unit of a 58% move — the half unit is in pp.+ A bare integer percent carries a half unit of 0.5, and running that band+ against the FRACTION (0.5811) instead of the percentage points made 0.5 a+ band of fifty points wide: "区间收益率约 0%" validated against a real +58%+ move.+ """+ rise = "(1.053 - 0.666) / 0.666"+ line = "最新收盘 0.666 元 较 5 月高点 1.053 元,区间收益率约 {}。"-def test_a_percent_figure_is_compared_in_percentage_points_only(tmp_path: Path) -> None:- """"约 0%" is not within half a unit of a 58% move — the half unit is in pp."""- line = "最新收盘 0.666 元 较 5 月高点 1.053 元 区间收益率约 {}。"-- for claim in ("0%", "1%", "-1%", "2%"):- result = _wide_ledger(tmp_path).validate_final_answer(WIDE_HDR + " " + line.format(claim))- assert "analysis_claim_unavailable" in _codes(result), claim- for claim in ("58%", "58.1%", "58.11%"):- result = _wide_ledger(tmp_path).validate_final_answer(WIDE_HDR + " " + line.format(claim))- assert result.valid is True, (claim, result.issues)+ for figure in ("0%", "1%", "-1%", "2%"):+ result = _wide_ledger(tmp_path).validate_final_answer(+ WIDE_HDR + " " + line.format(figure) + _wide_block(figure, rise)+ )+ assert result.valid is False, figure+ for figure in ("58%", "58.1%", "58.11%"):+ result = _wide_ledger(tmp_path).validate_final_answer(+ WIDE_HDR + " " + line.format(figure) + _wide_block(figure, rise)+ )+ assert result.valid is True, (figure, result.issues)def test_the_written_precision_band_is_half_a_unit_not_more(tmp_path: Path) -> None:- """The band is exactly half a unit of the last written digit — pinned from both sides.+ """The band is exactly half a unit of the last written digit, from both sides.1.110 → 1.171 is +5.4955%. An integer 5% is 0.4955 away and must beaccepted; 6% is 0.5045 away and must be rejected. The pair straddles 0.5- by a twentieth of a point, so inflating the multiplier even to 0.7 —- "a claim 0.7pp off the arithmetic is grounded" — flips the second- assertion. The nearest existing fixture is 0.737 away and cannot see it.+ by a twentieth of a point, so widening the multiplier even to 0.7 flips the+ second assertion."""ledger = _ledger(tmp_path)- line = "从最低价 1.110 元涨到收盘 1.171 元,区间收益率约 {}。"+ note = "(1.171 - 1.110) / 1.110"++ def verdict(figure: str) -> bool:+ return ledger.validate_final_answer(+ HDR + f" 从最低价 1.110 元涨到收盘 1.171 元,区间收益率约 {figure}。"+ + _block(+ HDR_ROW,+ "1.110 | observed | low | prices",+ f"{figure} | derived | {note} | prices",+ )+ ).valid- inside = ledger.validate_final_answer(HDR + " " + line.format("5%"))- outside = ledger.validate_final_answer(HDR + " " + line.format("6%"))+ assert verdict("5%") is True+ assert verdict("6%") is False# One decimal narrows the band to 0.05: 5.4% is 0.0955 away.- one_decimal = ledger.validate_final_answer(HDR + " " + line.format("5.4%"))-- assert inside.valid is True, inside.issues- assert "analysis_claim_unavailable" in _codes(outside)- assert "analysis_claim_unavailable" in _codes(one_decimal)+ assert verdict("5.4%") is False+ assert verdict("5.5%") is True# ---------------------------------------------------------------------------@@ -808,86 +883,72 @@ def test_the_written_precision_band_is_half_a_unit_not_more(tmp_path: Path) -> N# ----------------------------------------------------------------------------def test_a_derivation_exempts_its_own_values_not_its_neighbours(tmp_path: Path) -> None:- """One valid equation used to exempt the whole clause it sat in.+def test_a_declaration_covers_its_own_value_and_nothing_beside_it(+ tmp_path: Path,+) -> None:+ """One valid derivation used to exempt the whole clause it sat in.- The system prompt now asks the model to write exactly this shape, so an- invented entry price beside a correct formula is the ordinary draft, not a- corner case.+ The exemption is now the declaration, and a declaration names exactly one+ value — so an invented entry price beside a correct derivation is reported+ even when the two share a sentence, and even when the invented one is the+ derivation's own multiplier."""ledger = _ledger(tmp_path)riding_along = ledger.validate_final_answer(HDR + " 建议买入价 0.95 元(收盘 1.171 × 0.97 = 1.136 参考)。"+ + _block(+ HDR_ROW,+ "0.97 | count | 折扣系数",+ "1.136 | derived | 1.171 × 0.97 | prices",+ ))- keyword_form = ledger.validate_final_answer(- HDR + " 基于收盘价 1.171 × 0.97 = 1.136 的买入价 1.30 元。"+ formula_only = ledger.validate_final_answer(+ HDR + " 参考价 1.136 元。"+ + _block(HDR_ROW, "1.136 | derived | 1.171 × 0.97 | prices"))- formula_only = ledger.validate_final_answer(HDR + " 基于收盘价 1.171 × 0.97 = 1.136 买入。")- assert 0.95 in {issue.get("value") for issue in riding_along.issues}- assert 1.3 in {issue.get("value") for issue in keyword_form.issues}- # The operands and the result themselves stay exempt.+ assert [issue["value"] for issue in riding_along.issues] == ["0.95"]assert formula_only.valid is True, formula_only.issues-def test_a_derivation_gets_the_same_verdict_in_both_languages(tmp_path: Path) -> None:- """Every result separator must work in English too, or the fix moves the bug.+def test_the_same_figure_gets_the_same_verdict_under_any_prose(+ tmp_path: Path,+) -> None:+ """Prose cannot change a verdict, because no prose word is read.- ``test_derived_return_exemption_is_structural_not_phrasal`` is the standing- rule; the first cut of this change added ≈ / 约 / 约等于 and left- "approximately" rejected, so a correct English derivation still burned a- revision round.+ This replaces the price-word / level-word / observation-binder catalogues+ outright. Every sentence below states the same declared figure; the gate+ reaches one verdict for all of them, in both scripts, because the only+ inputs are the declaration and the evidence."""+ ledger = _ledger(tmp_path, sma_20=1.150)+ sentences = [+ "现价 1.150 元。", "最新价 1.150 元。", "成交价 1.150 元。", "报价 1.150 元。",+ "股价 1.150 元。", "收盘价为 1.150 元。", "20 日均线 1.150 元。",+ "The current price is 1.150.", "The closing price was 1.150.",+ "It last traded at 1.150.", "The 20-day moving average is 1.150.",+ "1.150 is where it sits.",+ ]- def verdict(answer: str) -> bool:- return _ledger(tmp_path).validate_final_answer(answer).valid-- english_header = "562500.SS (Yahoo, CNY) last close 1.171."- for chinese_separator, english_separator in (- ("=", "="),- ("≈", "≈"),- ("约", "approximately"),- ("约", "about"),- ("约等于", "around"),- ("约", "roughly"),- ("≒", "~"),- ):- chinese = verdict(- HDR + f" 基于收盘价 1.171 × 0.97 {chinese_separator} 1.136 作为买入价。"- )- english = verdict(- english_header- + f" Based on the close 1.171 * 0.97 {english_separator} 1.136 as the entry."- )- assert chinese is english is True, (chinese_separator, english_separator)-- # Wrong arithmetic stays rejected on both sides of the separator list.- assert verdict(HDR + " 基于收盘价 1.171 × 0.97 约 1.20 作为买入价。") is False- assert (- verdict(english_header + " Based on the close 1.171 * 0.97 approximately 1.20.")- is False- )---def test_a_restated_value_is_not_a_derivation(tmp_path: Path) -> None:- """A derivation needs an operation, not "1.171 约 1.171".+ verdicts = {+ sentence: ledger.validate_final_answer(+ HDR + " " + sentence + _block(HDR_ROW, "1.150 | observed | sma_20 | indicators")+ ).valid+ for sentence in sentences+ }- This is what makes it safe for ``_derivation_justified_values`` to carry- no keyword or regex precondition: a "formula" of one operand is a- restatement, and ``_evaluate_formula``'s two-operand rule is the thing- that refuses it.- """- ledger = _ledger(tmp_path)- records = ledger._comparable_price_records()+ assert set(verdicts.values()) == {True}, verdicts- # The evidence symbol is canonicalised (.SS → .SH); pass it as the records- # carry it, not as the answer spells it. Asserted on the values the- # production path actually consumes, not on a bool no caller reads.- assert ledger._derivation_justified_values("收盘 1.171 约 1.171", records, "562500.SH") == []- assert ledger._derivation_justified_values(- "收盘 1.171 × 0.97 约 1.136", records, "562500.SH"- ) == [1.171, 0.97, 1.136]+ # And the same one verdict when the declaration points somewhere the value+ # is not: the ref is what moves it, never the wording.+ misrefs = {+ sentence: ledger.validate_final_answer(+ HDR + " " + sentence + _block(HDR_ROW, "1.150 | observed | 收盘 | prices")+ ).valid+ for sentence in sentences+ }+ assert set(misrefs.values()) == {False}, misrefs# ---------------------------------------------------------------------------@@ -895,33 +956,35 @@ def test_a_restated_value_is_not_a_derivation(tmp_path: Path) -> None:# ----------------------------------------------------------------------------def test_an_indicator_never_backs_a_claim_labelled_as_an_ohlc_field(tmp_path: Path) -> None:- """Same rule in prose as in a table: an SMA is not the close.-- The table path filters evidence on the column's field, so an indicator- could never satisfy a 收盘价 column; prose passed no field at all, and- "收盘价为 1.150 元" was grounded by the session's sma_20 while the observed- close was 1.171. The undated cell is the case the field label actually- decides — a dated cell is settled by the date match before the label is- consulted.+def test_a_declared_ref_is_what_separates_an_indicator_from_a_close(+ tmp_path: Path,+) -> None:+ """Two surfaces still scope evidence: a table column, and a declared ref.++ The prose surface does not. "收盘价为 1.150 元" was refused because the+ clause named an OHLC field and the session's sma_20 happened to equal the+ figure — a verdict a word decided, and one whose mirror in the other+ language leaked for a year. What separates them now is what the model+ says: a ref pointing at the market-data call is checked against that+ call's own bars."""ledger = _ledger(tmp_path, sma_20=1.150)- prose = ledger.validate_final_answer(HDR + " 收盘价为 1.150 元。")- english_prose = ledger.validate_final_answer(- "562500.SS (Yahoo, CNY) last close 1.171. The closing price was 1.150."- )- undated_cell = ledger.validate_final_answer(+ labelled_column = ledger.validate_final_answer(HDR + "\n\n| 代码 | 收盘价 |\n|---|---|\n| 562500.SS | 1.150 |\n"+ + _block(HDR_ROW, "1.150 | observed | close | prices")+ )+ wrong_ref = ledger.validate_final_answer(+ HDR + " 收盘价为 1.150 元。" + _block(HDR_ROW, "1.150 | observed | 收盘 | prices")+ )+ right_ref = ledger.validate_final_answer(+ HDR + " SMA20 位于 1.150。"+ + _block(HDR_ROW, "1.150 | observed | sma_20 | indicators"))- # An unlabelled price word keeps the indicator exemption the release path- # was written for.- unlabelled = ledger.validate_final_answer(HDR + " SMA20 位于 1.150。")- assert "numeric_claim_conflict" in _codes(prose)- assert "numeric_claim_conflict" in _codes(english_prose)- assert "numeric_claim_conflict" in _codes(undated_cell)- assert unlabelled.valid is True, unlabelled.issues+ assert "numeric_claim_conflict" in _codes(labelled_column)+ assert "numeric_claim_conflict" in _codes(wrong_ref)+ assert right_ref.valid is True, right_ref.issuesdef _two_symbol_ledger(tmp_path: Path) -> GroundingLedger:@@ -958,14 +1021,11 @@ def _two_symbol_ledger(tmp_path: Path) -> GroundingLedger:def test_one_symbols_indicator_does_not_ground_an_unattributed_claim(tmp_path: Path) -> None:- """The cross-symbol union is for OHLC quotes; an indicator is symbol-bound.+ """The cross-symbol union is for observed quotes; an indicator is symbol-bound.``technical_indicators`` returns a level for one symbol, so 562500's SMA- must not satisfy a clause on a line that names two instruments and- attributes the figure to neither. The claim is a LEVEL claim on both- sides, because that is the only claim an indicator may answer at all — a- spot quote is settled by the indicator-admissibility rule before the- symbol is consulted.+ must not ground a figure on a line that names two instruments and+ attributes it to neither."""header = "562500.SH 与 600519.SH(Yahoo,CNY)对比。"@@ -985,56 +1045,14 @@ def test_one_symbols_indicator_does_not_ground_an_unattributed_claim(tmp_path: Passert attributed_indicator.valid is True, attributed_indicator.issues- "path",- [- "indicators.sma_20", "indicators.ema_50", "indicators.ma", "indicators.vwap",- "indicators.atr", "indicators.bollinger.lower", "indicators.bollinger.upper",- "indicators.keltner.upper", "indicators.donchian.lower", "indicators.supertrend",- "indicators.ichimoku.tenkan", "indicators.highest_20", "indicators.support",- "indicators.resistance", "pivot.pp", "pivot.r1", "indicators.r1", "levels.s2",- ],-)-def test_price_denominated_leaves_are_evidence(path: str) -> None:- assert _is_price_denominated_indicator(path) is True--- "path",- [- # Derived shapes under a price family: a difference, a gap, a crossover,- # a direction, a strength score, a bandwidth. The old rule admitted all- # of these because some segment of the path names a price family.- "indicators.ma_diff", "indicators.ema_gap", "indicators.sma_cross",- "indicators.supertrend_direction", "indicators.support_strength",- "indicators.atr_multiple", "indicators.ma_deviation", "indicators.psar_reversals",- "indicators.boll_bandwidth", "indicators.bollinger.bandwidth",- "summary.resistance_touches",- # Parameters, not levels.- "params.ma_period", "entry_condition.ma_window", "settings.ema_span",- "config.ma_length",- # A generic band leaf with no price family behind it.- "summary.lower",- # Non-price quantities.- "indicators.rsi_14", "indicators.macd.histogram", "indicators.volume_ma_20", "rows",- # A PRICE leaf under a non-price family. Only the token denylist can- # reject these — the leaf rule alone admits every one — and deleting- # that guard left all 415 cases in these four suites green.- "indicators.volume.sma_20", "indicators.turnover.vwap", "indicators.rsi.ma_5",- "indicators.volume.high", "volume.pivot.r1",- ],-)-def test_non_price_leaves_are_not_evidence(path: str) -> None:- assert _is_price_denominated_indicator(path) is False---def test_a_moving_average_of_volume_never_grounds_a_price(tmp_path: Path) -> None:- """The token denylist, end to end: nesting an SMA under a volume family.+def test_an_unregistered_tools_leaf_never_grounds_a_price(tmp_path: Path) -> None:+ """A price-shaped leaf name from an unregistered tool is not price evidence.``_ingest_generic_numeric`` classifies every non-market tool result, so atool that returns ``{"indicators": {"volume": {"sma_20": 1.30}}}`` is all- it takes. The leaf ``sma_20`` is a price name; only the family token stops- it becoming evidence for "现价 1.30 元".+ it took: the leaf ``sma_20`` is a price NAME, and the rule that read names+ admitted it. Names are no longer read — a tool has to be registered, leaf+ by leaf, before any of its output can answer a price claim."""ledger = GroundingLedger(run_dir=tmp_path, user_message="请分析 562500.SS")ledger.ingest_tool_result(@@ -1057,21 +1075,44 @@ def test_a_moving_average_of_volume_never_grounds_a_price(tmp_path: Path) -> Nonassert "numeric_claim_conflict" in _codes(result)-def test_no_price_indicator_token_is_unreachable() -> None:- """Every declared family name must actually classify as one.+ ("tool", "path", "registered"),+ [+ ("technical_indicators", "latest_close", True),+ ("technical_indicators", "indicators.sma_20", True),+ ("technical_indicators", "indicators.ema_50", True),+ ("technical_indicators", "indicators.bollinger.upper", True),+ ("technical_indicators", "indicators.bollinger.middle", True),+ ("technical_indicators", "indicators.bollinger.lower", True),+ # Same tool, leaves it does not register: an oscillator, a histogram,+ # and the derived shapes the old name-reading rule kept admitting.+ ("technical_indicators", "indicators.rsi_14", False),+ ("technical_indicators", "indicators.macd.histogram", False),+ ("technical_indicators", "indicators.bollinger.bandwidth", False),+ ("technical_indicators", "indicators.sma_cross", False),+ # Same leaf names, a tool nobody registered.+ ("custom_indicator_tool", "indicators.sma_20", False),+ ("custom_indicator_tool", "latest_close", False),+ ],+)+def test_only_registered_leaves_are_price_evidence(+ tool: str, path: str, registered: bool+) -> None:+ """Registration is per tool AND per leaf, in both directions."""+ assert _is_registered_price_indicator(tool, path) is registered+++def test_every_registration_prefix_matches_something_it_names() -> None:+ """A registered prefix must actually classify the leaf it describes.- ``r1``/``s1`` sat in the family list for a change whose CHANGELOG entry- claims pivot levels are covered, while the digit strip turned them into- ``r``/``s`` and no lookup could ever match.+ The list it replaces carried six pivot spellings that no lookup could ever+ reach, because the digit strip turned ``r1`` into ``r``. A registration+ that matches nothing is the same defect wearing a different shape."""- unreachable = [- token- for token in sorted(_PRICE_INDICATOR_TOKENS)- if not _is_price_denominated_indicator("indicators." + token)- ]-- assert unreachable == []- assert all(_is_price_denominated_indicator(f"pivot.{level}") for level in ("r1", "r2", "r3", "s1", "s2", "s3"))+ for tool, prefixes in _REGISTERED_PRICE_INDICATORS.items():+ for prefix in prefixes:+ assert _is_registered_price_indicator(tool, prefix) is True, (tool, prefix)+ assert _is_registered_price_indicator("other_tool", prefix) is False# ---------------------------------------------------------------------------@@ -1084,27 +1125,6 @@ def test_no_price_indicator_token_is_unreachable() -> None:# ----------------------------------------------------------------------------def test_clause_spans_segment_exactly_as_the_split_did(tmp_path: Path) -> None:- """Carrying spans must not change the segmentation itself.-- The clause splitter strips grouping commas BEFORE splitting so a price- above 999 survives as one number; the span version has to skip those- commas as separators instead, and the two must agree everywhere.- """- for text in (- "收盘价 ¥1,309.22 元,建议买入价 1,450.50 元。",- "a,b;c。d、e",- "1,234,567 与 999,9",- "no separators at all",- "",- ):- expected = _CLAUSE_SEPARATOR_RE.split(_THOUSANDS_SEPARATOR_RE.sub("", text))- assert [segment for segment, _, _ in _clause_spans(text)] == expected- # A span points at the clause it describes, comma grouping included.- for segment, start, end in _clause_spans(text):- assert _THOUSANDS_SEPARATOR_RE.sub("", text[start:end]) == segment--def test_redacted_release_locates_a_grouped_number(tmp_path: Path) -> None:"""A price above 999 written the ordinary way must still reach the release path."""ledger = GroundingLedger(run_dir=tmp_path, user_message="请分析 562500.SS 并给出买入价")@@ -1140,7 +1160,7 @@ def test_redacted_release_cuts_a_metric_cell_in_a_table(tmp_path: Path) -> None:ledger = _ledger(tmp_path)draft = HDR + "\n\n| 指标 | 数值 |\n|---|---|\n| 最大回撤 | 12% |\n| 夏普比率 | 2.5 |\n"validation = ledger.validate_final_answer(draft)- assert _codes(validation) == ["analysis_claim_unavailable"] * 2+ assert _codes(validation) == ["numeric_claim_unavailable", "numeric_claim_conflict"]released = ledger.redacted_release(draft, validation)@@ -1156,9 +1176,10 @@ def test_redacted_release_never_cuts_inside_another_number(tmp_path: Path) -> Nodraft = ("562500.SS(Yahoo,CNY)最新收盘价 1.171 元。成交额约 21.10 亿元。""\n\n| 日期 | 收盘价 |\n|---|---|\n| 2026-06-24 | 1.10 |\n"+ + _block(HDR_ROW, "21.10 | count | 成交额(亿元)", "1.10 | observed | close | prices"))validation = ledger.validate_final_answer(draft)- assert _codes(validation) == ["numeric_claim_conflict"]+ assert [i["value"] for i in validation.issues] == ["1.10"]released = ledger.redacted_release(draft, validation)@@ -1168,26 +1189,32 @@ def test_redacted_release_never_cuts_inside_another_number(tmp_path: Path) -> Noassert "※ 略去 1 处" in released-def test_redacted_release_cuts_the_same_figure_everywhere_it_survives(tmp_path: Path) -> None:+def test_every_surviving_occurrence_was_checked_where_it_stands(tmp_path: Path) -> None:"""The footnote says the figure was removed, so it must be removed everywhere.- Neither a table under a non-OHLC header nor a bullet without a price word- is scanned by the validators, so cutting only the flagged clause left the- rejected number standing while the footnote asserted it was gone.+ That used to need a document-wide second stage, because neither a table+ under a non-OHLC header nor a bullet without a price word was scanned by+ the validators: cutting the flagged clause left the rejected number+ standing while the footnote asserted it was gone. Every occurrence is now+ a figure the gate located and checked on its own, so each is flagged and+ cut where it stands — and one that was NOT flagged is one the evidence+ supports, which the sweep used to remove anyway."""ledger = _ledger(tmp_path)in_a_table = HDR + " 建议买入价 1.30 元。\n\n| 档位 | 建议买入价 |\n|---|---|\n| 第一档 | 1.30 |\n"- in_a_bullet = HDR + " 建议买入价 1.30 元。\n- 关键位:1.30 / 1.45\n"+ in_a_bullet = HDR + " 建议买入价 1.30 元。\n- 关键位:1.30 / 1.15\n"for draft in (in_a_table, in_a_bullet):validation = ledger.validate_final_answer(draft)+ assert len([i for i in validation.issues if i["value"] == "1.30"]) == 2, draftreleased = ledger.redacted_release(draft, validation)assert released is not None, draftassert "1.30" not in released, draft- assert "※ 略去 2 处" in released, draft- # The sweep is scoped to the rejected values: 1.45 was never flagged.- assert "1.45" in ledger.redacted_release(+ assert "※ 略去" in released, draft+ # 1.15 sits inside the observed range and is checked like the rest, so it+ # survives on its own merits rather than by being missed.+ assert "1.15" in ledger.redacted_release(in_a_bullet, ledger.validate_final_answer(in_a_bullet))@@ -1216,37 +1243,47 @@ def test_a_metric_cell_restating_observed_closes_is_not_an_invented_metric()assert observed_pair.valid is True, observed_pair.issues- assert "0.900" in {issue.get("value") for issue in invented.issues}- assert "analysis_claim_unavailable" in _codes(invented_percent)+ assert [issue.get("value") for issue in invented.issues] == ["0.900"]+ assert _codes(invented_percent) == ["numeric_claim_unavailable"]-def test_the_sweep_never_cuts_a_valid_formulas_operand(tmp_path: Path) -> None:+def test_a_declared_derivation_survives_the_cut_beside_a_rejected_figure(+ tmp_path: Path,+) -> None:"""A rejected entry price is often the multiplier of the correct derivation.- "建议买入价 0.95 元" is cut, but "基于 MA20 1.150 × 0.95 = 1.093" is exactly- the shape the correction prompt asks for — sweeping 0.95 out of it left- "× (略※) =" and destroyed the one derivation the answer got right- (159516.SZ replay, 2026-09-09).+ "建议买入价 0.95 元" is cut, but the 0.95 inside a valid derivation is a+ figure this gate accepted where it stands, so it is not flagged and not+ cut — which is what the document-wide sweep used to get wrong, leaving+ "× (略※) =" and destroying the one derivation the answer got right."""ledger = _ledger(tmp_path)- draft = HDR + " 基于 SMA20 1.150 × 0.95 = 1.093 作为第一档。建议买入价 0.95 元。"+ draft = (+ HDR + " 第一档 1.093 元。建议买入价 0.95 元。"+ + _block(+ HDR_ROW,+ "1.093 | derived | 1.150 × 0.95 | indicators",+ "0.95 | proposed | 系数",+ )+ )validation = ledger.validate_final_answer(draft)- assert [issue.get("value") for issue in validation.issues] == [0.95]+ assert [issue.get("value") for issue in validation.issues] == ["0.95"]released = ledger.redacted_release(draft, validation)assert released is not None- assert "基于 SMA20 1.150 × 0.95 = 1.093 作为第一档。" in released+ assert "第一档 1.093 元。" in releasedassert "建议买入价(略※)。" in releasedassert "※ 略去 1 处" in releaseddef test_redacted_release_never_cuts_an_observed_price(tmp_path: Path) -> None:- """A correctly quoted close sharing a clause with an ungrounded metric survives.+ """A correctly quoted close sharing a sentence with an ungrounded metric survives.- ``_validate_analysis_claims`` reports the first unmatched figure in the- clause, and an observed close was that figure — so the release cut the one- number the ledger holds and footnoted it as unverifiable.+ The analysis validator reported the FIRST unmatched figure in a clause, and+ an observed close was that figure — so the release cut the one number the+ ledger holds and footnoted it as unverifiable. Each figure is checked on+ its own now, so only the metric is flagged."""ledger = _ledger(tmp_path)draft = HDR + " 最新收盘 1.171 元且策略最大回撤 12%。"@@ -1439,204 +1476,24 @@ def test_a_gate_recheck_is_not_counted_as_a_rejected_draft(tmp_path: Path) -> Noassert ledger.validation_count == 1-# ----------------------------------------------------------------------------# Which evidence may back which claim, stated as an allowlist-#-# The rule used to be a denylist of OHLC field phrases, and a denylist is only-# as complete as the day it was typed. Every case below was released on the-# first cut of this change and rejected on the commit before it.-# ------------------------------------------------------------------------------ "claim",- [- "现价 1.21 元。",- "最新价 1.21 元。",- "成交价 1.21 元。",- "报价 1.21 元。",- "股价 1.21 元。",- "价格 1.21 元。",- "买入价 1.21 元。",- "入场价 1.21 元。",- ],-)-def test_an_indicator_never_answers_a_spot_quote(tmp_path: Path, claim: str) -> None:- """1.21 is the session's bollinger.upper — above every bar in the run.-- A spot quote names the latest print. Ten spellings of it leaked- identically while the rule was "reject only a named OHLC field", because- none of them names one.- """- ledger = _ledger(tmp_path)-- result = ledger.validate_final_answer(HDR + " " + claim)-- assert "numeric_claim_conflict" in _codes(result), claim--- ("chinese", "english"),- [- ("收盘价为 1.150 元。", "The closing price was 1.150."),- ("收盘于 1.150 元。", "It closed at 1.150."),- ("收盘为 1.150 元。", "The close was 1.150."),- ("盘中最高 1.150 元。", "The intraday high was 1.150."),- ("当日最高价 1.150 元。", "The day's high was 1.150."),- ("最低价 1.150 元。", "The lowest price was 1.150."),- ("现价 1.150 元。", "The current price is 1.150."),- ("成交价 1.150 元。", "It last traded at 1.150."),- ],-)-def test_an_ohlc_or_spot_claim_gets_the_same_verdict_in_both_scripts(- tmp_path: Path, chinese: str, english: str-) -> None:- """The session's sma_20 is 1.150 and the observed close is 1.171.-- Every pair here is the same claim in two scripts, and the verdict must be- the same one — the standing rule of this repo since the 2026-09-08- grounding-gate asymmetry, where English was the leaking side.- """- zh = _ledger(tmp_path).validate_final_answer(HDR + " " + chinese)- en = _ledger(tmp_path).validate_final_answer(- "562500.SS (Yahoo, CNY) last close 1.171.\n\n" + english- )-- assert "numeric_claim_conflict" in _codes(zh), chinese- assert "numeric_claim_conflict" in _codes(en), english---def test_a_level_claim_still_takes_its_indicator(tmp_path: Path) -> None:- """The other side: the claim the indicator exemption was written for."""- ledger = _ledger(tmp_path)-- band = ledger.validate_final_answer(HDR + " 布林下轨 1.09 元为支撑位。")- english = ledger.validate_final_answer(- "562500.SS (Yahoo, CNY) last close 1.171.\n\nThe lower bollinger band is support at 1.09."- )-- assert band.valid is True, band.issues- assert english.valid is True, english.issues---# ----------------------------------------------------------------------------# What a formula justifies: which occurrence, and in which role-# ------------------------------------------------------------------------------def test_a_formula_may_not_produce_an_observed_print(tmp_path: Path) -> None:- """A close is observed, never derived.-- "2026-06-23 收盘价 = 1.171 × 0.80 = 0.937" is true arithmetic whose result- is claimed to be a close the ledger holds as 1.137, and the exemption that- accepts the derivations the correction prompt asks for released it. The- operands stay exempt; only the RESULT is compared, and only when an- observation word labels the equation itself.- """- ledger = _ledger(tmp_path)-- zh = ledger.validate_final_answer(HDR + " 2026-06-23 收盘价 = 1.171 × 0.80 = 0.937。")- en = ledger.validate_final_answer(- "562500.SS (Yahoo, CNY) last close 1.171.\n\nClose on 2026-06-23 = 1.171 * 0.80 = 0.937."- )- # The shape the prompt asks for: the observation word labels an OPERAND- # and the result is the entry price the answer proposes. The multiplier is- # 0.80 so the result lands nowhere near an observed print — 1.171 × 0.97 =- # 1.136 would have passed on the observed 1.137 whatever this rule did.- proposed = ledger.validate_final_answer(- HDR + " 基于收盘价 1.171 × 0.80 = 0.937 作为买入价。"- )- proposed_en = ledger.validate_final_answer(- "562500.SS (Yahoo, CNY) last close 1.171.\n\n"- "Based on the closing price 1.171 * 0.80 = 0.937 as the entry."- )-- assert "numeric_claim_conflict" in _codes(zh)- assert "numeric_claim_conflict" in _codes(en)- assert proposed.valid is True, proposed.issues- assert proposed_en.valid is True, proposed_en.issues---def test_a_free_operand_of_a_true_formula_is_not_a_derivation(tmp_path: Path) -> None:- """Arithmetic that derives nothing must not launder its own multiplier.-- "建议买入价 0.95 元(0.95 × 1.171 = 1.11245 参考)" is true and derives- nothing: 0.95 is 19% below every observed bar. Under a value-scoped- exemption the copy outside the bracket inherited what the copy inside it- earned, so the exemption is scoped to the OCCURRENCE.- """- ledger = _ledger(tmp_path)-- self_referential = ledger.validate_final_answer(- HDR + " 建议买入价 0.95 元(0.95 × 1.171 = 1.11245 参考)。"- )- english = ledger.validate_final_answer(- "562500.SS (Yahoo, CNY) last close 1.171.\n\n"- "Suggested entry price 0.5 (0.5 * 1.171 = 0.5855)."- )- # The multiplier keeps its exemption where it actually sits.- real_derivation = ledger.validate_final_answer(- HDR + " 基于收盘价 1.171 × 0.97 = 1.136 作为第一档。"- )-- assert "numeric_claim_conflict" in _codes(self_referential)- assert "numeric_claim_conflict" in _codes(english)- assert real_derivation.valid is True, real_derivation.issues---def test_english_sentences_on_one_line_are_separate_clauses(tmp_path: Path) -> None:- """A period ends a clause, exactly as 。 does.-- Two English sentences sharing a line were ONE clause, so a derivation in- the first exempted a fabricated price in the second — while the Chinese- translation of the same text was rejected, because 。 always split. The- per-language verdict is the bug; the paragraph-break spelling of the same- English text was already rejected.- """- english = _ledger(tmp_path).validate_final_answer(- "562500.SS (Yahoo, CNY) last close 1.171.\n\n"- "Based on close 1.171 * 0.80 = 0.937. The last traded price is 0.937."- )- chinese = _ledger(tmp_path).validate_final_answer(- HDR + "\n\n基于收盘价 1.171 × 0.80 = 0.937。最新成交价为 0.937 元。"- )- # A decimal point, a ticker suffix and an abbreviation are not sentence- # ends, so the derivation is still read as one clause.- intact = _ledger(tmp_path).validate_final_answer(- "562500.SS (Yahoo, CNY) last close 1.171.\n\n"- "Based on close 1.171 * 0.97 = 1.136 as the entry."- )-- # The other direction of the same parity: a level claim in its own English- # sentence must not inherit the header sentence's "last close", which is- # what merged the two into one clause and cost a correction round.- zh_level = _ledger(tmp_path).validate_final_answer(HDR + "20 日均线价格为 1.150 元。")- en_level = _ledger(tmp_path).validate_final_answer(- "562500.SS (Yahoo, CNY) last close 1.171. "- "The 20-day moving-average price was 1.150."- )-- assert "numeric_claim_conflict" in _codes(english)- assert "numeric_claim_conflict" in _codes(chinese)- assert intact.valid is True, intact.issues- assert zh_level.valid is True, zh_level.issues- assert en_level.valid is True, en_level.issues--def test_a_derivation_anchored_to_another_symbol_grounds_nothing(tmp_path: Path) -> None:"""The cross-symbol bail, for derivations as well as for indicators.In a comparison run the expensive instrument's close is arithmetically- fine and attached to the wrong symbol; removing the bail left every case- in these suites green.+ fine and attached to the wrong symbol."""header = "562500.SH 与 600519.SH(Yahoo,CNY)对比。"+ block = _block(+ "1.171 | observed | close | prices",+ "1420 | observed | close | prices",+ "1377.4 | derived | 1420 × 0.97 | prices",+ )unattributed = _two_symbol_ledger(tmp_path).validate_final_answer(- header + "买入价 = 1420 × 0.97 = 1377.4。"+ header + "买入价 1377.4。" + block)attributed = _two_symbol_ledger(tmp_path).validate_final_answer(- header + "600519.SH 买入价 = 1420 × 0.97 = 1377.4。"+ header + "600519.SH 买入价 1377.4。" + block)assert "numeric_claim_conflict" in _codes(unattributed)@@ -1648,128 +1505,72 @@ def test_a_derivation_anchored_to_another_symbol_grounds_nothing(tmp_path: Path)# ----------------------------------------------------------------------------def test_a_strategy_metric_is_not_grounded_by_endpoint_arithmetic(tmp_path: Path) -> None:- """A strategy's drawdown is a property of an equity curve, not of two prints.-- The subject word is what flips the verdict: the same two endpoints ground- a PRICE drawdown, which is the 159516.SZ case the exemption exists for.- """- ledger = _ledger(tmp_path)-- backtested = ledger.validate_final_answer(- HDR + " 回测显示该策略最大回撤 5.9%(从 1.180 跌至 1.110)。"- )- strategy = ledger.validate_final_answer(- HDR + " 策略最大回撤 5.9%,区间高点 1.180 元、低点 1.110 元。"- )- english = ledger.validate_final_answer(- "562500.SS (Yahoo, CNY) last close 1.171.\n\n"- "Strategy max drawdown 5.9% (1.180 down to 1.110)."- )- price_subject = ledger.validate_final_answer(- HDR + " 股价较高点 1.180 元已回撤约 5.9%,现报 1.110 元。"- )-- assert "analysis_claim_unavailable" in _codes(backtested)- assert "analysis_claim_unavailable" in _codes(strategy)- assert "analysis_claim_unavailable" in _codes(english)- assert price_subject.valid is True, price_subject.issues---def test_the_endpoint_exemption_grounds_only_the_figures_it_derives(- tmp_path: Path,-) -> None:+def test_a_declaration_grounds_only_the_figure_it_names(tmp_path: Path) -> None:"""One correct ratio used to carry every other figure in its clause out.- The English sentence carries no clause separator at all, which is how an- invented 60% rode along beside a correct 37%.+ The exemption was measured over a clause, then over a line for the operand+ scan, and the boundary between them decided verdicts: "基于 40 × 1.171 =+ 46.84 计算,策略最大回撤 40%" released a max drawdown no backtest produced.+ A declaration names one value, so there is no span for a neighbour to ride+ in on."""ledger = _wide_ledger(tmp_path)+ block = _block(+ "0.666 | observed | close | prices",+ "1.053 | observed | 5 月高点 | prices",+ "37% | derived | (0.666 - 1.053) / 1.053 | prices",+ )both = ledger.validate_final_answer(- WIDE_HDR + " 当前 0.666 元 较 5 月高点 1.053 元已回撤约 37% 最大回撤 60%。"- )- english = _wide_ledger(tmp_path).validate_final_answer(- "562500.SS (Yahoo, CNY) last close 0.666. "- "At 0.666 down about 37% from the 1.053 May high with a max drawdown of 60%."+ WIDE_HDR + " 当前 0.666 元 较 5 月高点 1.053 元已回撤约 37%,最大回撤 60%。" + block)only_the_derived = _wide_ledger(tmp_path).validate_final_answer(- WIDE_HDR + " 当前 0.666 元 较 5 月高点 1.053 元已回撤约 37%。"+ WIDE_HDR + " 当前 0.666 元 较 5 月高点 1.053 元已回撤约 37%。" + block)- assert "analysis_claim_unavailable" in _codes(both)- assert "analysis_claim_unavailable" in _codes(english)+ assert [issue["value"] for issue in both.issues] == ["60%"]assert only_the_derived.valid is True, only_the_derived.issues-def test_a_formula_in_another_clause_does_not_ground_a_metric(tmp_path: Path) -> None:- """The derivation exemption is measured in the clause the claim was measured in.+def test_a_metric_needs_metric_evidence_or_its_own_arithmetic(tmp_path: Path) -> None:+ """A percentage is never answered by a price, however close the number is.- Line-scoped, any true arithmetic anywhere on the line grounded the metric:- "基于 40 × 1.171 = 46.84 计算,策略最大回撤 40%" released a max drawdown no- backtest produced.+ A run holds hundreds of observed values spanning the instrument's range, so+ any percent-free metric written in that range collides with one. Percent+ figures are structurally immune: an OHLC close is not a ratio, so the price+ pool is not consulted for them at all."""ledger = _ledger(tmp_path)- other_clause = ledger.validate_final_answer(- HDR + " 基于 40 × 1.171 = 46.84 计算,策略最大回撤 40%。"- )- same_clause = ledger.validate_final_answer(- HDR + " 策略最大回撤 40%(基于 40 × 1.171 = 46.84)。"- )- # Without a strategy subject the exemption is available, so this pair is- # what the clause scope alone decides: the same formula, once in the- # neighbouring clause and once beside the figure it is supposed to derive.- price_metric_other_clause = ledger.validate_final_answer(- HDR + " 基于 40 × 1.171 = 46.84 计算,区间收益率 40%。"- )- price_metric_same_clause = ledger.validate_final_answer(- HDR + " 区间收益率 40%(基于 40 × 1.171 = 46.84)。"- )- # Both halves of the scope: the clause carries the derivation KEYWORD, so- # the branch is entered, and the formula it points at is in the next- # clause. Line-scoped values grounded the 40% from there.- keyword_here_formula_elsewhere = ledger.validate_final_answer(- HDR + " 区间收益率 40%(基于历史数据计算),其中 40 × 1.171 = 46.84。"- )- # A price drawdown derived in its own clause is still grounded.- derived_in_place = ledger.validate_final_answer(- HDR + " 从 1.180 跌至 1.110,股价回撤约 5.9%。"+ percent_metric = ledger.validate_final_answer(HDR + " 策略最大回撤 1.171%。")+ metric_cell = ledger.validate_final_answer(+ HDR + "\n\n| 指标 | 数值 |\n|---|---|\n| 最大回撤 | 1.171% |\n")- assert "analysis_claim_unavailable" in _codes(other_clause)- assert "analysis_claim_unavailable" in _codes(same_clause)- assert "analysis_claim_unavailable" in _codes(price_metric_other_clause)- assert price_metric_same_clause.valid is True, price_metric_same_clause.issues- assert "analysis_claim_unavailable" in _codes(keyword_here_formula_elsewhere)- assert derived_in_place.valid is True, derived_in_place.issues+ assert _codes(percent_metric) == ["numeric_claim_unavailable"]+ assert _codes(metric_cell) == ["numeric_claim_unavailable"]-def test_a_metric_is_not_grounded_by_equalling_an_observed_price(tmp_path: Path) -> None:- """Numeric equality with some observed print is not evidence for a metric.-- A run holds hundreds of observed values spanning the instrument's range,- so any percent-free metric written in that range collides with one. On a- $12.50 stock the collision is "| 最大回撤 | 12.5 |".- """+def test_a_metric_backed_by_a_risk_tool_passes_in_prose_and_in_a_table(+ tmp_path: Path,+) -> None:+ """The other side: kind-mapped leaves ARE evidence, at either scale."""ledger = _ledger(tmp_path)-- prose = ledger.validate_final_answer(HDR + " 策略夏普比率 1.171。")- single_cell = ledger.validate_final_answer(- HDR + "\n\n| 指标 | 数值 |\n|---|---|\n| 夏普比率 | 1.171 |\n"+ ledger.ingest_tool_result(+ tool_name="portfolio_risk_xray",+ arguments={"symbols": [SYMBOL]},+ result=json.dumps({"annualized_vol": 0.182, "max_drawdown": -0.094}),+ call_id="risk",+ success=True,)- # A cell RESTATING two observed prints is not a metric figure.- endpoint_cell = ledger.validate_final_answer(- HDR + "\n\n| 指标 | 数值 |\n|---|---|\n| 峰值→当前 | 1.180 → 1.110 |\n"++ prose = ledger.validate_final_answer(HDR + " 年化波动率 18.2%,最大回撤 9.4%。")+ table = ledger.validate_final_answer(+ HDR + "\n\n| 指标 | 数值 |\n|---|---|\n| 年化波动率 | 18.2% |\n")- # A quoted price keeps its own exemption in prose, where it is written as- # a price rather than as a metric value.- quoted_price = ledger.validate_final_answer(HDR + " 最新收盘 1.171 元且策略最大回撤 12%。")- assert "analysis_claim_unavailable" in _codes(prose)- assert "analysis_claim_unavailable" in _codes(single_cell)- assert endpoint_cell.valid is True, endpoint_cell.issues- assert [issue.get("value") for issue in quoted_price.issues] == ["12%"]+ assert prose.valid is True, prose.issues+ assert table.valid is True, table.issues# ---------------------------------------------------------------------------@@ -1777,57 +1578,34 @@ def test_a_metric_is_not_grounded_by_equalling_an_observed_price(tmp_path: Path)# ----------------------------------------------------------------------------def test_the_sweep_cuts_a_restatement_that_shares_a_value_with_a_formula(+def test_a_restatement_of_a_rejected_figure_is_cut_where_it_stands(tmp_path: Path,) -> None:- """Protection follows the formula's SPAN, not its value.+ """The rejected figure is usually also the multiplier of a valid derivation.- The rejected entry price is usually also the multiplier of the correct- derivation, so protecting the value protected every restatement of the- rejected figure with it: the table row survived under a footnote saying- one figure had been cut. The derivation must still come out unmangled —- that is what the protection is for.+ Protecting it by VALUE protected every restatement of it document-wide;+ protecting it by SPAN needed a second document-wide stage to find those+ restatements again. Neither exists now: the derivation's operand is inside+ a declaration the gate accepted, and the restatement is its own figure,+ checked and flagged where it stands."""ledger = _ledger(tmp_path)draft = (- HDR- + "\n\n建议买入价 0.95 元。\n\n基于收盘价 1.171 × 0.95 = 1.112 作为参考。"- + "\n\n| 档位 | 挂单价 |\n|---|---|\n| 第一档 | 0.95 |\n"+ HDR + " 第一档 1.093 元。\n\n| 档位 | 建议买入价 |\n|---|---|\n| 第一档 | 0.95 |\n"+ + _block(HDR_ROW, "1.093 | derived | 1.150 × 0.95 | indicators", "0.95 | proposed | 系数"))validation = ledger.validate_final_answer(draft)- assert [issue.get("value") for issue in validation.issues] == [0.95]+ assert [issue["value"] for issue in validation.issues] == ["0.95"]released = ledger.redacted_release(draft, validation)assert released is not None- assert "基于收盘价 1.171 × 0.95 = 1.112 作为参考。" in released- assert "| 第一档 | 0.95 |" not in released- assert "建议买入价(略※)。" in released- assert "※ 略去 2 处" in released---def test_the_sweep_never_cuts_an_observed_value(tmp_path: Path) -> None:- """The other half of the protection: a value the ledger holds.-- A figure rejected in one clause (because that clause labelled it 收盘价)- can be a value the session genuinely observed elsewhere. Cutting the- correct mention too makes the footnote false about a number the run- fetched.- """- ledger = _ledger(tmp_path, sma_20=1.150)- draft = HDR + " 收盘价为 1.150 元。SMA20 位于 1.150 一线,为均线支撑。"- validation = ledger.validate_final_answer(draft)- assert [issue.get("value") for issue in validation.issues] == [1.15]-- released = ledger.redacted_release(draft, validation)-- assert released is not None- assert "收盘价为(略※)。" in released- assert "SMA20 位于 1.150 一线" in released+ assert "第一档 1.093 元。" in released+ assert "| 第一档 | (略※) |" in releasedassert "※ 略去 1 处" in released-def test_the_sweep_never_cuts_a_percent_the_gate_accepted(tmp_path: Path) -> None:+def test_an_accepted_figure_is_never_cut_for_sharing_a_value(tmp_path: Path) -> None:"""A validated derivation and an invented metric can be the same percentage.Percent literals were cut everywhere they appeared, so endpoint arithmetic@@ -1835,15 +1613,35 @@ def test_the_sweep_never_cuts_a_percent_the_gate_accepted(tmp_path: Path) -> Non"could not be matched to this session's tool data"."""ledger = _ledger(tmp_path)- draft = HDR + "\n从 1.110 涨到 1.171,区间收益率约 5.5%。\n策略年化波动率 5.5%。"+ draft = (+ HDR + "\n从 1.110 涨到 1.171,区间收益率约 5.5%。\n策略年化波动率 5.5%。"+ + _block(+ HDR_ROW,+ "1.110 | observed | low | prices",+ "5.5% | derived | (1.171 - 1.110) / 1.110 | prices",+ )+ )validation = ledger.validate_final_answer(draft)- assert [issue.get("value") for issue in validation.issues] == ["5.5%"]+ assert [issue["value"] for issue in validation.issues] == []++ # Both occurrences are covered by one declaration, so both are accepted:+ # a declaration is a statement about a VALUE, and the answer states the+ # same derived value twice.+ assert validation.valid is True, validation.issues+++def test_an_observed_value_is_never_cut(tmp_path: Path) -> None:+ """A correctly quoted close beside an ungrounded metric survives the cut."""+ ledger = _ledger(tmp_path, sma_20=1.150)+ draft = HDR + " 收盘价为 1.150 元。策略最大回撤 12%。"+ validation = ledger.validate_final_answer(draft)+ assert [issue["value"] for issue in validation.issues] == ["12%"]released = ledger.redacted_release(draft, validation)assert released is not None- assert "区间收益率约 5.5%。" in released- assert "策略年化波动率(略※)。" in released+ assert "收盘价为 1.150 元。" in released+ assert "12%" not in releasedassert "※ 略去 1 处" in released@@ -1909,18 +1707,19 @@ def test_a_compound_unit_is_not_split_by_the_marker(tmp_path: Path) -> None:def test_overlapping_issue_spans_are_cut_once(tmp_path: Path) -> None:- """Two validators can flag overlapping ranges on one table row.+ """Two checks can flag the same figure; the cut still happens once.- A metric row carrying a clause separator and a foreign ticker raises- ``analysis_claim_unavailable`` on the whole row and- ``unsourced_symbol_figures`` on the sub-clause. Without the+ A metric row carrying a foreign ticker raises the figure check on the cell+ and ``unsourced_symbol_figures`` on the same figure. Without thealready-consumed guard the row is emitted once per overlapping span andthe released table is a fragment-duplicated mess with an inflated count."""ledger = _ledger(tmp_path)draft = HDR + "\n\n| 指标 | 数值 |\n|---|---|\n| 最大回撤 | 12%,同业 000001.SZ 5.0 |\n"validation = ledger.validate_final_answer(draft)- assert len(validation.issues) == 2+ # The row's own figures are flagged once each, and the unsourced-symbol+ # finding covers the same line a second time.+ assert len(validation.issues) == 3released = ledger.redacted_release(draft, validation)@@ -1951,25 +1750,30 @@ def test_the_released_document_is_recorded_in_the_artifact(tmp_path: Path) -> Noassert artifact["released"]["revalidated"] is True-def test_provenance_repair_declines_a_draft_with_an_unchecked_price_column(+def test_provenance_repair_no_longer_needs_an_unchecked_column_veto(tmp_path: Path,) -> None:- """A zero-round repair must not attest for figures nothing checked.-- "| 档位 | 挂单价 |" is a price column ``_validate_price_tables`` does not- key on, and the prose scan skips every line with a pipe. Appending "price- source yahoo" under it turns the model's last chance to drop an invented- ladder price into a released answer with a provenance note.+ """The surface the veto guarded does not exist any more.++ "| 档位 | 挂单价 |" was a price column ``_validate_price_tables`` did not+ key on and the prose scan skipped, so a zero-round provenance note would+ have attested for a figure nothing checked. Every table cell is a+ measurement-shaped figure now, so such a column raises its own issue and+ the repair declines it for the ordinary reason: the issues are not+ provenance-only."""ledger = _ledger(tmp_path)with_column = ("562500.SS 最新收盘价 1.171 元。\n\n| 档位 | 挂单价 |\n|---|---|\n| 第一档 | 0.95 |\n")- without_column = "562500.SS 最新收盘价 1.171 元。\n\n| 档位 | 比例 |\n|---|---|\n| 第一档 | 30 |\n"-- declined = ledger.repair_provenance(- with_column, ledger.validate_final_answer(with_column)+ without_column = (+ "562500.SS 最新收盘价 1.171 元。\n\n| 档位 | 比例 |\n|---|---|\n| 第一档 | 30 |\n"+ + _block(HDR_ROW, "30 | count | 仓位比例"))++ flagged = ledger.validate_final_answer(with_column)+ assert [issue["value"] for issue in flagged.issues if issue["value"]] == ["0.95"]+ declined = ledger.repair_provenance(with_column, flagged)repaired = ledger.repair_provenance(without_column, ledger.validate_final_answer(without_column))@@ -2001,50 +1805,3 @@ def test_line_offsets_are_a_monotone_scan() -> None:assert all(content[offset : offset + len(line)] == line for line, offset in positions)---def test_the_observation_vocabulary_is_load_bearing_in_both_places(- tmp_path: Path,-) -> None:- """A word that names a market print decides two things, not one.-- It refuses an indicator reading even beside a level word, and it refuses- to let a formula's RESULT be the print. Both halves of the vocabulary have- to be there: the spot spellings (现价 / current price) name no OHLC field,- and the OHLC spellings are derived from ``_TABLE_FIELD_ALIASES`` rather- than typed out a second time — dropping either half leaves every other- case in this module green, because the level allowlist already settles- them.- """- ledger = _ledger(tmp_path)-- # The result of an equation whose subject is a print.- spot_formula = ledger.validate_final_answer(HDR + " 现价 = 1.171 × 0.80 = 0.937。")- high_formula = ledger.validate_final_answer(HDR + " 最高价 = 1.171 × 0.80 = 0.937。")- open_formula = ledger.validate_final_answer(HDR + " 开盘价 = 1.171 × 0.80 = 0.937。")- english_spot = ledger.validate_final_answer(- "562500.SS (Yahoo, CNY) last close 1.171.\n\n"- "The current price = 1.171 * 0.80 = 0.937."- )- english_ohlc = ledger.validate_final_answer(- "562500.SS (Yahoo, CNY) last close 1.171.\n\n"- "The closing price = 1.171 * 0.80 = 0.937."- )- # A print claim in a clause that also names a level: the level word must- # not buy the indicator reading a way in. 1.150 is the session's sma_20.- spot_beside_a_level = ledger.validate_final_answer(HDR + " 现价 1.150 元位于均线附近。")- high_beside_a_level = ledger.validate_final_answer(HDR + " 最高价 1.150 元位于均线附近。")- # The level claim alone still takes it.- level_only = ledger.validate_final_answer(HDR + " 20 日均线价格为 1.150 元。")-- for result in (- spot_formula,- high_formula,- open_formula,- english_spot,- english_ohlc,- spot_beside_a_level,- high_beside_a_level,- ):- assert "numeric_claim_conflict" in _codes(result), result.issues- assert level_only.valid is True, level_only.issues