Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(grounding): a tail-risk figure names its field once a session holds more than one (#1425)

Haozhe Wu6e62139ef585
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.py
index fe3da4507..865c27277 100644
--- a/agent/src/agent/context.py
+++ b/agent/src/agent/context.py
@@ -196,7 +196,11 @@ Decide which workflow to use based on the request:
a metric whose identity matters (VaR vs ES, 95% vs 99%), use the result field
as `ref`: `data.tail_risk.var_95` or just `var_95` from `portfolio_risk_xray`,
`historical_var` from `quantlib_call`. When more than one call returned that
- field (historical_var at 95% and at 99%), name the call: `q1::historical_var`;
+ field (historical_var at 95% and at 99%), name the call: `q1::historical_var`.
+ Once this session holds more than one tail-risk measurement (a VaR and an ES,
+ or 95% and 99%), EVERY tail-risk figure needs that field ref — a call id or no
+ declaration at all cannot say which of them you are quoting, and the figure is
+ sent back for correction;
`derived` — arithmetic on observed values (`note`: the formula; every number
added or subtracted must itself be an observed value);
`proposed` — a price level you suggest, such as an entry, stop or target: inside
diff --git a/agent/src/agent/grounding/evidence.py b/agent/src/agent/grounding/evidence.py
index e5e7c327d..07234ce27 100644
--- a/agent/src/agent/grounding/evidence.py
+++ b/agent/src/agent/grounding/evidence.py
@@ -366,6 +366,47 @@ _QUALIFIER_SUFFIXES = frozenset(
)
+#: Tail-risk measure per field-name token, scanned right to left like every
+#: other head-noun rule in this module. VaR and ES/CVaR are different
+#: measurements of the same family, and 95% and 99% are different numbers of
+#: either, so the family alone cannot say which value a figure quotes (#1425).
+_TAIL_RISK_MEASURE_TOKENS = {
+ "var": "var",
+ "cvar": "es",
+ "es": "es",
+ "shortfall": "es",
+}
+
+
+def tail_risk_identity(path: str) -> str | None:
+ """The tail-risk identity an evidence field names, e.g. ``var_95``.
+
+ Read off the FIELD NAME a tool returned — never off answer prose, which the
+ gate does not interpret. ``data.tail_risk.var_95`` and ``historical_var``
+ are ``var_95`` and ``var``; ``cvar_99`` and ``es_99`` are both ``es_99``,
+ which is the point: they are the same measurement under two names.
+
+ Args:
+ path: Evidence JSON path or leaf name.
+
+ Returns:
+ ``"<measure>"`` or ``"<measure>_<confidence>"``, or None when the field
+ is not a tail-risk value at all.
+ """
+ if _metric_kind_for_path(path) != "tail_risk":
+ return None
+ tokens = [token for token in re.split(r"[_.]", _leaf_name(path)) if token]
+ confidence = tokens[-1] if tokens and tokens[-1].isdigit() else ""
+ measure = None
+ for token in reversed([token for token in tokens if not token.isdigit()]):
+ measure = _TAIL_RISK_MEASURE_TOKENS.get(token)
+ if measure is not None:
+ break
+ if measure is None:
+ return None
+ return f"{measure}_{confidence}" if confidence else measure
+
+
def _metric_kind_for_path(path: str) -> str | None:
"""Map an evidence JSON path to an analysis metric kind.
diff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.py
index bf1b801c8..0a511ce2b 100644
--- a/agent/src/agent/grounding/policies.py
+++ b/agent/src/agent/grounding/policies.py
@@ -11,7 +11,7 @@ import ast
import json
import math
from dataclasses import dataclass, field
-from typing import Any, Callable, Iterable, Sequence
+from typing import Any, Callable, Iterable, Mapping, Sequence
from src.agent.grounding.identity import (
_CANONICAL_SYMBOL_RE,
@@ -26,6 +26,7 @@ from src.agent.grounding.evidence import (
_metric_kind_for_path,
_price_field_for_path,
_timestamp_matches_claim_date,
+ tail_risk_identity,
)
from src.agent.grounding.figures import (
Declaration,
@@ -784,6 +785,61 @@ class _PolicyMixin:
return []
return sorted({f"{call}::{path}" for call, path, _ in sources})
+ def _tail_risk_sources(
+ self,
+ records: Sequence[EvidenceRecord],
+ entries: Iterable[Mapping[str, Any]] = (),
+ ) -> list[tuple[str, float]]:
+ """``(identity, value)`` for every tail-risk value among these sources.
+
+ Identity is read off the field name (:func:`tail_risk_identity`), so
+ ``var_95`` and ``es_95`` are two identities and ``cvar_99`` / ``es_99``
+ are one.
+ """
+ sources: list[tuple[str, float]] = []
+ for record in records:
+ identity = tail_risk_identity(record.field)
+ if identity and record.status == "observed" and record.value is not None:
+ sources.append((identity, float(record.value)))
+ for entry in entries:
+ identity = tail_risk_identity(str(entry.get("field") or ""))
+ if identity and entry.get("value") is not None:
+ sources.append((identity, float(entry["value"])))
+ return sources
+
+ def _tail_risk_ref_required(
+ self,
+ figure: Figure,
+ records: Sequence[EvidenceRecord],
+ entries: Iterable[Mapping[str, Any]] = (),
+ ) -> list[str]:
+ """Tail-risk identities this figure could be quoting, when there are several.
+
+ #1425's remaining half, decided as a policy rather than patched: a
+ session that observed more than one tail-risk identity cannot tell which
+ one an undeclared or call-scoped figure means — the gate reads a
+ number's shape, never the words "VaR 99%" beside it — so the figure has
+ to name its field. A ref that names the field narrows the scope to one
+ identity before this runs, so a declared figure never reaches here.
+
+ Empty when the scope holds at most one identity (nothing to confuse) or
+ when the figure matches none of the tail-risk values, which keeps every
+ other kind of figure on exactly today's path.
+
+ Returns:
+ Sorted identities, or an empty list when no ref is required.
+ """
+ sources = self._tail_risk_sources(records, entries)
+ if len({identity for identity, _ in sources}) < 2:
+ return []
+ return sorted(
+ {
+ identity
+ for identity, value in sources
+ if self._matches_evidence(figure, [value], [value])
+ }
+ )
+
def _price_pool(
self,
symbol: str | None,
@@ -1031,8 +1087,43 @@ class _PolicyMixin:
scoped_records, metric_values = scoped
values = [float(record.value) for record in scoped_records] + metric_values
money = figure.currency and not figure.percent
+ # A call- or tool-scoped ref pools every field that call returned,
+ # so it cannot choose between the tail-risk identities in it (#1425).
+ scoped_entries = [
+ entry
+ for entry in self._analysis_metrics
+ if declaration.ref in (entry.get("call_id"), entry.get("tool"))
+ ]
+ tail_risk = self._tail_risk_ref_required(
+ figure, scoped_records, scoped_entries
+ )
+ scoped_identities: list[str] = []
+ if tail_risk:
+ scoped_sources = self._tail_risk_sources(scoped_records, scoped_entries)
+ scoped_identities = sorted({identity for identity, _ in scoped_sources})
+ # Whatever else the call returned may still answer the figure.
+ blocked = {
+ value for identity, value in scoped_sources if identity in tail_risk
+ }
+ values = [value for value in values if value not in blocked]
if self._matches_evidence(figure, values, [] if money else values):
return []
+ if tail_risk:
+ return [
+ self._figure_issue(
+ "numeric_claim_conflict",
+ figure,
+ "observed",
+ symbol,
+ "tail_risk_needs_field_ref",
+ f"is declared observed from {declaration.ref}, which returned "
+ f"{', '.join(scoped_identities)} and matches "
+ f"{', '.join(tail_risk)}; a tail-risk figure has to name the "
+ "field it quotes",
+ source_tool_call_ids=[declaration.ref],
+ ambiguous_sources=scoped_identities,
+ )
+ ]
ambiguous = self._ambiguous_field_sources(declaration.ref, symbol)
if ambiguous:
return [
@@ -1075,7 +1166,29 @@ class _PolicyMixin:
direct, scaled = prices + self._row_pool(symbol, money_only=True), []
else:
direct, scaled = prices + self._row_pool(symbol), self._metric_pool(symbol)
- if not direct and not scaled:
+ # An undeclared tail-risk figure is matched against every tail-risk
+ # value in the session, so it needs a field ref for the same reason a
+ # call-scoped one does (#1425).
+ session_records = [
+ record
+ for record in self._evidence
+ if not symbol or not record.symbol or record.symbol == symbol
+ ]
+ tail_risk = self._tail_risk_ref_required(
+ figure, session_records, self._analysis_metrics
+ )
+ session_identities: list[str] = []
+ if tail_risk:
+ session_sources = self._tail_risk_sources(
+ session_records, self._analysis_metrics
+ )
+ session_identities = sorted({identity for identity, _ in session_sources})
+ blocked = {
+ value for identity, value in session_sources if identity in tail_risk
+ }
+ direct = [value for value in direct if value not in blocked]
+ scaled = [value for value in scaled if value not in blocked]
+ if not direct and not scaled and not tail_risk:
return [
self._figure_issue(
"numeric_claim_unavailable",
@@ -1091,6 +1204,20 @@ class _PolicyMixin:
]
if self._matches_evidence(figure, direct, scaled, legacy_direct=True):
return []
+ if tail_risk:
+ return [
+ self._figure_issue(
+ "numeric_claim_conflict",
+ figure,
+ "observed",
+ symbol,
+ "tail_risk_needs_field_ref",
+ f"matches {', '.join(tail_risk)}, and this session observed "
+ f"{', '.join(session_identities)}, so the figure has to name "
+ "the field it quotes",
+ ambiguous_sources=session_identities,
+ )
+ ]
observed = sorted(direct or scaled)
attributable = symbol is not None or len(
{record.symbol for record in records if record.symbol}
diff --git a/agent/src/agent/grounding/release.py b/agent/src/agent/grounding/release.py
index f9eaa5c27..e91564695 100644
--- a/agent/src/agent/grounding/release.py
+++ b/agent/src/agent/grounding/release.py
@@ -74,6 +74,7 @@ _CORRECTION_REASONS = {
"value_mismatch": "the observed evidence is {range}",
"not_in_referenced_call": "call {ref} returned no such value",
"ambiguous_field_ref": "{ref} names {sources}, which hold different values; use the one quoted as the ref",
+ "tail_risk_needs_field_ref": "this session holds {sources}, which are different measurements; declare the figure with a ref naming the field it quotes (data.tail_risk.var_99, var_99, or q1::historical_var)",
"no_formula": "its note states no arithmetic",
"formula_not_evaluable": "its note is not an arithmetic expression over two or more operands",
"formula_not_anchored": "no operand of its note is a value this session observed",
diff --git a/agent/tests/test_grounding_role_hardening.py b/agent/tests/test_grounding_role_hardening.py
index 574e3edce..0e54d5ada 100644
--- a/agent/tests/test_grounding_role_hardening.py
+++ b/agent/tests/test_grounding_role_hardening.py
@@ -577,7 +577,7 @@ def _pct(value: float) -> str:
return f"{abs(value) * 100:.2f}%"
[email protected]("ref", ["data.tail_risk.var_95", "tail_risk.var_95", "var_95", "x1"])
[email protected]("ref", ["data.tail_risk.var_95", "tail_risk.var_95", "var_95"])
def test_a_tail_risk_ref_grounds_its_own_value(tmp_path: Path, ref: str) -> None:
result = _ledger(tmp_path, MARKET_A, XRAY).validate_final_answer(
HDR + " VaR 95%: 1.57%。" + _block(ROW, "95% | count | confidence", f"1.57% | observed | VaR 95% | {ref}")
@@ -585,6 +585,89 @@ def test_a_tail_risk_ref_grounds_its_own_value(tmp_path: Path, ref: str) -> None
assert result.valid is True, result.issues
+#: One tail-risk identity in the whole session: nothing to choose between.
+XRAY_ONE = (
+ "portfolio_risk_xray",
+ {"symbols": [A]},
+ {"status": "ok", "data": {"tail_risk": {"var_95": 0.0157}}},
+ "x1",
+)
+
+
+def test_a_call_scoped_ref_does_not_choose_a_tail_risk_identity(tmp_path: Path) -> None:
+ """#1425's remaining half: ``ref x1`` pools every tail-risk field that call
+ returned, so it cannot say whether 1.57% is the VaR 95% or the ES 95%.
+
+ This is the policy the owner decided on 2026-09-23 rather than a patch: when
+ a session holds more than one tail-risk identity, the figure has to name its
+ field. It costs a correction round on an answer that reads correctly today,
+ which is the price of the gate not reading the words "VaR 95%" beside it.
+ """
+ result = _ledger(tmp_path, MARKET_A, XRAY).validate_final_answer(
+ HDR + " VaR 95%: 1.57%。" + _block(ROW, "95% | count | confidence", "1.57% | observed | VaR 95% | x1")
+ )
+
+ assert result.valid is False
+ assert _reasons(result) == ["tail_risk_needs_field_ref"]
+ # The correction names every identity the call returned, so the model can
+ # pick one, not just the one the number happened to match.
+ assert result.issues[0]["ambiguous_sources"] == ["es_95", "es_99", "var_95", "var_99"]
+
+
+def test_an_undeclared_tail_risk_percent_needs_a_field_ref(tmp_path: Path) -> None:
+ """The undeclared half of the same rule: a percent a tool returned needs no
+ declaration, so it was matched against every tail-risk value in the session.
+ """
+ result = _ledger(tmp_path, MARKET_A, XRAY).validate_final_answer(HDR + " 单日 VaR 为 1.57%。")
+
+ assert result.valid is False
+ assert _reasons(result) == ["tail_risk_needs_field_ref"]
+
+
+def test_one_tail_risk_identity_still_grounds_without_a_ref(tmp_path: Path) -> None:
+ """The other side of the guard: the rule fires on ambiguity, not on tail risk.
+
+ Same claim, same prose, a session holding only ``var_95`` -- no ref needed,
+ and an invented value is still rejected.
+ """
+ grounded = _ledger(tmp_path, MARKET_A, XRAY_ONE).validate_final_answer(
+ HDR + " 单日 VaR 为 1.57%。"
+ )
+ invented = _ledger(tmp_path, MARKET_A, XRAY_ONE).validate_final_answer(
+ HDR + " 单日 VaR 为 3.10%。"
+ )
+
+ assert grounded.valid is True, grounded.issues
+ assert invented.valid is False
+
+
+def test_an_invented_value_is_a_mismatch_not_a_missing_ref(tmp_path: Path) -> None:
+ """The rule keys on the value the figure matches, not on the session merely
+ holding tail risk: 2.11% is the ES 95% and needs a ref, while 3.10% is in no
+ tail-risk field and must keep saying so -- a fabricated number told to "add a
+ ref" would send the model looking for a field that holds it."""
+ ambiguous = _ledger(tmp_path / "a", MARKET_A, XRAY).validate_final_answer(
+ HDR + " 单日 VaR 为 2.11%。"
+ )
+ invented = _ledger(tmp_path / "b", MARKET_A, XRAY).validate_final_answer(
+ HDR + " 单日 VaR 为 3.10%。"
+ )
+
+ assert _reasons(ambiguous) == ["tail_risk_needs_field_ref"]
+ assert _reasons(invented) == ["value_mismatch"]
+
+
+def test_a_non_tail_risk_figure_is_untouched_by_the_ref_rule(tmp_path: Path) -> None:
+ """A sharpe from another call still grounds off a call-scoped ref while the
+ session holds four tail-risk identities -- the rule keys on the value the
+ figure matches, not on the session having tail risk in it."""
+ result = _ledger(tmp_path, MARKET_A, XRAY, FACTOR_A).validate_final_answer(
+ HDR + " 夏普 0.888。" + _block(ROW, "0.888 | observed | sharpe | fa")
+ )
+
+ assert result.valid is True, result.issues
+
+
@pytest.mark.parametrize(
("claim", "ref"),
[