Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(grounding): drop the bare-code lock, align the prompt with the gate, stream prose after the block

Haozhe Wuf3a636d3798a
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.py
index 221ae4cb1..6b557f7f2 100644
--- a/agent/src/agent/context.py
+++ b/agent/src/agent/context.py
@@ -185,17 +185,23 @@ Decide which workflow to use based on the request:
three may be written in the user's language (`雅虎`, `腾讯`, `元`). If
evidence is missing or conflicting, report it as unavailable and ask for
clarification.
-- **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):
+- **Declare every figure that is not a plain tool value:** a number with a
+ decimal point, a percent sign or a currency mark, or in a table cell, is
+ checked against this session's tool results. A price or volume a tool
+ returned needs nothing more. Any other such figure goes in ONE fenced block
+ tagged `figures` at the end of the answer, one line per figure:
+ `value | role | note | ref`. Roles:
+ `observed` — a tool value that is not a price or volume of the symbol, e.g. a
+ PE ratio (`ref`: the tool name such as `get_fundamentals`, or its call id);
+ `derived` — arithmetic on observed values (`note`: the formula; every number
+ added or subtracted must itself be an observed value);
+ `proposed` — a price level you suggest, such as an entry, stop or target: inside
+ the observed price range, or with a formula over observed values in `note`; a
+ percentage is not a level, so state the price it implies;
+ `cited` — from a source other than this session's tools: name the source in the
+ same sentence as the figure, and in `note`;
+ `count` — an integer count, window or horizon. Plain integers, 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
diff --git a/agent/src/agent/grounding/identity.py b/agent/src/agent/grounding/identity.py
index 12f133f94..6e3e1eae1 100644
--- a/agent/src/agent/grounding/identity.py
+++ b/agent/src/agent/grounding/identity.py
@@ -425,10 +425,6 @@ 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`."""
@@ -486,8 +482,6 @@ class _IdentityMixin:
self._identity_required = True
self._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_status
if frozen_status != "locked" or not authorized:
@@ -945,100 +939,6 @@ 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.py
index e3aca17ed..78edc40bb 100644
--- a/agent/src/agent/grounding/ledger.py
+++ b/agent/src/agent/grounding/ledger.py
@@ -110,14 +110,6 @@ 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()
@@ -249,7 +241,6 @@ 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()
@@ -270,9 +261,9 @@ class GroundingLedger(
"""Validate text WITHOUT counting it as a rejected draft.
For the recheck that follows a deterministic repair or redaction. No
- model round produced that text, so recording it would spend one unit
- of the revision budget (``loop.py``) and add an attempt to the
- artifact that no draft stands behind.
+ model round produced that text, so recording it would count a
+ rejected draft nobody wrote and add an artifact attempt no draft
+ stands behind.
Args:
content: The repaired or redacted answer.
@@ -285,12 +276,10 @@ class GroundingLedger(
def _validate(self, content: str, *, record: bool) -> ValidationResult:
"""Run the gate, optionally without recording the attempt.
- ``validation_count`` is the run's rejected-DRAFT count: it caps the
- revision budget (``loop.py``) and is printed to the user as the number
- of rejected drafts in the degraded-run reason. The release path's own
- rechecks are not drafts — one successful ``redacted_release`` inflated
- the count from 1 to 4 with no model round in between, shrinking the
- budget and overstating the audit number — so they pass ``record=False``.
+ ``validation_count`` is the run's checked-DRAFT count: the degraded-run
+ reason prints it and the ``grounding_status`` round follows it (the
+ revision cap itself is counted in ``loop.py``). The release path's own
+ rechecks are not drafts, so they pass ``record=False``.
Args:
content: Candidate assistant answer.
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index efe73cffc..45cf20d70 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -1395,13 +1395,22 @@ class AgentLoop:
)
streamed_chars = 0
+ stream_total = 0
def _on_text_chunk(delta: str) -> None:
- nonlocal streamed_chars
+ nonlocal streamed_chars, stream_total
thinking_chunks.append(delta)
+ stream_total += len(delta)
if buffer_text_output:
return
# The figures block never streams: see streamable_length.
+ # Only a fence character can hold text back, so a clean
+ # stream is emitted as it arrives instead of re-parsing the
+ # whole answer on every chunk.
+ if streamed_chars + len(delta) == stream_total and not ("`" in delta or "~" in delta):
+ self._emit("text_delta", {"delta": delta, "iter": current_iter})
+ streamed_chars = stream_total
+ return
text = "".join(thinking_chunks)
safe = (
self._grounding.streamable_length(text)
@@ -1497,6 +1506,7 @@ class AgentLoop:
)
thinking_chunks.clear()
streamed_chars = 0
+ stream_total = 0
reasoning_chars = 0
last_reasoning_emit = None
# Wait on the cancel event, not time.sleep: the delay now
@@ -1700,8 +1710,7 @@ class AgentLoop:
if repaired is not None:
# Non-recording: no model round produced this
# text, and ``validation_count`` is the
- # revision budget AND the rejected-draft
- # number the user is shown.
+ # rejected-draft number the user is shown.
recheck = self._grounding.revalidate(repaired)
if recheck.valid:
trace.write(
@@ -1862,10 +1871,14 @@ class AgentLoop:
# 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:
+ if not final_content.startswith(shown):
+ # Stripping the block also trims the blank lines
+ # the stream already showed before its fence.
+ shown = shown.rstrip()
+ if final_content.startswith(shown) and len(final_content) > len(shown):
self._emit(
"text_delta",
- {"delta": final_content[streamed_chars:], "iter": current_iter},
+ {"delta": final_content[len(shown):], "iter": current_iter},
)
should_continue_goal = False
continuation_snapshot = None
diff --git a/agent/tests/test_grounding_bare_code_lock.py b/agent/tests/test_grounding_bare_code_lock.py
deleted file mode 100644
index bc22a4a8f..000000000
--- a/agent/tests/test_grounding_bare_code_lock.py
+++ /dev/null
@@ -1,155 +0,0 @@
-"""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"}
-
-
-def test_a_typed_code_does_not_carry_an_untyped_one_through(tmp_path: Path) -> None:
- """Every symbol in the call must be vouched for, not just one of them."""
- ledger = GroundingLedger(run_dir=tmp_path, user_message="159516 现在能买吗?给我一个买入价")
-
- decision = _fetch(ledger, "c1", ["159516.SZ", "510300.SH"])
-
- assert decision.allowed is False
- assert ledger.authorized_symbols == set()
diff --git a/agent/tests/test_grounding_release.py b/agent/tests/test_grounding_release.py
index 065f58b81..615255f1a 100644
--- a/agent/tests/test_grounding_release.py
+++ b/agent/tests/test_grounding_release.py
@@ -1957,3 +1957,14 @@ def test_a_held_back_line_that_never_became_a_fence_is_still_shown(tmp_path: Pat
assert result["content"] == content
assert streamed == content
+
+
+def test_prose_after_the_figures_block_still_reaches_the_stream(tmp_path: Path) -> None:
+ """The block is held back from its fence on; what follows it is flushed at the end."""
+ content = "建议每周复盘 3 次。\n\n```figures\n3 | count | 次/周\n```\n\n补充:先写结论。"
+
+ result, streamed, _ = _stream(tmp_path, content)
+
+ assert "figures" not in streamed
+ assert "补充:先写结论。" in result["content"]
+ assert streamed.rstrip().endswith("补充:先写结论。")
diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsx
index 06c905941..f3831f758 100644
--- a/frontend/src/pages/Agent.tsx
+++ b/frontend/src/pages/Agent.tsx
@@ -791,6 +791,9 @@ export function Agent() {
tool_call: (d) => {
touch();
replayAttemptSeenRef.current = true;
+ // A recovery round fetches evidence before the next draft; the tool
+ // activity line says what is happening, so the status line steps aside.
+ setGroundingRevision(null);
if (!identifyActivity(d, "working")) return;
queueStreamUpdate("", false);
const toolName = String(d.tool || "");
diff --git a/frontend/src/pages/__tests__/AgentGroundingStatus.test.tsx b/frontend/src/pages/__tests__/AgentGroundingStatus.test.tsx
index e3fa53f0d..af9edacde 100644
--- a/frontend/src/pages/__tests__/AgentGroundingStatus.test.tsx
+++ b/frontend/src/pages/__tests__/AgentGroundingStatus.test.tsx
@@ -153,4 +153,24 @@ describe("Agent grounding status line", () => {
expect(useAgentStore.getState().status).toBe("streaming");
expect(screen.queryByText(STATUS_TEXT)).not.toBeInTheDocument();
});
+
+ it("steps aside when a recovery round starts a tool call", async () => {
+ await renderStreamingAttempt("attempt-1");
+
+ act(() => {
+ latestHandlers().grounding_status({ attempt_id: "attempt-1", stage: "revising", round: 1, issues: 2 });
+ });
+ expect(screen.getByText("Checking the figures in this answer (round 1)…")).toBeInTheDocument();
+
+ act(() => {
+ latestHandlers().tool_call({
+ attempt_id: "attempt-1",
+ tool: "get_market_data",
+ call_id: "call-recovery",
+ arguments: { codes: ["159516.SZ"] },
+ });
+ });
+ expect(screen.queryByText(STATUS_TEXT)).not.toBeInTheDocument();
+ });
+
});