Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(grounding): check untagged fences, integer prices in the thousands, prices declared count, and never stream an unchecked number

Haozhe Wu1f7654fec3d0
diff --git a/agent/src/agent/grounding/figures.py b/agent/src/agent/grounding/figures.py
index 635c5f66c..c78652ae8 100644
--- a/agent/src/agent/grounding/figures.py
+++ b/agent/src/agent/grounding/figures.py
@@ -851,7 +851,9 @@ def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:
for index, (line, start) in enumerate(_lines_with_offsets(content))
]
fences = _fenced_blocks(content)
- hard: list[tuple[int, int]] = [(start, end) for start, end, _, _ in fences]
+ # A fence tagged with a language holds code; an untagged one is how a model
+ # sets off a plan or a quote, so its numbers are read as prose.
+ hard: list[tuple[int, int]] = [(start, end) for start, end, info, _ in fences if info]
soft: list[tuple[int, int]] = []
dates = list(_DATE_RE.finditer(text))
full_dates = [match for match in dates if match.group("full")]
diff --git a/agent/src/agent/grounding/ledger.py b/agent/src/agent/grounding/ledger.py
index 78edc40bb..d4e8a09c8 100644
--- a/agent/src/agent/grounding/ledger.py
+++ b/agent/src/agent/grounding/ledger.py
@@ -170,9 +170,11 @@ class GroundingLedger(
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.
+ Held back: everything from the figures block's fence on (the model's
+ declaration to the gate), a last line that could still become that fence,
+ everything from the first measurement-shaped number (the gate has not
+ checked it, and a rejected draft must not have shown it), and a number
+ still being written ("0." before "666").
Args:
text: The answer streamed so far.
@@ -181,12 +183,32 @@ class GroundingLedger(
The length of the prefix that is safe to emit.
"""
span = parse_figures_block(text).span
+ limit = len(text)
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)
+ limit = span[0]
+ else:
+ line_start = text.rfind("\n") + 1
+ if text[line_start:].lstrip()[:1] in ("`", "~"):
+ limit = line_start
+ prefix = text[:limit]
+ measured = GroundingLedger.measurement_start(prefix)
+ if measured is not None:
+ return measured
+ trimmed = prefix.rstrip(" \t")
+ cursor = len(trimmed)
+ while cursor and (trimmed[cursor - 1].isdigit() or trimmed[cursor - 1] in ".,"):
+ cursor -= 1
+ if any(char.isdigit() for char in trimmed[cursor:]):
+ return cursor
+ return limit
+
+ @staticmethod
+ def measurement_start(text: str) -> int | None:
+ """Where the first measurement-shaped number in ``text`` starts, or None."""
+ for figure in scan_figures(text, parse_figures_block(text)):
+ if figure.shape == "measured":
+ return figure.start
+ return None
def identity_summary(self) -> dict[str, Any]:
"""Return compact identity state for traces and tool errors."""
diff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.py
index 4b7658110..411a33f12 100644
--- a/agent/src/agent/grounding/policies.py
+++ b/agent/src/agent/grounding/policies.py
@@ -84,6 +84,11 @@ _OTHER_CURRENCY_PREFIXES = "港美日欧韩台新加澳"
#: Relative band a value must fall in to count as matching evidence.
_TOLERANCE = 0.005
+#: A plain integer is read as a price only for an instrument quoted in the
+#: thousands (600519.SH, an index, BTC). Below that, a prose integer is a window,
+#: a horizon or a count ("20 日均线", "200-day") and stays unchecked.
+_INTEGER_PRICE_FLOOR = 1000.0
+
#: Price fields a rejected prose figure is pointed at, in order (#1433).
_CITABLE_FIELDS = ("close", "price", "adj_close")
@@ -447,14 +452,27 @@ class _PolicyMixin:
for declaration in block.declarations
if declaration.role == "observed"
}
+ # Multipliers a declared derivation uses: a count equal to one is that factor.
+ derived_constants = [
+ operand
+ for declaration in block.declarations
+ if declaration.role == "derived"
+ for evaluated in [_formula_in_note(declaration.note)]
+ if evaluated is not None
+ for operand in evaluated[1]
+ ]
checked_price = False
for figure in figures:
- if figure.shape != "measured":
+ if figure.shape not in ("measured", "bare"):
continue
declaration = block.match(figure.value, figure.percent)
symbol = self._figure_symbol(
content, figure, declaration, line_symbols, document_symbol, records
)
+ if figure.shape == "bare" and not self._poses_as_price(
+ figure, self._price_band(symbol, records)
+ ):
+ continue
if declaration is not None:
written = self._written_symbol(content, figure, line_symbols, records)
if written and symbol and written != symbol:
@@ -505,10 +523,26 @@ class _PolicyMixin:
)
continue
if role == "count":
- if not _is_plain_count(figure):
+ posing = (
+ _is_plain_count(figure)
+ and self._poses_as_price(figure, self._price_band(symbol, records))
+ and not _close_any(figure.value, derived_constants)
+ )
+ if not _is_plain_count(figure) or posing:
checked_price = True
issues.extend(
- self._count_as_observed(figure, declaration, symbol, records)
+ self._count_as_observed(
+ figure,
+ declaration,
+ symbol,
+ records,
+ why=(
+ "it sits in the instrument's observed price range and no "
+ "declared derivation uses it"
+ if posing
+ else "a count cannot carry a currency mark"
+ ),
+ )
)
continue
if role == "cited":
@@ -770,18 +804,51 @@ class _PolicyMixin:
declaration: Declaration,
symbol: str | None,
records: Sequence[EvidenceRecord],
+ *,
+ why: str = "a count cannot carry a currency mark",
) -> list[dict[str, Any]]:
- """Check a ``count`` that carries a measurement as the observation it is."""
+ """Check a ``count`` that looks like a price as the observation it claims to be."""
found = self._check_observed(figure, declaration, symbol, records)
for issue in found:
issue["role"] = "count"
issue["message"] = (
- f"{figure.text} is declared count, but a count cannot carry a currency "
- "mark, so it was checked as observed: "
- + issue["message"][len(figure.text) + 1 :]
+ f"{figure.text} is declared count, but {why}, so it was checked as "
+ "observed: " + issue["message"][len(figure.text) + 1 :]
)
return found
+ def _price_band(
+ self, symbol: str | None, records: Sequence[EvidenceRecord]
+ ) -> tuple[float, float] | None:
+ """The observed price range of a figure's instrument, or None when unknown."""
+ if symbol is None and len({record.symbol for record in records if record.symbol}) > 1:
+ return None
+ prices = [value for value in self._price_pool(symbol, records) if value > 0]
+ return (min(prices), max(prices)) if prices else None
+
+ @staticmethod
+ def _poses_as_price(figure: Figure, band: tuple[float, float] | None) -> bool:
+ """Whether an unmarked number sits where its instrument's price does.
+
+ A decimal inside the observed range (±10%) reads as a quote. An integer
+ does only for an instrument quoted in the thousands, between half and
+ twice its range. A percent is never a price.
+
+ Args:
+ figure: The figure.
+ band: The instrument's observed ``(low, high)``, or None.
+
+ Returns:
+ True when the number should be checked as a price.
+ """
+ if band is None or figure.percent:
+ return False
+ low, high = band
+ value = abs(figure.value)
+ if "." in (figure.digits or figure.text):
+ return low * 0.9 <= value <= high * 1.1
+ return low >= _INTEGER_PRICE_FLOOR and low * 0.5 <= value <= high * 2.0
+
def _metric_pool(self, symbol: str | None) -> list[float]:
"""Metric values from completed analysis results and metric-named leaves."""
values = [
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index ad7efedb5..0d9043ae3 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -1396,18 +1396,21 @@ class AgentLoop:
streamed_chars = 0
stream_total = 0
+ stream_frozen = False
def _on_text_chunk(delta: str) -> None:
- nonlocal streamed_chars, stream_total
+ nonlocal streamed_chars, stream_total, stream_frozen
thinking_chunks.append(delta)
stream_total += len(delta)
- if buffer_text_output:
+ if buffer_text_output or stream_frozen:
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):
+ # Neither the figures block nor an unchecked measurement streams
+ # (see streamable_length). Only a fence character or a digit
+ # can hold text back, so any other chunk is emitted as it
+ # arrives instead of re-parsing the whole answer.
+ if streamed_chars + len(delta) == stream_total and not any(
+ char in "`~" or char.isdigit() for char in delta
+ ):
self._emit("text_delta", {"delta": delta, "iter": current_iter})
streamed_chars = stream_total
return
@@ -1417,6 +1420,9 @@ class AgentLoop:
if self._grounding is not None
else len(text)
)
+ if self._grounding is not None and safe < len(text):
+ # Held at a measurement: nothing after it streams this turn.
+ stream_frozen = self._grounding.measurement_start(text) == safe
if safe > streamed_chars:
self._emit(
"text_delta",
@@ -1507,6 +1513,7 @@ class AgentLoop:
thinking_chunks.clear()
streamed_chars = 0
stream_total = 0
+ stream_frozen = False
reasoning_chars = 0
last_reasoning_emit = None
# Wait on the cancel event, not time.sleep: the delay now
@@ -1749,6 +1756,13 @@ class AgentLoop:
value=final_content,
offload_kind=f"answer-rejected-{current_iter}",
)
+ if not buffer_text_output and streamed_chars:
+ # The stream showed this draft up to its first unchecked
+ # number; the next draft or the released answer replaces it.
+ self._emit(
+ "stream_reset",
+ {"iter": current_iter, "reason": "grounding_rejected"},
+ )
react_trace.append(
{
"type": "answer_rejected",
diff --git a/agent/tests/test_grounding_figures_contract.py b/agent/tests/test_grounding_figures_contract.py
index 2be7cdbe7..5ea2b04d3 100644
--- a/agent/tests/test_grounding_figures_contract.py
+++ b/agent/tests/test_grounding_figures_contract.py
@@ -731,6 +731,9 @@ def test_the_chinese_prompt_example_passes_the_gate_it_describes(tmp_path: Path)
("答案。\n\n``", len("答案。\n\n")),
("答案。\n\n```fig", len("答案。\n\n")),
("答案。\n```python\nx = 1\n", len("答案。\n```python\nx = 1\n")),
+ ("收盘 0.666 元。", len("收盘 ")), # an unchecked measurement waits
+ ("复盘 3", len("复盘 ")), # a number still being written waits
+ ("复盘 3 次。", len("复盘 3 次。")), # a finished bare integer streams
],
)
def test_streaming_holds_back_the_figures_fence_and_nothing_else(text: str, safe: int) -> None:
@@ -787,3 +790,14 @@ def test_a_magnitude_mark_is_a_glued_symbol_not_a_word(
from src.agent.grounding.figures import magnitude_suffix
assert magnitude_suffix(text, end) == expected
+
+
+def test_an_untagged_fence_is_prose_and_a_tagged_one_is_code() -> None:
+ """A trading plan set off in a bare fence was released unchecked."""
+ untagged = "交易计划:\n```\n入场 0.881\n止损 0.800\n```"
+ tagged = "代码:\n```python\nentry = 0.881\n```"
+
+ measured = {f.text for f in scan_figures(untagged, parse_figures_block(untagged)) if f.shape == "measured"}
+
+ assert measured == {"0.881", "0.800"}
+ assert not [f for f in scan_figures(tagged, parse_figures_block(tagged)) if f.shape == "measured"]
diff --git a/agent/tests/test_grounding_release.py b/agent/tests/test_grounding_release.py
index c8ce0791a..ad85edcc8 100644
--- a/agent/tests/test_grounding_release.py
+++ b/agent/tests/test_grounding_release.py
@@ -2071,3 +2071,36 @@ def test_a_figures_block_ending_a_tool_call_turn_is_not_shown(tmp_path: Path) ->
streamed = "".join(data.get("delta", "") for event, data in events if event == "text_delta")
assert "先记一笔。" in streamed
assert "figures" not in streamed
+
+
+def test_an_unchecked_measurement_never_streams_before_the_gate(tmp_path: Path) -> None:
+ """An unbuffered draft stops streaming at its first measurement; a rejection resets it."""
+ llm = _ScriptedLLM(
+ [_Response(content="本周收益约 12.5%,好于上周。"), _Response(content="本周整体不错。")]
+ )
+ events: list[tuple[str, dict[str, Any]]] = []
+ agent = AgentLoop(
+ registry=ToolRegistry(),
+ llm=llm,
+ max_iterations=4,
+ 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")
+ assert "12.5" not in streamed
+ assert [data for event, data in events if event == "stream_reset"]
+ assert result["content"] == "本周整体不错。"
+
+
+def test_a_checked_measurement_streams_once_the_gate_passes(tmp_path: Path) -> None:
+ prose = "仓位上限 5%。"
+
+ result, streamed, _ = _stream(tmp_path, prose + "\n\n```figures\n5% | count | 仓位参数\n```")
+
+ assert result["content"] == prose
+ assert streamed == prose
diff --git a/agent/tests/test_grounding_role_hardening.py b/agent/tests/test_grounding_role_hardening.py
index cc05191ed..a1a6738db 100644
--- a/agent/tests/test_grounding_role_hardening.py
+++ b/agent/tests/test_grounding_role_hardening.py
@@ -137,7 +137,7 @@ def test_a_count_cannot_carry_a_currency_mark(tmp_path: Path, prose: str, row: s
("建议持有 3.5 个月。", "3.5 | count | 月"),
("建议持有 3.0 个月。", "3.0 | count | 月"),
("仓位上限 5%。", "5% | count | 仓位参数"),
- ("折扣系数 0.97。", "0.97 | count | 系数"),
+ ("权重 0.30。", "0.30 | count | 权重"),
("主观判断上涨概率 70%。", "70% | count | 主观判断"),
],
)
@@ -685,3 +685,40 @@ def test_a_referenced_table_cell_is_checked_against_its_own_column(tmp_path: Pat
)
def test_short_tail_risk_names_count_only_as_the_whole_leaf(leaf: str, kind: str | None) -> None:
assert _metric_kind_for_path(leaf) == kind
+
+
+def test_an_integer_price_of_an_instrument_quoted_in_the_thousands_is_checked(tmp_path: Path) -> None:
+ """"最新收盘 1520" was unchecked for 600519.SH; "200 日均线" and a 0.6-yuan ETF's "20 日" stay so."""
+ head = "600519.SH(akshare,CNY)"
+
+ def verdict(name: str, markets: tuple[Any, ...], text: str, message: str):
+ return _ledger(tmp_path / name, *markets, message=message).validate_final_answer(text)
+
+ invented = verdict("bad", (MARKET_B,), head + "最新收盘 1520。", f"分析 {B}")
+ observed = verdict("good", (MARKET_B,), head + "最新收盘 1450。", f"分析 {B}")
+ window = verdict("window", (MARKET_B,), head + "最新收盘 1450,跌破 200 日均线。", f"分析 {B}")
+ small = verdict("small", (MARKET_A,), HDR + " 跌破 20 日均线。", f"分析 {A}")
+
+ assert invented.valid is False
+ assert observed.valid is True, observed.issues
+ assert window.valid is True, window.issues
+ assert small.valid is True, small.issues
+
+
+def test_a_count_inside_the_price_range_needs_a_derivation(tmp_path: Path) -> None:
+ """An unmarked price declared count is checked; a multiplier its derivation uses is not."""
+ posing = _ledger(tmp_path / "posing", MARKET_A).validate_final_answer(
+ HDR + " 最新收盘 0.888。" + _block(ROW, "0.888 | count | n")
+ )
+ factor = _ledger(tmp_path / "factor", MARKET_A).validate_final_answer(
+ HDR + " 第一档 0.646 元,折扣系数 0.97。"
+ + _block(ROW, "0.646 | derived | 0.666 × 0.97 | c1", "0.97 | count | 系数")
+ )
+ weight = _ledger(tmp_path / "weight", MARKET_A).validate_final_answer(
+ HDR + " 权重 0.30。" + _block(ROW, "0.30 | count | 权重")
+ )
+
+ assert posing.valid is False
+ assert "observed price range" in posing.issues[0]["message"]
+ assert factor.valid is True, factor.issues
+ assert weight.valid is True, weight.issues
diff --git a/agent/tests/test_grounding_shape_hardening.py b/agent/tests/test_grounding_shape_hardening.py
index d75c21b84..345ac2cf3 100644
--- a/agent/tests/test_grounding_shape_hardening.py
+++ b/agent/tests/test_grounding_shape_hardening.py
@@ -495,9 +495,12 @@ def test_a_second_figures_opener_ends_an_unclosed_first_block() -> None:
def test_streaming_holds_back_from_the_first_block() -> None:
- text = HDR + _block(HDR_ROW) + "\n\n更多。" + _block("3 | count | n")
+ lead = "先说结论。"
+ text = lead + _block(HDR_ROW) + "\n\n更多。" + _block("3 | count | n")
- assert GroundingLedger.streamable_length(text) == len(HDR) + 2
+ assert GroundingLedger.streamable_length(text) == len(lead) + 2
+ # A measurement before the block holds the stream earlier still.
+ assert GroundingLedger.streamable_length(HDR + _block(HDR_ROW)) == HDR.index("0.666")
# ---------------------------------------------------------------------------