Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(grounding): resolve indexed field refs and list exact indexed candidates

zeus229cdd19af6e470
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.py
index cc4c86f05..2d9a8bcc7 100644
--- a/agent/src/agent/context.py
+++ b/agent/src/agent/context.py
@@ -206,6 +206,10 @@ Decide which workflow to use based on the request:
`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.
+ Each element of a list is its own field: address it by index,
+ `call_id::data.positions[0].contribution_pct` (`positions.0.contribution_pct`
+ is read the same way). A field name without the index does not select an
+ element, and one element's ref never grounds another element's value.
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 d8b98cf78..81c7a7cc3 100644
--- a/agent/src/agent/grounding/policies.py
+++ b/agent/src/agent/grounding/policies.py
@@ -43,6 +43,17 @@ from src.agent.grounding.figures import (
import re
+# ``a.0.b`` and ``a[0].b`` name the same list element; evidence paths are
+# emitted with brackets, so refs are compared in that spelling.
+_DOTTED_INDEX_RE = re.compile(r"(?<=\w)\.(\d+)(?=\.|\[|$)")
+_INDEX_RE = re.compile(r"\[\d+\]")
+_MAX_INDEXED_REF_CANDIDATES = 12
+
+
+def _index_normalized(path: str) -> str:
+ """Spell dotted collection indices with brackets (``a.0.b`` -> ``a[0].b``)."""
+ return _DOTTED_INDEX_RE.sub(r"[\1]", path)
+
# Loader ids are ASCII but the answer follows the user's language, so a source
# is surfaced by any alias ("数据来源:腾讯财经" for ``tencent``).
_SOURCE_ALIASES = {
@@ -853,8 +864,13 @@ class _PolicyMixin:
dropped here, before any count of calls, so two instruments' closes do
not make ``close`` ambiguous.
"""
+ wanted = _index_normalized(field)
+
def named(path: Any) -> bool:
- return isinstance(path, str) and (path == field or path.endswith("." + field))
+ if not isinstance(path, str):
+ return False
+ path = _index_normalized(path)
+ return path == wanted or path.endswith("." + wanted)
records = [
record
@@ -1070,6 +1086,54 @@ class _PolicyMixin:
}
return sorted(refs)
+ def _indexed_field_ref_candidates(
+ self, ref: str, figure: Figure
+ ) -> list[str]:
+ """Exact ``call_id::path[i]`` refs for a ``call::field`` ref that named no element.
+
+ Only paths that equal the declared field once every collection index is
+ dropped are offered, and only from the call (or tool) the ref names.
+ Refs whose value matches the figure come first. These are hints for the
+ next draft; the ref is never resolved through them.
+ """
+ found: dict[str, float] = {}
+ for key in (part.strip() for part in re.split(r"[;,]", ref or "")):
+ if "::" not in key:
+ continue
+ scope, field = (part.strip() for part in key.split("::", 1))
+ if not scope or not field:
+ continue
+ bare = _INDEX_RE.sub("", _index_normalized(field))
+ for call_id, tool, path, value in (
+ *(
+ (r.call_id, r.tool, r.field, r.value)
+ for r in self._evidence
+ if r.status == "observed"
+ ),
+ *(
+ (e.get("call_id"), e.get("tool"), e.get("field"), e.get("value"))
+ for e in self._analysis_metrics
+ ),
+ ):
+ if (
+ call_id
+ and isinstance(path, str)
+ and value is not None
+ and scope in (call_id, tool)
+ and _INDEX_RE.search(path)
+ ):
+ stripped = _INDEX_RE.sub("", path)
+ if stripped == bare or stripped.endswith("." + bare):
+ found[f"{call_id}::{path}"] = float(value)
+ ranked = sorted(
+ found,
+ key=lambda item: (
+ not self._matches_evidence(figure, [found[item]], [found[item]]),
+ item,
+ ),
+ )
+ return ranked[:_MAX_INDEXED_REF_CANDIDATES]
+
def _tail_risk_ref_required(
self,
figure: Figure,
@@ -1441,6 +1505,9 @@ class _PolicyMixin:
f"is declared observed from {declaration.ref}, whose results "
f"{'for ' + symbol + ' ' if symbol else ''}do not contain it",
source_tool_call_ids=[declaration.ref],
+ field_ref_candidates=self._indexed_field_ref_candidates(
+ declaration.ref, figure
+ ),
observed_nearest=self._nearest_prints(figure, scoped_records, values),
)
]
diff --git a/agent/tests/test_grounding_indexed_field_refs.py b/agent/tests/test_grounding_indexed_field_refs.py
new file mode 100644
index 000000000..802d371a8
--- /dev/null
+++ b/agent/tests/test_grounding_indexed_field_refs.py
@@ -0,0 +1,158 @@
+"""Field refs into list elements: index spelling, exact candidates, isolation."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from src.agent.grounding import GroundingLedger
+
+pytestmark = pytest.mark.unit
+
+TOOL = "report_tool"
+CALL = "call_1|fc_1"
+PAYLOAD = {
+ "ok": True,
+ "data": {
+ "total_return_pct": 0.36,
+ "positions": [
+ {"symbol": "AAA", "contribution_pct": 1.23},
+ {"symbol": "BBB", "contribution_pct": -0.87},
+ ],
+ },
+}
+
+
+def _ledger(tmp_path: Path) -> GroundingLedger:
+ ledger = GroundingLedger(
+ run_dir=tmp_path, user_message="Show contributions per position"
+ )
+ ledger.ingest_tool_result(
+ tool_name=TOOL,
+ arguments={},
+ result=json.dumps(PAYLOAD),
+ call_id=CALL,
+ success=True,
+ )
+ return ledger
+
+
+def _validate(tmp_path: Path, prose: str, *rows: str):
+ block = "\n\n```figures\n" + "\n".join(rows) + "\n```"
+ return _ledger(tmp_path).validate_final_answer(prose + block)
+
+
+def _ref(index: int, dotted: bool = False, field: str = "contribution_pct") -> str:
+ path = f"positions.{index}" if dotted else f"positions[{index}]"
+ return f"{CALL}::data.{path}.{field}"
+
+
+def test_bracket_index_ref_validates(tmp_path: Path) -> None:
+ result = _validate(
+ tmp_path,
+ "One item contributed 1.23% and the other -0.87%.",
+ f"1.23% | observed | first item | {_ref(0)}",
+ f"-0.87% | observed | second item | {_ref(1)}",
+ )
+ assert result.valid is True, result.issues
+
+
+def test_dotted_index_ref_validates_the_same_elements(tmp_path: Path) -> None:
+ result = _validate(
+ tmp_path,
+ "One item contributed 1.23% and the other -0.87%.",
+ f"1.23% | observed | first item | {_ref(0, dotted=True)}",
+ f"-0.87% | observed | second item | {_ref(1, dotted=True)}",
+ )
+ assert result.valid is True, result.issues
+
+
[email protected]("dotted", [False, True])
+def test_wrong_value_for_an_indexed_element_is_rejected(
+ tmp_path: Path, dotted: bool
+) -> None:
+ result = _validate(
+ tmp_path,
+ "The first item contributed 1.24%.",
+ f"1.24% | observed | first item | {_ref(0, dotted)}",
+ )
+ assert result.valid is False
+ assert {issue["code"] for issue in result.issues} == {"numeric_claim_conflict"}
+
+
[email protected]("dotted", [False, True])
+def test_other_elements_value_is_not_authorized_by_an_indexed_ref(
+ tmp_path: Path, dotted: bool
+) -> None:
+ # -0.87 exists in the call, but only at positions[1].
+ result = _validate(
+ tmp_path,
+ "The first item contributed -0.87%.",
+ f"-0.87% | observed | first item | {_ref(0, dotted)}",
+ )
+ assert result.valid is False
+ assert {issue["reason"] for issue in result.issues} == {"not_in_referenced_call"}
+
+
+def test_elements_are_not_ambiguous_with_each_other(tmp_path: Path) -> None:
+ result = _validate(
+ tmp_path,
+ "Contributions were 1.23% and -0.87%.",
+ f"1.23% | observed | first | {_ref(0, dotted=True)}",
+ f"-0.87% | observed | second | {_ref(1)}",
+ )
+ assert result.valid is True, result.issues
+ assert not any(
+ issue.get("reason") == "ambiguous_field_ref" for issue in result.issues
+ )
+
+
+def test_dotted_index_does_not_touch_unindexed_or_scalar_refs(tmp_path: Path) -> None:
+ result = _validate(
+ tmp_path,
+ "Total return was 0.36%.",
+ f"0.36% | observed | total | {CALL}::data.total_return_pct",
+ )
+ assert result.valid is True, result.issues
+
+
+ "ref",
+ [
+ f"{CALL}::data.positions.contribution_pct",
+ f"{TOOL}::positions.contribution_pct",
+ f"{CALL}::data.positions.2.contribution_pct",
+ ],
+)
+def test_failed_ref_lists_exact_indexed_candidates(tmp_path: Path, ref: str) -> None:
+ result = _validate(
+ tmp_path,
+ "The first item contributed 1.23%.",
+ f"1.23% | observed | first item | {ref}",
+ )
+ assert result.valid is False
+ candidates = result.issues[0]["field_ref_candidates"]
+ assert candidates[0] == _ref(0) # the one matching the figure first
+ assert set(candidates) == {_ref(0), _ref(1)}
+ assert all(item.startswith(f"{CALL}::data.positions[") for item in candidates)
+
+
+def test_candidates_are_shown_to_the_model_in_the_correction(tmp_path: Path) -> None:
+ ledger = _ledger(tmp_path)
+ result = ledger.validate_final_answer(
+ "The second item contributed -0.87%.\n\n```figures\n"
+ f"-0.87% | observed | second item | {TOOL}::positions.contribution_pct\n```"
+ )
+ assert f"valid field refs: {_ref(1)}" in ledger.correction_prompt(result)
+
+
+def test_unrelated_field_gets_no_candidates(tmp_path: Path) -> None:
+ result = _validate(
+ tmp_path,
+ "Something was 9.99%.",
+ f"9.99% | observed | x | {CALL}::data.positions.weight_pct",
+ )
+ assert result.valid is False
+ assert not result.issues[0].get("field_ref_candidates")