"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(grounding): let figures quoted from a read document enter the ledger
Zigen Hanbf5c38f8e716
diff --git a/agent/src/agent/grounding/evidence.py b/agent/src/agent/grounding/evidence.pyindex c0827cf7c..586d4c2b7 100644--- a/agent/src/agent/grounding/evidence.py+++ b/agent/src/agent/grounding/evidence.py@@ -15,7 +15,12 @@ from dataclasses import dataclass, replacefrom pathlib import Pathfrom typing import Any, Mapping-from src.agent.grounding.figures import _CURRENCY_CODES+from src.agent.grounding.figures import (+ Figure,+ _CURRENCY_CODES,+ parse_figures_block,+ scan_figures,+)from src.agent.grounding.identity import (_CANONICAL_SYMBOL_RE,_infer_currency,@@ -30,6 +35,10 @@ _TIMESTAMP_FIELDS = ("trade_date", "date", "datetime", "timestamp", "time", "ind_MAX_GENERIC_EVIDENCE = 2_000+#: Figures one document may contribute. A filing's text carries far more+#: numbers than a tool result, and one long document must not crowd the ledger.+_MAX_DOCUMENT_FIGURES = 400+#: Top-level fields of a code-running tool's envelope (backtest, bash, ...). They#: describe the process, not the market, so they never become observed evidence._ENVELOPE_FIELDS = frozenset(@@ -683,6 +692,21 @@ def _is_price_kind(record: EvidenceRecord) -> bool:)+def _document_field(figure: Figure) -> str:+ """The evidence field a document's figure is recorded under.++ The name carries the figure's written shape and nothing more. A document+ does not say whether a number is revenue or a price, so a made-up semantic+ name would let the gate's money and percent filters act on a distinction the+ file never drew — while the shape is exactly what the reader did see.+ """+ if figure.percent:+ return "document.ratio"+ if figure.currency:+ return "document.amount"+ return "document.figure"++class _EvidenceMixin:"""Evidence behaviour of :class:`GroundingLedger`."""@@ -1390,3 +1414,96 @@ class _EvidenceMixin:continuerecords.append(replace(record, field=field_name))return records++ def _ingest_document_text(+ self,+ arguments: Mapping[str, Any],+ payload: dict[str, Any],+ call_id: str,+ *,+ tool_name: str = "read_document",+ ) -> None:+ """Record the figures a document states as observed evidence.++ ``read_document`` answers with one prose blob, so the numeric-leaf+ flattening every other tool goes through found nothing: a PDF's figures+ never became evidence and the gate redacted each of them as unsourced.++ Only numbers carrying a mark of measurement count. A page number, a+ section heading or a year in running text is not a finding, and+ admitting bare integers would let an invented small figure match by+ chance. The document must not be one this run wrote — reading back its+ own draft is not observation — and nothing under the run directory is+ read as a document, so the ledger's own artifacts cannot launder+ themselves through the reader.++ Args:+ arguments: The reader's arguments; its ``file_path`` names the source.+ payload: The document reader's envelope.+ call_id: The reader call that showed this text to the model.+ tool_name: The reader that returned the text.+ """+ text = next(+ (+ payload[key]+ for key in ("text", "content", "markdown")+ if isinstance(payload.get(key), str)+ ),+ None,+ )+ if not text:+ return+ path: Path | None = None+ raw_path = arguments.get("file_path")+ if isinstance(raw_path, str) and raw_path.strip():+ try:+ path = Path(raw_path).resolve()+ except OSError:+ path = None+ if path is not None:+ if self._is_model_written(path):+ return+ try:+ path.relative_to(self.run_dir.resolve())+ except ValueError:+ pass+ else:+ return+ artifact = path.name if path is not None else None+ if artifact is None and isinstance(payload.get("file"), str):+ artifact = payload["file"]+ room = min(+ _MAX_DOCUMENT_FIGURES,+ _MAX_GENERIC_EVIDENCE - len(self._evidence),+ )+ if room <= 0:+ return+ seen: set[tuple[float, bool, str | None]] = set()+ for figure in scan_figures(text, parse_figures_block(text)):+ if room <= 0:+ return+ if figure.shape != "measured":+ continue+ value = float(figure.value) * float(figure.scale or 1.0)+ if not math.isfinite(value):+ continue+ key = (round(value, 6), bool(figure.percent), figure.currency_code)+ if key in seen:+ continue+ seen.add(key)+ self._evidence.append(+ EvidenceRecord(+ call_id=call_id,+ tool=tool_name,+ symbol=None,+ source="document",+ timestamp=None,+ field=_document_field(figure),+ value=value,+ status="observed",+ currency=figure.currency_code,+ artifact=artifact,+ )+ )+ room -= 1+diff --git a/agent/src/agent/grounding/ledger.py b/agent/src/agent/grounding/ledger.pyindex 68a3efefe..b1c6c5bac 100644--- a/agent/src/agent/grounding/ledger.py+++ b/agent/src/agent/grounding/ledger.py@@ -347,6 +347,11 @@ class GroundingLedger(self._ingest_engine_table(payload, call_id)elif tool_name == "read_run_artifact" and payload is not None:self._ingest_engine_table(payload, call_id, tool_name=tool_name)+ elif tool_name == "read_document" and payload is not None:+ # A document answers in prose, so the numeric-leaf walk below never+ # reached its numbers: every figure quoted from an uploaded PDF came+ # back as unsourced (#2050).+ self._ingest_document_text(arguments, payload, call_id)elif payload is not None:self._ingest_generic_numeric(tool_name, arguments, payload, call_id)self.persist()diff --git a/agent/tests/test_grounding_document_figures.py b/agent/tests/test_grounding_document_figures.pynew file mode 100644index 000000000..f21870ae9--- /dev/null+++ b/agent/tests/test_grounding_document_figures.py@@ -0,0 +1,167 @@+"""Figures a document states ground the report written from that document.++Regression history (2026-10-26, #2050): a user uploaded an annual report, the+agent read it with ``read_document``, and the report quoted the document's own+revenue, margin and EPS — every one of which the gate redacted as unsourced. The+reader answers with one prose blob, so the numeric-leaf walk every other tool+goes through found nothing to record, and a figure quoted from the file had no+evidence behind it.++What stays closed is pinned beside each change: only numbers carrying a mark of+measurement count (a page number, a section number or a year in running text is+not a finding, and admitting bare integers would let an invented small figure+match by chance), a document this run wrote is never evidence, and nothing under+the run directory counts as a document — the ledger's own artifacts must not+launder themselves through the reader.++Every value here is synthetic; no market data lives in the repository.+"""++from __future__ import annotations++import json+from pathlib import Path++from src.agent.grounding import GroundingLedger++REPORT = """第一节 经营回顾++公司本年度毛利率 41.2%,每股收益 2.87 元,营收增速 12.4%。+员工总数 3400 人,报告日期 2025 年 3 月 18 日,第 12 页。+"""+++def _document_envelope(path: Path, text: str) -> str:+ return json.dumps(+ {+ "status": "ok",+ "file": path.name,+ "format": path.suffix.lstrip(".") or "txt",+ "char_count": len(text),+ "truncated": False,+ "text": text,+ },+ ensure_ascii=False,+ )+++def _read_document(+ ledger: GroundingLedger,+ path: Path,+ call_id: str,+ text: str = REPORT,+) -> None:+ ledger.ingest_tool_result(+ tool_name="read_document",+ arguments={"file_path": str(path)},+ result=_document_envelope(path, text),+ call_id=call_id,+ success=True,+ )+++def _ledger_with_upload(tmp_path: Path) -> tuple[GroundingLedger, Path]:+ """A ledger whose run directory sits beside, not above, the upload."""+ run_dir = tmp_path / "run"+ run_dir.mkdir()+ uploads = tmp_path / "uploads"+ uploads.mkdir()+ document = uploads / "ar2025.pdf"+ document.write_text(REPORT, encoding="utf-8")+ return GroundingLedger(run_dir=run_dir, user_message="读一下这份年报,总结经营情况"), document+++def _declared(prose: str, *lines: str) -> str:+ return prose + "\n\n```figures\n" + "\n".join(lines) + "\n```"+++def test_a_document_figure_grounds_the_answer_that_quotes_it(tmp_path: Path) -> None:+ ledger, document = _ledger_with_upload(tmp_path)+ _read_document(ledger, document, "doc-1")++ result = ledger.validate_final_answer(+ _declared(+ "年报显示毛利率 41.2%,每股收益 2.87 元,营收增速 12.4%。",+ "41.2% | observed | 毛利率 | ar2025.pdf",+ "2.87 | observed | 每股收益 | ar2025.pdf",+ "12.4% | observed | 营收增速 | ar2025.pdf",+ )+ )++ assert result.valid, result.issues+++def test_a_document_figure_is_not_evidence_before_the_document_is_read(+ tmp_path: Path,+) -> None:+ """The document exists on disk but the model never saw it."""+ ledger, _ = _ledger_with_upload(tmp_path)++ result = ledger.validate_final_answer(+ _declared("年报显示毛利率 41.2%。", "41.2% | observed | 毛利率 | ar2025.pdf")+ )++ assert not result.valid+++def test_a_page_number_and_a_year_are_not_findings(tmp_path: Path) -> None:+ """Page 12 and the year 2025 are layout, not facts about the company."""+ ledger, document = _ledger_with_upload(tmp_path)+ _read_document(ledger, document, "doc-1")++ values = {record.value for record in ledger._evidence}++ assert 41.2 in values and 2.87 in values and 12.4 in values+ assert 12 not in values, "页码进了账本"+ assert 2025 not in values, "年份进了账本"+ assert 3400 not in values, "人数这类无计量标记的整数不该进账本"+++def test_a_document_this_run_wrote_is_not_evidence(tmp_path: Path) -> None:+ """Reading back the run's own draft is not observation."""+ ledger, document = _ledger_with_upload(tmp_path)+ ledger.ingest_tool_result(+ tool_name="write_file",+ arguments={"path": str(document)},+ result=json.dumps({"status": "ok", "path": str(document)}),+ call_id="model-write-doc",+ success=True,+ )+ _read_document(ledger, document, "doc-1")++ result = ledger.validate_final_answer(+ _declared("年报显示毛利率 41.2%。", "41.2% | observed | 毛利率 | ar2025.pdf")+ )++ assert not result.valid+++def test_a_document_inside_the_run_directory_is_not_evidence(tmp_path: Path) -> None:+ """The ledger's own artifacts must not launder themselves through the reader."""+ ledger = GroundingLedger(run_dir=tmp_path, user_message="读一下这份年报")+ document = tmp_path / "report.md"+ document.write_text(REPORT, encoding="utf-8")+ _read_document(ledger, document, "doc-1")++ result = ledger.validate_final_answer(+ _declared("报告显示毛利率 41.2%。", "41.2% | observed | 毛利率 | report.md")+ )++ assert not result.valid+++def test_an_error_envelope_records_nothing(tmp_path: Path) -> None:+ ledger, document = _ledger_with_upload(tmp_path)+ ledger.ingest_tool_result(+ tool_name="read_document",+ arguments={"file_path": str(document)},+ result=json.dumps({"status": "error", "error": "unsupported format"}),+ call_id="doc-1",+ success=False,+ )++ result = ledger.validate_final_answer(+ _declared("年报显示毛利率 41.2%。", "41.2% | observed | 毛利率 | ar2025.pdf")+ )++ assert not result.valid