Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(grounding): list exact refs for ambiguous fields

zeus22939c3002e8756
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.py
index 865c27277..c328b5449 100644
--- a/agent/src/agent/context.py
+++ b/agent/src/agent/context.py
@@ -195,8 +195,9 @@ Decide which workflow to use based on the request:
PE ratio (`ref`: the tool name such as `get_fundamentals`, or its call id). For
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`.
+ `historical_var` from `quantlib_call`. When more than one call returned the
+ same field, name the exact call as `call_id::field` (for example
+ `q1::historical_var`); a tool name is not a call id.
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
diff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.py
index 8bf702485..cbd426d0c 100644
--- a/agent/src/agent/grounding/policies.py
+++ b/agent/src/agent/grounding/policies.py
@@ -810,6 +810,54 @@ class _PolicyMixin:
sources.append((identity, float(entry["value"])))
return sources
+ @staticmethod
+ def _tail_risk_field_refs(
+ records: Sequence[EvidenceRecord],
+ entries: Iterable[Mapping[str, Any]] = (),
+ ) -> list[str]:
+ """Exact call_id::field refs available for tail-risk evidence."""
+ refs = {
+ f"{record.call_id}::{record.field}"
+ for record in records
+ if record.call_id
+ and record.field
+ and record.status == "observed"
+ and record.value is not None
+ and tail_risk_identity(record.field)
+ }
+ refs |= {
+ f"{entry.get('call_id')}::{entry.get('field')}"
+ for entry in entries
+ if entry.get("call_id")
+ and entry.get("field")
+ and entry.get("value") is not None
+ and tail_risk_identity(str(entry.get("field") or ""))
+ }
+ return sorted(refs)
+
+ def _tool_field_ref_candidates(
+ self, ref: str, symbol: str | None
+ ) -> list[str]:
+ """Exact call refs for a mistaken tool_name::field declaration."""
+ key = (ref or "").strip()
+ if "::" not in key:
+ return []
+ scope, field = (part.strip() for part in key.split("::", 1))
+ if not scope or not field:
+ return []
+ records, entries = self._field_sources(field, symbol)
+ refs = {
+ f"{record.call_id}::{record.field}"
+ for record in records
+ if record.tool == scope and record.call_id and record.field
+ }
+ refs |= {
+ f"{entry.get('call_id')}::{entry.get('field')}"
+ for entry in entries
+ if entry.get("tool") == scope and entry.get("call_id") and entry.get("field")
+ }
+ return sorted(refs)
+
def _tail_risk_ref_required(
self,
figure: Figure,
@@ -1088,6 +1136,29 @@ class _PolicyMixin:
scoped = self._referenced(declaration.ref, symbol, figure) if declaration else None
if scoped is not None:
scoped_records, metric_values = scoped
+ if (
+ declaration is not None
+ and not scoped_records
+ and not metric_values
+ ):
+ call_field_candidates = self._tool_field_ref_candidates(
+ declaration.ref, symbol
+ )
+ if call_field_candidates:
+ return [
+ self._figure_issue(
+ "numeric_claim_conflict",
+ figure,
+ "observed",
+ symbol,
+ "field_ref_needs_call_id",
+ f"is declared observed from {declaration.ref}, whose left side is "
+ "a tool name rather than one exact call id",
+ source_tool_call_ids=[declaration.ref],
+ ambiguous_sources=call_field_candidates,
+ field_ref_candidates=call_field_candidates,
+ )
+ ]
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,
@@ -1125,6 +1196,9 @@ class _PolicyMixin:
"field it quotes",
source_tool_call_ids=[declaration.ref],
ambiguous_sources=scoped_identities,
+ field_ref_candidates=self._tail_risk_field_refs(
+ scoped_records, scoped_entries
+ ),
)
]
ambiguous = self._ambiguous_field_sources(declaration.ref, symbol)
@@ -1140,6 +1214,7 @@ class _PolicyMixin:
f"{', '.join(ambiguous)}, and they hold different values",
source_tool_call_ids=[declaration.ref],
ambiguous_sources=ambiguous,
+ field_ref_candidates=ambiguous,
)
]
return [
@@ -1219,6 +1294,9 @@ class _PolicyMixin:
f"{', '.join(session_identities)}, so the figure has to name "
"the field it quotes",
ambiguous_sources=session_identities,
+ field_ref_candidates=self._tail_risk_field_refs(
+ session_records, self._analysis_metrics
+ ),
)
]
observed = sorted(direct or scaled)
diff --git a/agent/src/agent/grounding/release.py b/agent/src/agent/grounding/release.py
index e91564695..a24957473 100644
--- a/agent/src/agent/grounding/release.py
+++ b/agent/src/agent/grounding/release.py
@@ -74,7 +74,8 @@ _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)",
+ "tail_risk_needs_field_ref": "this session holds {sources}, which are different measurements; declare the figure with an exact field ref",
+ "field_ref_needs_call_id": "{ref} uses a tool name before ::; use one exact call_id::field ref from {sources}",
"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",
@@ -121,6 +122,9 @@ def _correction_line(issue: dict[str, Any]) -> str:
sources=", ".join(str(source) for source in issue.get("ambiguous_sources") or []),
result=result if result else "a different value",
)
+ candidates = issue.get("field_ref_candidates") or []
+ if candidates:
+ evidence += "; valid field refs: " + ", ".join(str(item) for item in candidates)
nearest = issue.get("observed_nearest") or []
if nearest:
evidence += "; nearest observed " + ", ".join(_format_price(float(item)) for item in nearest)
diff --git a/agent/tests/test_grounding_role_hardening.py b/agent/tests/test_grounding_role_hardening.py
index 0e54d5ada..da17ef0b3 100644
--- a/agent/tests/test_grounding_role_hardening.py
+++ b/agent/tests/test_grounding_role_hardening.py
@@ -614,6 +614,77 @@ def test_a_call_scoped_ref_does_not_choose_a_tail_risk_identity(tmp_path: Path)
assert result.issues[0]["ambiguous_sources"] == ["es_95", "es_99", "var_95", "var_99"]
+XRAY_SECOND = (
+ "portfolio_risk_xray",
+ {"symbols": [A]},
+ {
+ "status": "ok",
+ "data": {
+ "tail_risk": {
+ "var_95": 0.0195,
+ "expected_shortfall_95": 0.0268,
+ "var_99": 0.0287,
+ "expected_shortfall_99": 0.0396,
+ }
+ },
+ },
+ "x2",
+)
+
+
+def test_tool_name_before_field_ref_lists_exact_call_refs(tmp_path: Path) -> None:
+ ledger = _ledger(
+ tmp_path,
+ MARKET_A,
+ XRAY,
+ XRAY_SECOND,
+ message="Compare portfolio tail risk across two scopes.",
+ )
+ result = ledger.validate_final_answer(
+ HDR + " VaR 95%: 1.57%。"
+ + _block(
+ ROW,
+ "95% | count | confidence",
+ "1.57% | observed | VaR 95% | "
+ "portfolio_risk_xray::data.tail_risk.var_95",
+ )
+ )
+
+ assert result.valid is False
+ assert _reasons(result) == ["field_ref_needs_call_id"]
+ assert result.issues[0]["field_ref_candidates"] == [
+ "x1::data.tail_risk.var_95",
+ "x2::data.tail_risk.var_95",
+ ]
+ correction = ledger.correction_prompt(result)
+ assert "x1::data.tail_risk.var_95" in correction
+ assert "x2::data.tail_risk.var_95" in correction
+
+
+def test_tail_risk_correction_lists_exact_payload_fields(tmp_path: Path) -> None:
+ ledger = _ledger(
+ tmp_path,
+ MARKET_A,
+ XRAY,
+ XRAY_SECOND,
+ message="Compare portfolio tail risk across two scopes.",
+ )
+ result = ledger.validate_final_answer(
+ HDR + " ES 95%: 2.11%。"
+ + _block(
+ ROW,
+ "95% | count | confidence",
+ "2.11% | observed | ES 95% | portfolio_risk_xray",
+ )
+ )
+
+ assert result.valid is False
+ assert _reasons(result) == ["tail_risk_needs_field_ref"]
+ correction = ledger.correction_prompt(result)
+ assert "x1::data.tail_risk.expected_shortfall_95" in correction
+ assert "x2::data.tail_risk.expected_shortfall_95" in correction
+
+
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.
@@ -711,6 +782,10 @@ def test_a_field_two_calls_returned_differently_needs_its_call(tmp_path: Path) -
ambiguous = answer("historical_var")
assert _reasons(ambiguous) == ["ambiguous_field_ref"]
assert ambiguous.issues[0]["ambiguous_sources"] == ["q1::historical_var", "q2::historical_var"]
+ assert ambiguous.issues[0]["field_ref_candidates"] == [
+ "q1::historical_var",
+ "q2::historical_var",
+ ]
assert answer("q1::historical_var").valid is True
assert _reasons(answer("q2::historical_var")) == ["not_in_referenced_call"]