"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(grounding): figures-block prompt contract, bare-code identity lock, no block in the stream
Haozhe Wu19523e6517e7
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.pyindex 0c8024970..221ae4cb1 100644--- a/agent/src/agent/context.py+++ b/agent/src/agent/context.py@@ -180,19 +180,39 @@ Decide which workflow to use based on the request:ask the user which one to use; re-querying will not collapse a genuineshortlist, and you may not pick one silently.- **Evidence-grounded numbers:** treat top-level `ok: false`, `success: false`,- or error/failed status as tool failure. Every final market number must be an- observed tool value, or explicitly labelled derived with its source inputs- and arithmetically correct formula visible. Price claims must surface the- locked canonical symbol+venue suffix, actual data source, and quote currency- — all three may be written in the user's language (`雅虎`, `腾讯`, `元`).- Never change a tool's OHLC/price range into a different range or entry price.- A proposed entry price that is not itself an observed value must be written- as an explicit formula over observed inputs — an OHLC value or a- price-denominated indicator this session fetched — e.g.- `基于收盘价 0.666 × 0.97 = 0.646`; an entry level written without such a- formula is cut from the released answer.- If evidence is missing or conflicting, report it as unavailable and ask for+ or error/failed status as tool failure. Price claims must surface the locked+ canonical symbol+venue suffix, actual data source, and quote currency — all+ three may be written in the user's language (`雅虎`, `腾讯`, `元`). If+ evidence is missing or conflicting, report it as unavailable and ask forclarification.+- **Declare every figure:** when the final answer states a number with a+ decimal point, a percent sign or a currency mark, or puts a number in a table+ cell, end the answer with ONE fenced block tagged `figures`, one line per+ figure: `value | role | note | ref`. Roles:+ `observed` — a value a tool returned (`ref`: that tool call's id, or the symbol);+ `derived` — arithmetic on observed values (`note`: the formula with its inputs);+ `proposed` — a level you suggest, such as an entry, stop or target: it must lie+ inside the observed price range, or carry a formula over observed values in `note`;+ `cited` — from a source other than this session's tools (`note`: the source);+ `count` — a count, window or horizon. Plain integers (counts, days, list+ numbers), dates and security codes need no line. Example (zh):+ ```figures+ 0.666 | observed | 159516.SZ 收盘 2026-09-09 | 159516.SZ+ 0.646 | derived | 0.666 × 0.97 | 159516.SZ+ 37% | derived | (1.053 − 0.666) / 1.053 | 159516.SZ+ 0.62 | proposed | 买入参考,位于观测区间 0.567–1.053 内+ ```+ Example (en):+ ```figures+ 182.4 | observed | AAPL.US close 2026-09-09 | AAPL.US+ 175 | proposed | entry, inside the observed 168.2–191.0 range+ 1.8 | cited | Sharpe ratio reported by the paper+ 20 | count | moving-average window, days+ ```+ The block is checked against this session's tool results and removed before+ the user sees the answer, so never refer to it in the prose. A figure you+ cannot declare truthfully under one of these roles must be removed, not+ relabelled; a rejected draft comes back with each failing figure listed.- **Figures need a symbol the session actually handled:** you may name an indexor a peer in passing, but the moment you attach a number to a ticker, thatticker must be one you passed to a tool that succeeded, or one a tooldiff --git a/agent/src/agent/grounding/identity.py b/agent/src/agent/grounding/identity.pyindex 6e3e1eae1..12f133f94 100644--- a/agent/src/agent/grounding/identity.py+++ b/agent/src/agent/grounding/identity.py@@ -425,6 +425,10 @@ class ToolAuthorization:)+# Identity records locked from a bare code the user typed (spec decision 4).+_BARE_CODE_KEY = "bare:"++class _IdentityMixin:"""Identity behaviour of :class:`GroundingLedger`."""@@ -482,6 +486,8 @@ class _IdentityMixin:self._identity_required = Trueself._buffer_output = True+ if set(symbols) <= self._bare_code_symbols(tool_name, symbols):+ return ToolAuthorization(allowed=True, symbols=symbols)authorized = {_normalize_symbol(item) for item in batch_authorized_symbols}frozen_status = batch_identity_status or self.identity_statusif frozen_status != "locked" or not authorized:@@ -939,6 +945,100 @@ class _IdentityMixin:symbols.append(symbol)return symbols+ def _roots_locked_elsewhere(self) -> set[str]:+ """Code roots already locked by an explicit suffix or the resolver."""+ return {+ record.symbol.rsplit(".", 1)[0]+ for key, record in self._identities.items()+ if record.status == "locked"+ and record.symbol+ and "." in record.symbol+ and not key.startswith(_BARE_CODE_KEY)+ }++ def _bare_code_symbols(self, tool_name: str, symbols: Iterable[str]) -> set[str]:+ """Consumer symbols vouched for by a bare six-digit code the user typed.++ A user who wrote ``159516`` named the instrument; only the venue suffix+ is the model's choice, and ``get_market_data`` returning rows for+ exactly one venue settles it (see :meth:`_lock_bare_codes`). ``000xxx``+ is excluded because those digits are both a Shanghai index and a+ Shenzhen stock, and a root something else already locked keeps that+ lock's venue.++ Args:+ tool_name: Requested tool.+ symbols: Canonical symbols the call asks for.++ Returns:+ The subset that may be fetched before any resolver call.+ """+ if tool_name != "get_market_data":+ return set()+ taken = self._roots_locked_elsewhere()+ eligible: set[str] = set()+ for symbol in symbols:+ root, dot, _ = symbol.rpartition(".")+ if dot and root in self._bare_codes and root not in taken and not root.startswith("000"):+ eligible.add(symbol)+ return eligible++ def _lock_bare_codes(+ self,+ arguments: Mapping[str, Any],+ payload: dict[str, Any] | None,+ call_id: str,+ ) -> None:+ """Lock a bare code once exactly one of its venues has returned rows.++ Rows for a second venue of the same code turn the record ambiguous, so+ the run falls back to the resolver instead of keeping a guessed venue.++ Args:+ arguments: The succeeding ``get_market_data`` call's arguments.+ payload: Its parsed result.+ call_id: Provider tool-call identity.+ """+ requested = self._bare_code_symbols(+ "get_market_data", self._extract_symbol_arguments(arguments)+ )+ if not requested or not isinstance(payload, dict):+ return+ for raw_symbol, raw_rows in payload.items():+ rows = raw_rows.get("data") if isinstance(raw_rows, dict) else raw_rows+ symbol = _normalize_symbol(raw_symbol)+ if symbol in requested and isinstance(rows, list) and rows:+ self._bare_code_hits.setdefault(symbol.rsplit(".", 1)[0], {}).setdefault(+ symbol, call_id+ )+ for root, hits in self._bare_code_hits.items():+ key = f"{_BARE_CODE_KEY}{root}"+ existing = self._identities.get(key)+ version = existing.version + 1 if existing else 1+ if len(hits) == 1:+ if existing is not None:+ continue+ (symbol, source_call), = hits.items()+ self._identities[key] = IdentityRecord(+ query=root,+ status="locked",+ symbol=symbol,+ venue=_infer_venue(symbol),+ instrument_type=_infer_instrument_type(symbol),+ currency=_infer_currency(symbol),+ source_tool_call_id=source_call,+ source=["get_market_data"],+ version=version,+ )+ elif existing is None or existing.status != "ambiguous":+ self._identities[key] = IdentityRecord(+ query=root,+ status="ambiguous",+ source_tool_call_id=call_id,+ candidates=[{"symbol": symbol} for symbol in sorted(hits)],+ version=version,+ )+def _track_session_symbols(self,arguments: Mapping[str, Any],diff --git a/agent/src/agent/grounding/ledger.py b/agent/src/agent/grounding/ledger.pyindex 5ea9afece..e3aca17ed 100644--- a/agent/src/agent/grounding/ledger.py+++ b/agent/src/agent/grounding/ledger.py@@ -110,6 +110,14 @@ class GroundingLedger(# names an instrument the run really handled.self._session_symbol_roots: set[str] = set()+ # Six-digit codes the user typed, with or without a venue suffix.+ self._bare_codes: set[str] = {+ run+ for run in "".join(ch if "0" <= ch <= "9" else " " for ch in user_message).split()+ if len(run) == 6+ }+ self._bare_code_hits: dict[str, dict[str, str]] = {}+self._seed_symbols(user_message, source="user_message")self.persist()@@ -166,6 +174,28 @@ class GroundingLedger("""Return how many figures the discounted release cut, or 0."""return int((self._released or {}).get("figures_removed", 0))+ @staticmethod+ def streamable_length(text: str) -> int:+ """Return how much of a streaming answer may be shown live.++ Everything from the figures block's fence on is the model's declaration+ to the gate, not answer text, and a last line that could still become+ that fence is held back until it is complete.++ Args:+ text: The answer streamed so far.++ Returns:+ The length of the prefix that is safe to emit.+ """+ span = parse_figures_block(text).span+ if span is not None:+ return span[0]+ line_start = text.rfind("\n") + 1+ if text[line_start:].lstrip()[:1] in ("`", "~"):+ return line_start+ return len(text)+def identity_summary(self) -> dict[str, Any]:"""Return compact identity state for traces and tool errors."""return {@@ -219,6 +249,7 @@ class GroundingLedger(self._ingest_resolution(arguments, payload, call_id)elif tool_name == "get_market_data":self._ingest_market_data(arguments, payload, call_id)+ self._lock_bare_codes(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/src/agent/loop.py b/agent/src/agent/loop.pyindex 31a230878..efe73cffc 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -1394,10 +1394,26 @@ class AgentLoop:self._grounding and self._grounding.should_buffer_output)+ streamed_chars = 0+def _on_text_chunk(delta: str) -> None:+ nonlocal streamed_charsthinking_chunks.append(delta)- if not buffer_text_output:- self._emit("text_delta", {"delta": delta, "iter": current_iter})+ if buffer_text_output:+ return+ # The figures block never streams: see streamable_length.+ text = "".join(thinking_chunks)+ safe = (+ self._grounding.streamable_length(text)+ if self._grounding is not None+ else len(text)+ )+ if safe > streamed_chars:+ self._emit(+ "text_delta",+ {"delta": text[streamed_chars:safe], "iter": current_iter},+ )+ streamed_chars = safedef _on_reasoning_chunk(delta: str) -> None:# Throttled: long reasoning streams produce hundreds of@@ -1480,6 +1496,7 @@ class AgentLoop:},)thinking_chunks.clear()+ streamed_chars = 0reasoning_chars = 0last_reasoning_emit = None# Wait on the cancel event, not time.sleep: the delay now@@ -1841,6 +1858,15 @@ class AgentLoop:"text_delta",{"delta": final_content, "iter": current_iter},)+ elif not self._released_fallback:+ # Flush a held-back last line that never became a+ # figures fence; a stripped block leaves nothing.+ shown = "".join(thinking_chunks)[:streamed_chars]+ if final_content.startswith(shown) and len(final_content) > streamed_chars:+ self._emit(+ "text_delta",+ {"delta": final_content[streamed_chars:], "iter": current_iter},+ )should_continue_goal = Falsecontinuation_snapshot = None_max_cont = _goal_max_continuations()diff --git a/agent/tests/test_grounding_bare_code_lock.py b/agent/tests/test_grounding_bare_code_lock.pynew file mode 100644index 000000000..e7570d87f--- /dev/null+++ b/agent/tests/test_grounding_bare_code_lock.py@@ -0,0 +1,145 @@+"""Spec decision 4: a bare code the user typed is locked by the fetch itself.++A user who writes ``159516`` has named the instrument; only the venue suffix is+the model's choice. ``get_market_data`` may fetch it before any resolver call,+and rows coming back for exactly one venue lock that venue. Rows for two venues+of the same code, the ``000xxx`` range (a Shanghai index and a Shenzhen stock+share those digits), a code the user never typed, any other tool, and a root+something else already locked all keep the resolver requirement.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any, Iterable++import pytest++from src.agent.grounding import GroundingLedger++pytestmark = pytest.mark.unit+++def _rows() -> list[dict[str, Any]]:+ return [+ {"trade_date": "2026-09-09", "open": 0.670, "high": 0.681, "low": 0.567, "close": 0.666}+ ]+++def _fetch(+ ledger: GroundingLedger,+ call_id: str,+ codes: Iterable[str],+ *,+ tool: str = "get_market_data",+ rows_for: set[str] | None = None,+ success: bool = True,+):+ arguments = {"codes": list(codes)}+ decision = ledger.authorize_tool_call(+ tool,+ arguments,+ batch_authorized_symbols=ledger.authorized_symbols,+ call_id=call_id,+ batch_identity_status=ledger.identity_status,+ )+ if decision.allowed:+ payload = {+ code: _rows() if rows_for is None or code in rows_for else []+ for code in arguments["codes"]+ }+ ledger.ingest_tool_result(+ tool_name=tool,+ arguments=arguments,+ result=json.dumps(payload),+ call_id=call_id,+ success=success,+ )+ return decision+++def test_a_bare_code_is_locked_by_the_one_venue_that_returned_rows(tmp_path: Path) -> None:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="159516 现在能买吗?给我一个买入价")++ decision = _fetch(ledger, "c1", ["159516.SZ"])++ assert decision.allowed is True+ assert ledger.identity_status == "locked"+ assert ledger.authorized_symbols == {"159516.SZ"}+ record = next(r for r in ledger.identity_summary()["records"] if r["symbol"] == "159516.SZ")+ assert record["source_tool_call_id"] == "c1"+++def test_two_venues_with_rows_leave_the_code_unlocked(tmp_path: Path) -> None:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="159516 现在能买吗?给我一个买入价")++ _fetch(ledger, "c1", ["159516.SZ", "159516.SH"])++ assert ledger.identity_status == "ambiguous"+ assert ledger.authorized_symbols == set()+++def test_a_second_venue_in_a_later_call_retracts_the_lock(tmp_path: Path) -> None:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="159516 现在能买吗?给我一个买入价")++ _fetch(ledger, "c1", ["159516.SZ"])+ _fetch(ledger, "c2", ["159516.SH"])++ assert ledger.identity_status == "ambiguous"+ assert ledger.authorized_symbols == set()+++def test_a_venue_that_returned_no_rows_does_not_count(tmp_path: Path) -> None:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="159516 现在能买吗?给我一个买入价")++ _fetch(ledger, "c1", ["159516.SZ", "159516.SH"], rows_for={"159516.SZ"})++ assert ledger.identity_status == "locked"+ assert ledger.authorized_symbols == {"159516.SZ"}+++def test_a_failed_fetch_locks_nothing(tmp_path: Path) -> None:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="159516 现在能买吗?给我一个买入价")++ _fetch(ledger, "c1", ["159516.SZ"], success=False)++ assert ledger.authorized_symbols == set()+++def test_the_000_range_is_never_locked_from_a_bare_code(tmp_path: Path) -> None:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="000001 现在能买吗?给我一个买入价")++ decision = _fetch(ledger, "c1", ["000001.SZ"])++ assert decision.allowed is False+ assert decision.error_code == "identity_required"+ assert ledger.authorized_symbols == set()+++def test_a_code_the_user_did_not_type_still_needs_the_resolver(tmp_path: Path) -> None:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="这个机器人ETF现在能买吗?给我一个买入价")++ decision = _fetch(ledger, "c1", ["159516.SZ"])++ assert decision.allowed is False+ assert ledger.authorized_symbols == set()+++def test_only_get_market_data_takes_the_bare_code_path(tmp_path: Path) -> None:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="159516 现在能买吗?给我一个买入价")++ decision = _fetch(ledger, "c1", ["159516.SZ"], tool="technical_indicators")++ assert decision.allowed is False+ assert ledger.authorized_symbols == set()+++def test_a_root_the_user_locked_with_a_suffix_keeps_its_venue(tmp_path: Path) -> None:+ ledger = GroundingLedger(run_dir=tmp_path, user_message="159516.SZ 现在能买吗?给我一个买入价")++ decision = _fetch(ledger, "c1", ["159516.SH"])++ assert decision.allowed is False+ assert decision.error_code == "identity_mismatch"+ assert ledger.authorized_symbols == {"159516.SZ"}diff --git a/agent/tests/test_grounding_figures_contract.py b/agent/tests/test_grounding_figures_contract.pyindex c9ad3494f..d0e24e723 100644--- a/agent/tests/test_grounding_figures_contract.py+++ b/agent/tests/test_grounding_figures_contract.py@@ -665,3 +665,54 @@ def test_a_fabricated_figure_is_refused_under_all_the_same_words(}assert set(verdicts.values()) == {False}, verdicts+++# ---------------------------------------------------------------------------+# The prompt's own examples, and streaming+# ---------------------------------------------------------------------------+++def _prompt_blocks() -> list[str]:+ from src.agent.context import _SYSTEM_PROMPT++ return [+ "```figures" + chunk.split("```")[0] + "```"+ for chunk in _SYSTEM_PROMPT.split("```figures")[1:]+ ]+++def test_every_figures_example_in_the_system_prompt_parses() -> None:+ """A malformed example teaches every run to write a malformed block."""+ blocks = [parse_figures_block("answer\n\n" + raw) for raw in _prompt_blocks()]++ assert len(blocks) == 2+ assert all(block.malformed == () for block in blocks)+ assert {d.role for block in blocks for d in block.declarations} == set(ROLES)+++def test_the_chinese_prompt_example_passes_the_gate_it_describes(tmp_path: Path) -> None:+ """The example sits on the same two bars this module probes with."""+ ledger = _ledger(tmp_path)+ prose = (+ "159516.SZ(akshare,CNY)最新收盘 0.666 元,第一档 0.646 元,"+ "较 5 月高点回撤 37%,买入参考 0.62 元。"+ )++ result = ledger.validate_final_answer(prose + "\n\n" + _prompt_blocks()[0])++ assert result.valid, result.issues+ assert result.released_text == prose+++ ("text", "safe"),+ [+ ("答案。", len("答案。")),+ ("答案。\n\n```figures\n0.666 | observed", len("答案。\n\n")),+ ("答案。\n\n``", len("答案。\n\n")),+ ("答案。\n\n```fig", len("答案。\n\n")),+ ("答案。\n```python\nx = 1\n", len("答案。\n```python\nx = 1\n")),+ ],+)+def test_streaming_holds_back_the_figures_fence_and_nothing_else(text: str, safe: int) -> None:+ assert GroundingLedger.streamable_length(text) == safediff --git a/agent/tests/test_grounding_release.py b/agent/tests/test_grounding_release.pyindex ad2836796..065f58b81 100644--- a/agent/tests/test_grounding_release.py+++ b/agent/tests/test_grounding_release.py@@ -1891,3 +1891,69 @@ def test_the_sweep_never_cuts_a_figure_the_gate_checked(tmp_path: Path) -> None:assert "最新收盘价 1.171 元" in releasedassert "1.171%" not in releasedassert "※ 略去 1 处" in released+++class _ChunkedLLM:+ """Streams its one answer in three-character chunks, like a provider."""++ model_name = "grounding-test"++ def __init__(self, content: str) -> None:+ self.content = content+ self.calls = 0++ def stream_chat(+ self,+ messages: list[dict[str, Any]],+ tools: list[Any] | None = None,+ on_text_chunk: Callable[[str], None] | None = None,+ on_reasoning_chunk: Callable[[str], None] | None = None,+ timeout: int | None = None,+ idle_timeout_s: float | None = None,+ should_cancel: Callable[[], bool] | None = None,+ ) -> _Response:+ self.calls += 1+ if on_text_chunk:+ for start in range(0, len(self.content), 3):+ on_text_chunk(self.content[start : start + 3])+ return _Response(content=self.content)++ def chat(self, messages: list[dict[str, Any]], **kwargs: Any) -> _Response:+ return _Response()+++def _stream(tmp_path: Path, content: str) -> tuple[dict[str, Any], str, AgentLoop]:+ events: list[tuple[str, dict[str, Any]]] = []+ agent = AgentLoop(+ registry=ToolRegistry(),+ llm=_ChunkedLLM(content),+ max_iterations=3,+ event_callback=lambda event, data: events.append((event, data)),+ )+ run_dir = tmp_path / "run"+ run_dir.mkdir()+ agent.memory.run_dir = str(run_dir)+ result = agent.run("总结一下这周的复盘心得")+ streamed = "".join(data.get("delta", "") for event, data in events if event == "text_delta")+ return result, streamed, agent+++def test_a_streamed_answer_never_shows_its_figures_block(tmp_path: Path) -> None:+ """A run with no evidence streams live, and the block still stays out."""+ prose = "建议每周复盘 3 次。"++ result, streamed, agent = _stream(tmp_path, prose + "\n\n```figures\n3 | count | 次/周\n```")++ assert agent._grounding.should_buffer_output is False+ assert result["content"] == prose+ assert "figures" not in streamed and "`" not in streamed+ assert streamed.strip() == prose+++def test_a_held_back_line_that_never_became_a_fence_is_still_shown(tmp_path: Path) -> None:+ content = "复盘要点如下:\n`先写结论,再写过程`"++ result, streamed, _ = _stream(tmp_path, content)++ assert result["content"] == content+ assert streamed == content