"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(grounding): recover container refs and multi-call field refs with value-matched leaf hints
zeus229675dad77aeea
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.pyindex 2d9a8bcc7..834747d3e 100644--- a/agent/src/agent/context.py+++ b/agent/src/agent/context.py@@ -210,6 +210,8 @@ Decide which workflow to use based on the request:`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 anelement, and one element's ref never grounds another element's value.+ A ref that names a list or object (`data.groups.positive`) grounds nothing;+ end it at the numeric field of the element you quote.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 nodeclaration at all cannot say which of them you are quoting, and the figure isdiff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.pyindex 81c7a7cc3..ab43ccbcc 100644--- a/agent/src/agent/grounding/policies.py+++ b/agent/src/agent/grounding/policies.py@@ -48,6 +48,10 @@ import re_DOTTED_INDEX_RE = re.compile(r"(?<=\w)\.(\d+)(?=\.|\[|$)")_INDEX_RE = re.compile(r"\[\d+\]")_MAX_INDEXED_REF_CANDIDATES = 12+#: A container ref is answered only with leaves that hold the figure's value, so+#: a handful is enough; calls returning one field are capped the same way.+_MAX_CONTAINER_REF_CANDIDATES = 5+_MAX_CALL_REF_CANDIDATES = 5def _index_normalized(path: str) -> str:@@ -1064,9 +1068,14 @@ class _PolicyMixin:return sorted(refs)def _tool_field_ref_candidates(- self, ref: str, symbol: str | None+ self, ref: str, symbol: str | None, figure: Figure | None = None) -> list[str]:- """Exact call refs for a mistaken tool_name::field declaration."""+ """Exact call refs for a mistaken tool_name::field declaration.++ With ``figure``, refs whose observed value matches it come first, most+ recent call first among equals; the list is capped. The hint never+ selects a call: the next draft must still declare the exact ref.+ """key = (ref or "").strip()if "::" not in key:return []@@ -1074,65 +1083,148 @@ class _PolicyMixin:if not scope or not field:return []records, entries = self._field_sources(field, symbol)- refs = {- self._ref_source(record.call_id, record.field, record.scope)[1]- for record in records- if record.tool == scope and record.call_id and record.field- }- refs |= {- self._ref_source(str(entry.get("call_id")), str(entry.get("field")), None)[1]- for entry in entries- if entry.get("tool") == scope and entry.get("call_id") and entry.get("field")- }- return sorted(refs)+ found: dict[str, list[float]] = {}+ for record in records:+ if record.tool == scope and record.call_id and record.field:+ found.setdefault(self._ref_source(record.call_id, record.field, record.scope)[1], []).append(+ float(record.value)+ )+ for entry in entries:+ if entry.get("tool") == scope and entry.get("call_id") and entry.get("field"):+ found.setdefault(self._ref_source(str(entry.get("call_id")), str(entry.get("field")), None)[1], []).append(+ float(entry["value"])+ )+ if figure is None:+ return sorted(found)+ recency = {item: index for index, item in enumerate(found)}+ ranked = sorted(+ found,+ key=lambda item: (+ not self._matches_evidence(figure, found[item], found[item]),+ -recency[item],+ item,+ ),+ )+ return ranked[:_MAX_CALL_REF_CANDIDATES]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.+ """Exact ``call_id::path[i]`` refs for a ``call::field`` ref that selected no value.++ Two shapes of an unresolved ref are helped, both only from the call (or+ tool) the ref names:++ * the ref names a list field without its index: paths that equal the+ declared field once every collection index is dropped are offered;+ * the ref names a container (``data.groups.positive``): its numeric+ descendants that hold the figure's value are offered, and none+ otherwise. An index written in the ref narrows the container to that+ 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.+ next draft; a ref is never resolved through them and a container ref+ authorizes nothing."""found: dict[str, float] = {}+ containers: set[str] = set()for key in (part.strip() for part in re.split(r"[;,]", ref or "")):if "::" not in key:continuescope, 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 (+ wanted = _index_normalized(field)+ bare = _INDEX_RE.sub("", wanted)+ below = re.compile(r"(?:^|\.)" + re.escape(wanted) + r"(?=[.\[])")+ for call_id, tool, path, value, record in (*(- (r.call_id, r.tool, r.field, r.value)+ (r.call_id, r.tool, r.field, r.value, r)for r in self._evidenceif r.status == "observed"),*(- (e.get("call_id"), e.get("tool"), e.get("field"), e.get("value"))+ (e.get("call_id"), e.get("tool"), e.get("field"), e.get("value"), None)for e in self._analysis_metrics),):- if (+ if not (call_idand isinstance(path, str)and value is not Noneand scope in (call_id, tool)- and _INDEX_RE.search(path)):+ continue+ if record is not None and not self._kind_fits(record, figure):+ continue+ item = f"{call_id}::{path}"+ if below.search(_index_normalized(path)):+ containers.add(item)+ found[item] = float(value)+ elif _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]+ found[item] = float(value)+ matches = {+ item: self._matches_evidence(figure, [value], [value])+ for item, value in found.items()+ }+ # A container is answered only by the leaf that holds the figure.+ kept = [item for item in found if item not in containers or matches[item]]+ ranked = sorted(kept, key=lambda item: (not matches[item], item))+ cap = _MAX_CONTAINER_REF_CANDIDATES if containers else _MAX_INDEXED_REF_CANDIDATES+ return ranked[:cap]++ def _other_call_field_ref_candidates(+ self, ref: str, symbol: str | None, figure: Figure+ ) -> list[str]:+ """Same-field refs from other calls of the tool whose value matches ``figure``.++ A ``call_id::field`` ref that does not hold the figure may still name the+ right field of the wrong call (scope or period). Only calls of the same+ tool as the declared call, whose value for that field matches, are+ offered, most recent first. A hint only: the declared ref stays rejected+ and the next draft must name the exact ref itself.+ """+ found: dict[str, None] = {}+ 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))+ tools = {r.tool for r in self._evidence if r.call_id == scope}+ tools |= {e.get("tool") for e in self._analysis_metrics if e.get("call_id") == scope}+ if not scope or not field or not tools:+ continue+ records, entries = self._field_sources(field, symbol)+ for call_id, tool, path, value, record in (+ *((r.call_id, r.tool, r.field, r.value, r) for r in records),+ *((e.get("call_id"), e.get("tool"), e.get("field"), e.get("value"), None) for e in entries),+ ):+ if (+ call_id+ and call_id != scope+ and tool in tools+ and isinstance(path, str)+ and (record is None or self._kind_fits(record, figure))+ and self._matches_evidence(figure, [float(value)], [float(value)])+ ):+ found[f"{call_id}::{path}"] = None+ return list(reversed(found))[:_MAX_CALL_REF_CANDIDATES]++ @staticmethod+ def _kind_fits(record: EvidenceRecord, figure: Figure) -> bool:+ """Whether a record is of the kind ``figure`` can be grounded in.++ Mirrors the narrowing ``_referenced`` applies, so a hint never points at+ a leaf the next draft would still be rejected for.+ """+ if figure.column and record.field != figure.column:+ return False+ if figure.percent:+ return not _is_price_kind(record) and not _is_metadata_count_leaf(record.field)+ if figure.currency:+ return _is_price_kind(record)+ return Truedef _tail_risk_ref_required(self,@@ -1420,7 +1512,7 @@ class _PolicyMixin:and not metric_values):call_field_candidates = self._tool_field_ref_candidates(- declaration.ref, symbol+ declaration.ref, symbol, figure)if call_field_candidates:return [@@ -1505,8 +1597,13 @@ 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+ field_ref_candidates=list(+ dict.fromkeys(+ [+ *self._indexed_field_ref_candidates(declaration.ref, figure),+ *self._other_call_field_ref_candidates(declaration.ref, symbol, figure),+ ]+ )),observed_nearest=self._nearest_prints(figure, scoped_records, values),)diff --git a/agent/src/agent/grounding/release.py b/agent/src/agent/grounding/release.pyindex 9d6ec64ce..002269eac 100644--- a/agent/src/agent/grounding/release.py+++ b/agent/src/agent/grounding/release.py@@ -135,9 +135,11 @@ def _correction_line(issue: dict[str, Any]) -> str:"; that is the same size with the opposite sign — the formula runs the other ""way round from the answer, so write its operands in the order the answer states")- candidates = issue.get("field_ref_candidates") or []- if candidates:- evidence += "; valid field refs: " + ", ".join(str(item) for item in candidates)+ # Each ref once, and not again when the reason already spelled the same list.+ candidates = list(dict.fromkeys(str(item) for item in issue.get("field_ref_candidates") or []))+ sources = list(dict.fromkeys(str(item) for item in issue.get("ambiguous_sources") or []))+ if candidates and not ("{sources}" in template and candidates == sources):+ evidence += "; valid field refs: " + ", ".join(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_backtest_outputs.py b/agent/tests/test_grounding_backtest_outputs.pyindex 7da1effb9..dd92eb1ad 100644--- a/agent/tests/test_grounding_backtest_outputs.py+++ b/agent/tests/test_grounding_backtest_outputs.py@@ -265,6 +265,25 @@ def test_a_bare_field_two_runs_hold_is_ambiguous_and_the_correction_names_the_ruassert "rp::sortino" in two_runs.correction_prompt(result)+def test_a_wrong_call_ref_hints_only_refs_that_then_ground_the_figure(+ two_runs: GroundingLedger,+) -> None:+ """The hint for a backtest's value names the call that wrote it, and each ref it lists validates."""+ wrong = two_runs.validate_final_answer(+ _declared("风险平价 Sortino 1.133。", "1.133 | observed | Sortino | bt-ew::sortino")+ )++ assert not wrong.valid+ (issue,) = wrong.issues+ assert issue["reason"] == "not_in_referenced_call"+ assert issue["field_ref_candidates"]+ for ref in issue["field_ref_candidates"]:+ assert ref.startswith("bt-rp::")+ assert two_runs.validate_final_answer(+ _declared("风险平价 Sortino 1.133。", f"1.133 | observed | Sortino | {ref}")+ ).valid, ref++def test_one_run_holding_two_drawdowns_is_still_one_source(tmp_path: Path) -> None:"""Engine and risk X-ray both report a max_drawdown; a ref cannot be ambiguousbetween two numbers the same run wrote."""diff --git a/agent/tests/test_grounding_container_field_refs.py b/agent/tests/test_grounding_container_field_refs.pynew file mode 100644index 000000000..327031376--- /dev/null+++ b/agent/tests/test_grounding_container_field_refs.py@@ -0,0 +1,261 @@+"""Recovery hints for container refs and multi-call field refs.++A ref that names a structured container (``call::data.groups.positive``), or a+tool name shared by several calls, cannot ground a figure by itself. These tests+pin that the correction feedback points at the exact leaf ref holding the+figure's value, and that no hint ever widens what a ref authorizes.+"""++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"+GROUPS = {+ "ok": True,+ "data": {+ "groups": {+ "positive": [+ {"symbol": "AAA", "move_pct": 2.50, "weight_pct": 10.0, "contribution_pct": 0.25},+ {"symbol": "BBB", "move_pct": 1.00, "weight_pct": 5.0, "contribution_pct": 0.05},+ ],+ "negative": [+ {"symbol": "CCC", "move_pct": -3.00, "weight_pct": 20.0, "contribution_pct": -0.60},+ ],+ },+ "other": {"metric": 42.5},+ },+}+++def _ledger(tmp_path: Path, *calls: tuple[str, dict]) -> GroundingLedger:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="Show contributions per group")+ for call_id, payload in calls or ((CALL, GROUPS),):+ ledger.ingest_tool_result(+ tool_name=TOOL,+ arguments={},+ result=json.dumps(payload),+ call_id=call_id,+ success=True,+ )+ return ledger+++def _issue(tmp_path: Path, figure: str, ref: str, *calls: tuple[str, dict]):+ ledger = _ledger(tmp_path, *calls)+ result = ledger.validate_final_answer(+ f"The value was {figure}.\n\n```figures\n{figure} | observed | value | {ref}\n```"+ )+ return ledger, result+++def _leaf(group: str, index: int, field: str) -> str:+ return f"{CALL}::data.groups.{group}[{index}].{field}"+++ ("figure", "expected"),+ [+ ("2.50%", _leaf("positive", 0, "move_pct")),+ ("10.0%", _leaf("positive", 0, "weight_pct")),+ ("0.25%", _leaf("positive", 0, "contribution_pct")),+ ("1.00%", _leaf("positive", 1, "move_pct")),+ ],+)+def test_container_ref_lists_the_value_matched_leaf_first(tmp_path: Path, figure: str, expected: str) -> None:+ _, result = _issue(tmp_path, figure, f"{CALL}::data.groups.positive")+ assert result.valid is False+ candidates = result.issues[0]["field_ref_candidates"]+ assert candidates[0] == expected+ assert len(candidates) <= 5+++def test_tool_scoped_container_ref_lists_exact_call_leaf(tmp_path: Path) -> None:+ # A tool name and a path missing its ``data.`` prefix still lead to exact refs.+ _, result = _issue(tmp_path, "-3.00%", f"{TOOL}::groups.negative")+ assert result.issues[0]["field_ref_candidates"][0] == _leaf("negative", 0, "move_pct")+++def test_container_hints_stay_inside_the_named_container(tmp_path: Path) -> None:+ _, result = _issue(tmp_path, "2.50%", f"{CALL}::data.groups.negative")+ assert result.valid is False+ assert not any("positive" in item for item in result.issues[0].get("field_ref_candidates") or [])+++def test_explicit_element_container_does_not_hint_a_sibling(tmp_path: Path) -> None:+ _, result = _issue(tmp_path, "1.00%", f"{CALL}::data.groups.positive[0]")+ assert result.valid is False+ assert not any("positive[1]" in item for item in result.issues[0].get("field_ref_candidates") or [])+++def test_container_ref_never_authorizes_a_value_by_itself(tmp_path: Path) -> None:+ for figure in ("2.50%", "-3.00%", "0.25%"):+ _, result = _issue(tmp_path, figure, f"{CALL}::data.groups.positive")+ assert result.valid is False, figure+ assert {issue["reason"] for issue in result.issues} == {"not_in_referenced_call"}+++def test_a_value_that_does_not_exist_gets_no_candidate_and_stays_rejected(+ tmp_path: Path,+) -> None:+ _, result = _issue(tmp_path, "7.77%", f"{CALL}::data.groups.positive")+ assert result.valid is False+ assert not result.issues[0].get("field_ref_candidates")+++def test_explicit_element_ref_does_not_authorize_another_element(tmp_path: Path) -> None:+ _, result = _issue(tmp_path, "1.00%", _leaf("positive", 0, "move_pct"))+ assert result.valid is False+ assert {issue["reason"] for issue in result.issues} == {"not_in_referenced_call"}+++def test_exact_leaf_ref_from_a_hint_validates(tmp_path: Path) -> None:+ _, result = _issue(tmp_path, "1.00%", _leaf("positive", 1, "move_pct"))+ assert result.valid is True, result.issues+++def test_unrelated_refs_get_no_descendant_list(tmp_path: Path) -> None:+ for ref in (f"{CALL}::data.other.metric", f"{CALL}::data.groups.zzz", f"{CALL}::data.zzz"):+ _, result = _issue(tmp_path, "2.50%", ref)+ assert result.valid is False+ assert not result.issues[0].get("field_ref_candidates"), ref+++def test_scalar_refs_keep_working(tmp_path: Path) -> None:+ _, result = _issue(tmp_path, "42.5", f"{CALL}::data.other.metric")+ assert result.valid is True, result.issues+++def test_feedback_lists_each_candidate_once_and_within_the_cap(tmp_path: Path) -> None:+ ledger, result = _issue(tmp_path, "2.50%", f"{CALL}::data.groups.positive")+ prompt = ledger.correction_prompt(result)+ assert prompt.count(_leaf("positive", 0, "move_pct")) == 1+ assert "valid field refs: " + _leaf("positive", 0, "move_pct") in prompt+++# --- several calls returning the same field ---------------------------------++CALL_A, CALL_B = "call_A|fc_a", "call_B|fc_b"+++def _returns(value: float) -> dict:+ return {"ok": True, "data": {"portfolio_return_pct": value}}+++def test_call_candidates_put_the_value_matched_call_first(tmp_path: Path) -> None:+ _, result = _issue(+ tmp_path,+ "-1.75%",+ f"{TOOL}::portfolio_return_pct",+ (CALL_A, _returns(-2.29)),+ (CALL_B, _returns(-1.75)),+ )+ issue = result.issues[0]+ assert issue["reason"] == "field_ref_needs_call_id"+ assert issue["field_ref_candidates"][0] == f"{CALL_B}::data.portfolio_return_pct"+ assert issue["ambiguous_sources"][0] == issue["field_ref_candidates"][0]+++def test_call_candidates_are_capped_and_deterministic(tmp_path: Path) -> None:+ calls = tuple((f"call_{i:02d}|fc_{i}", _returns(float(i))) for i in range(12))+ first = _issue(tmp_path, "-1.75%", f"{TOOL}::portfolio_return_pct", *calls)[1]+ second = _issue(tmp_path, "-1.75%", f"{TOOL}::portfolio_return_pct", *calls)[1]+ candidates = first.issues[0]["field_ref_candidates"]+ assert len(candidates) <= 5+ assert candidates == second.issues[0]["field_ref_candidates"]+++def test_call_feedback_does_not_repeat_the_candidate_list(tmp_path: Path) -> None:+ ledger, result = _issue(+ tmp_path,+ "-1.75%",+ f"{TOOL}::portfolio_return_pct",+ (CALL_A, _returns(-2.29)),+ (CALL_B, _returns(-1.75)),+ )+ prompt = ledger.correction_prompt(result)+ assert prompt.count(f"{CALL_B}::data.portfolio_return_pct") == 1+++def test_a_call_ref_never_authorizes_a_value_seen_only_in_another_call(+ tmp_path: Path,+) -> None:+ _, result = _issue(+ tmp_path,+ "-1.75%",+ f"{CALL_A}::data.portfolio_return_pct",+ (CALL_A, _returns(-2.29)),+ (CALL_B, _returns(-1.75)),+ )+ assert result.valid is False+ assert {issue["reason"] for issue in result.issues} == {"not_in_referenced_call"}+++def test_the_matching_call_ref_validates_once_chosen(tmp_path: Path) -> None:+ _, result = _issue(+ tmp_path,+ "-1.75%",+ f"{CALL_B}::data.portfolio_return_pct",+ (CALL_A, _returns(-2.29)),+ (CALL_B, _returns(-1.75)),+ )+ assert result.valid is True, result.issues+++def test_a_tool_scoped_ref_with_a_nonexistent_value_stays_rejected(tmp_path: Path) -> None:+ _, result = _issue(+ tmp_path,+ "-9.99%",+ f"{TOOL}::portfolio_return_pct",+ (CALL_A, _returns(-2.29)),+ (CALL_B, _returns(-1.75)),+ )+ assert result.valid is False+++def test_wrong_call_for_the_right_field_hints_the_call_holding_the_value(tmp_path: Path) -> None:+ _, result = _issue(+ tmp_path,+ "-1.75%",+ f"{CALL_A}::data.portfolio_return_pct",+ (CALL_A, _returns(-2.29)),+ (CALL_B, _returns(-1.75)),+ )+ assert result.valid is False+ assert result.issues[0]["field_ref_candidates"] == [f"{CALL_B}::data.portfolio_return_pct"]+++def test_wrong_call_hint_is_value_matched_only(tmp_path: Path) -> None:+ _, result = _issue(+ tmp_path,+ "-9.99%",+ f"{CALL_A}::data.portfolio_return_pct",+ (CALL_A, _returns(-2.29)),+ (CALL_B, _returns(-1.75)),+ )+ assert result.valid is False+ assert not result.issues[0].get("field_ref_candidates")+++def test_wrong_call_hint_stays_within_the_declared_calls_tool(tmp_path: Path) -> None:+ ledger = _ledger(tmp_path, (CALL_A, _returns(-2.29)))+ ledger.ingest_tool_result(+ tool_name="other_tool",+ arguments={},+ result=json.dumps(_returns(-1.75)),+ call_id="call_X|fc_x",+ success=True,+ )+ result = ledger.validate_final_answer(+ f"The value was -1.75%.\n\n```figures\n-1.75% | observed | v | {CALL_A}::data.portfolio_return_pct\n```"+ )+ assert result.valid is False+ assert not result.issues[0].get("field_ref_candidates")