Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(grounding): a redaction keeps a table's row numbers and the words in its cells (#1471)

Haozhe Wub1820b34bcf9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1443a6522..3cdc079e5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -76,6 +76,19 @@ This project adheres to [Semantic Versioning](https://semver.org/).
### Fixed
+- **A redacted answer keeps its row numbers and its labels** (#1471). When the
+ grounding gate released a draft with its unverified figures cut, a ranked
+ table came back with `(omitted※)` in place of 1, 2, 3, of the `12m` in its
+ headers and of "3 names" in the prose. Every integer in a table cell was a
+ measurement, so the rank column was cut; and each cut figure's digits were
+ then swept out of the rest of the page, single digits included. Three shape
+ rules, no word list: a column whose numbered cells read 1, 2, 3 … in row
+ order is the table's index; a plain integer in a cell that also holds a
+ word (`12m mean return`, `Mean beta (9 reported)`) is read as it would be
+ in a sentence, while a cell that holds only a number, any decimal, percent
+ or currency figure, and every cell under an OHLC column stay measurements;
+ and the sweep never keys on a single digit. An integer price of an
+ instrument quoted in the thousands is still checked inside a worded cell.
- **One cash-starved open is one rejection, not twenty-six** (#1470). In
`position_adjustment="hold"`, the search that scales a basket down to the
cash available re-planned every open on each step, and every step whose
diff --git a/agent/src/agent/grounding/figures.py b/agent/src/agent/grounding/figures.py
index 3557e8fcf..71e2c117f 100644
--- a/agent/src/agent/grounding/figures.py
+++ b/agent/src/agent/grounding/figures.py
@@ -56,6 +56,12 @@ _DATE_RE = re.compile(
# required, so a line opening with a figure ("1.171 元是收盘价") is untouched.
_ORDINAL_RE = re.compile(r"(?m)^[^\S\n]*(?:#{1,6}[^\S\n]*)?\d{1,3}[.)、][^\S\n]+")
+# SHAPE 5 — a table cell that only numbers its row ("1", "2.", "3)"), and a word
+# inside a cell: two or more letters of any script ("12m mean return", "12个月").
+# A glued unit letter ("25x", "25 倍") is not a word (#1471).
+_INDEX_CELL_RE = re.compile(r"\d{1,3}[.)]?")
+_CELL_WORD_RE = re.compile(r"[^\W\d_]{2,}")
+
# SHAPE 4 — a CommonMark fence line: at most three spaces of indent, a run of
# backticks or tildes, and the info string.
_FENCE_RE = re.compile(r"(?m)^ {0,3}(`{3,}|~{3,})(.*)$")
@@ -191,6 +197,8 @@ class TableRow:
columns: dict[int, str]
date_column: int | None
symbol_column: int | None
+ # Which table of the document the row belongs to, in document order.
+ table: int = 0
@dataclass(frozen=True)
@@ -660,6 +668,7 @@ def table_rows(content: str) -> list[TableRow]:
positions = _lines_with_offsets(content)
rows: list[TableRow] = []
index = 0
+ table = 0
while index < len(positions):
if positions[index][0].count("|") < 2:
index += 1
@@ -687,8 +696,9 @@ def table_rows(content: str) -> list[TableRow]:
if not cells or _is_separator_row(cells):
continue
rows.append(
- TableRow(line_index, tuple(cells), columns, date_column, symbol_column)
+ TableRow(line_index, tuple(cells), columns, date_column, symbol_column, table)
)
+ table += 1
return rows
@@ -859,16 +869,54 @@ def _short_date_is_structural(content: str, match: re.Match[str], full_dates: Se
return any(segment <= full.start() and full.end() <= match.start() for full in full_dates)
+def _index_cells(rows: Sequence[TableRow]) -> set[tuple[int, int]]:
+ """Spans of the cells of a column that only numbers its table's rows (#1471).
+
+ A column whose numbered cells read 1, 2, 3 … in row order is the table's
+ index. No price or metric takes that shape, and cutting it turned a ranking
+ into a column of omission marks. A cell without a digit ("—", "Total") is
+ skipped; one numbered row proves no sequence, so it takes two. A column the
+ header binds to an OHLC field is never an index.
+
+ Args:
+ rows: Every table row of the document.
+
+ Returns:
+ ``(start, end)`` of each index cell.
+ """
+ tables: dict[int, list[TableRow]] = {}
+ for row in rows:
+ tables.setdefault(row.table, []).append(row)
+ spans: set[tuple[int, int]] = set()
+ for body in tables.values():
+ for position in range(max(len(row.cells) for row in body)):
+ if position in body[0].columns:
+ continue
+ numbered = [
+ row.cells[position]
+ for row in body
+ if position < len(row.cells) and any(char.isdigit() for char in row.cells[position][0])
+ ]
+ if len(numbered) < 2 or not all(_INDEX_CELL_RE.fullmatch(text) for text, _, _ in numbered):
+ continue
+ if [int(text.rstrip(".)")) for text, _, _ in numbered] == list(range(1, len(numbered) + 1)):
+ spans.update((start, end) for _, start, end in numbered)
+ return spans
+
+
def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:
"""Locate and classify every number in the prose of a draft (spec §3).
- * ``exempt`` — a date, time, security-code digits, line-leading ordinal or
- anything fenced; a bare year, compact date or a table date/symbol cell
- only while it carries no decimal point, percent or currency mark (and a
- year not under a price column).
+ * ``exempt`` — a date, time, security-code digits, line-leading ordinal,
+ a table's row-number column or anything fenced; a bare year, compact date
+ or a table date/symbol cell only while it carries no decimal point,
+ percent or currency mark (and a year not under a price column).
* ``measured`` — a decimal point, percent / pp / bp, touching currency mark
- or table cell: the shape a fabricated price or metric takes.
- * ``bare`` — a plain integer (counts, horizons, window lengths): unchecked.
+ or a table cell that holds a number and no word: the shape a fabricated
+ price or metric takes.
+ * ``bare`` — a plain integer (counts, horizons, window lengths), in prose or
+ beside words in a table cell ("12m mean return"): unchecked. A cell under
+ an OHLC column stays measured whatever else it holds.
Args:
content: The candidate answer.
@@ -900,11 +948,13 @@ def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:
(view.start(match.start()), view.end(match.end()))
for match in pattern.finditer(text)
)
+ rows = table_rows(content)
cells = [
(start, end, row, position)
- for row in table_rows(content)
+ for row in rows
for position, (_, start, end) in enumerate(row.cells)
]
+ index_cells = _index_cells(rows)
figures: list[Figure] = []
for token in _numbers(text):
@@ -919,12 +969,19 @@ def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:
structural = row is not None and position in (row.date_column, row.symbol_column)
currency = _currency_before(text, token.start) or _currency_after(text, token.end)
marked = percent or currency or "." in token.digits
- if _within((start, digits_end), hard):
+ # A cell that also holds a word is prose set in a table: its plain
+ # integer is a count or a horizon, as it would be in a sentence (#1471).
+ worded = (
+ row is not None
+ and position not in row.columns
+ and _CELL_WORD_RE.search(row.cells[position][0]) is not None
+ )
+ if _within((start, digits_end), hard) or (cell is not None and cell[:2] in index_cells):
shape = "exempt"
elif structural or _within((start, digits_end), soft):
priced = row is not None and not structural and position in row.columns
shape = "measured" if marked or priced else "exempt"
- elif marked or row is not None:
+ elif marked or (row is not None and not worded):
shape = "measured"
else:
shape = "bare"
diff --git a/agent/src/agent/grounding/release.py b/agent/src/agent/grounding/release.py
index 1149b328e..6f2d40e0d 100644
--- a/agent/src/agent/grounding/release.py
+++ b/agent/src/agent/grounding/release.py
@@ -628,7 +628,8 @@ class _ReleaseMixin:
"37", and a code fence can still print it. Figures compare by normalized
digits, so an escaped spelling is the same restatement. Measured prose
survivors were checked and grounded, and the figures block is not
- answer text, so neither is swept.
+ answer text, so neither is swept. A single-digit figure is never a
+ sweep key.
Args:
text: The already-cut document.
@@ -637,6 +638,9 @@ class _ReleaseMixin:
Returns:
``(rewritten text, normalized digits of each figure swept)``.
"""
+ # One digit restates nothing: every "2" and "3" on the page shares it, and
+ # sweeping them took list references and counts with the figure (#1471).
+ keys = {key for key in keys if len(key) > 1}
if not keys:
return text, []
stale = [
diff --git a/agent/tests/test_grounding_figures_contract.py b/agent/tests/test_grounding_figures_contract.py
index 5ea2b04d3..55c41889e 100644
--- a/agent/tests/test_grounding_figures_contract.py
+++ b/agent/tests/test_grounding_figures_contract.py
@@ -801,3 +801,77 @@ def test_an_untagged_fence_is_prose_and_a_tagged_one_is_code() -> None:
assert measured == {"0.881", "0.800"}
assert not [f for f in scan_figures(tagged, parse_figures_block(tagged)) if f.shape == "measured"]
+
+
+# ---------------------------------------------------------------------------
+# #1471 — a table's row numbers and the words in its cells are not measurements
+# ---------------------------------------------------------------------------
+
+_RANKED = (
+ "| # | 代码 | 市盈率 |\n|---|---|---|\n"
+ "| 1 | 159516.SZ | 45 |\n| 2 | 159516.SZ | 38 |\n| 3 | 159516.SZ | 52 |\n"
+)
+
+
+def test_a_column_that_numbers_its_rows_is_structure() -> None:
+ """1, 2, 3 down a column is the table's index; the metric beside it is still checked."""
+ shapes = {figure.text: figure.shape for figure in scan_figures(_RANKED, parse_figures_block(_RANKED))}
+
+ assert [shapes[number] for number in ("1", "2", "3")] == ["exempt"] * 3
+ assert [shapes[metric] for metric in ("45", "38", "52")] == ["measured"] * 3
+
+
+ "table",
+ [
+ "| 序号 | 值 |\n|---|---|\n| 1. | 45 |\n| 2. | 38 |\n", # numbered with a dot
+ "| 序号 | 值 |\n|---|---|\n| 1) | 45 |\n| — | 40 |\n| 2) | 38 |\n", # a row without a number
+ "| 值 | 名次 |\n|---|---|\n| 45 | 1 |\n| 38 | 2 |\n", # the index need not be first
+ ],
+)
+def test_an_index_column_is_recognised_by_its_sequence(table: str) -> None:
+ measured = {f.text for f in scan_figures(table, parse_figures_block(table)) if f.shape == "measured"}
+ assert measured <= {"45", "40", "38"} and {"45", "38"} <= measured
+
+
+ ("table", "still_measured"),
+ [
+ ("| # | 值 |\n|---|---|\n| 1 | 45 |\n", {"1", "45"}), # one row proves no sequence
+ ("| 手数 | 值 |\n|---|---|\n| 1 | 45 |\n| 2 | 38 |\n| 4 | 52 |\n", {"1", "2", "4"}), # not consecutive
+ ("| 手数 | 值 |\n|---|---|\n| 2 | 45 |\n| 3 | 38 |\n", {"2", "3"}), # does not start at 1
+ ("| 手数 | 值 |\n|---|---|\n| 3 | 45 |\n| 2 | 38 |\n| 1 | 52 |\n", {"3", "2", "1"}), # descending
+ ("| 收盘 | 值 |\n|---|---|\n| 1 | 45 |\n| 2 | 38 |\n", {"1", "2"}), # a price column is never an index
+ ],
+)
+def test_a_column_that_is_not_a_plain_sequence_is_still_checked(table: str, still_measured: set[str]) -> None:
+ measured = {f.text for f in scan_figures(table, parse_figures_block(table)) if f.shape == "measured"}
+ assert still_measured <= measured
+
+
+ ("cell", "figure", "shape"),
+ [
+ ("12m mean return", "12", "bare"), # a horizon inside a label
+ ("Mean beta (9 reported)", "9", "bare"), # a count inside a label
+ ("30 days", "30", "bare"),
+ ("12个月平均收益", "12", "bare"),
+ ("45", "45", "measured"), # a number alone is the table's data
+ ("25x", "25", "measured"), # a glued unit letter is not a word
+ ("25 倍", "25", "measured"),
+ ("1.35 (est.)", "1.35", "measured"), # a decimal is a measurement wherever it stands
+ ("up 37% YoY", "37%", "measured"),
+ ("$950 consensus", "950", "measured"),
+ ],
+)
+def test_a_cell_is_read_as_prose_only_where_it_holds_words(cell: str, figure: str, shape: str) -> None:
+ table = f"| Metric | Value |\n|---|---|\n| {cell} | n/a |\n"
+ shapes = {f.text: f.shape for f in scan_figures(table, parse_figures_block(table))}
+ assert shapes[figure] == shape, shapes
+
+
+def test_words_in_a_price_column_cell_do_not_unbind_it() -> None:
+ """The header bound the column to a close; "300 est" under it is still a close."""
+ table = "| 代码 | 收盘 |\n|---|---|\n| 159516.SZ | 300 est |\n"
+ shapes = {f.text: f.shape for f in scan_figures(table, parse_figures_block(table))}
+ assert shapes["300"] == "measured"
diff --git a/agent/tests/test_grounding_release.py b/agent/tests/test_grounding_release.py
index ad85edcc8..cb74ee7f5 100644
--- a/agent/tests/test_grounding_release.py
+++ b/agent/tests/test_grounding_release.py
@@ -2104,3 +2104,64 @@ def test_a_checked_measurement_streams_once_the_gate_passes(tmp_path: Path) -> N
assert result["content"] == prose
assert streamed == prose
+
+
+# ---------------------------------------------------------------------------
+# #1471 — a redaction cuts the invented figures, not the table's furniture
+# ---------------------------------------------------------------------------
+
+_SCREEN = (
+ "562500.SS (Yahoo, CNY) last close 1.171.\n\n"
+ "| # | Ticker | Sector | 9/16 Close | 12m | 6m | Fwd PE |\n"
+ "|---|---|---|---|---|---|---|\n"
+ "| 1 | 562500.SS | ETF (robotics) | 1.171 | +8.0% | +3.0% | 22.5 |\n"
+ "| 2 | 562500.SS | ETF (robotics) | 1.137 | +5.0% | +2.0% | 18.1 |\n"
+ "| 3 | 562500.SS | ETF (robotics) | 1.171 | +4.0% | +1.0% | 30.2 |\n\n"
+ "| Metric | Value |\n|---|---|\n| 12m mean return | +5.7% |\n| Mean beta (3 reported) | 1.35 |\n\n"
+ "1. Names 1 to 3 are up over 12m and 6m; the sleeve is 3 names in 1 sector.\n"
+ "2. Name 2 trades lower vs the 9/16 close.\n"
+)
+
+
+def test_a_redacted_screen_keeps_its_row_numbers_and_labels(tmp_path: Path) -> None:
+ """The reporter's table came back with its ranks, "12m" and "3 names" all omitted.
+
+ Every row number was a table cell, so a measurement, so cut; and each cut
+ digit was then swept out of the prose. Only the invented returns, multiples
+ and beta may go.
+ """
+ ledger = _ledger(tmp_path, message="Screen a few names and rank them")
+ validation = ledger.validate_final_answer(_SCREEN)
+ flagged = sorted(str(issue["value"]) for issue in validation.issues)
+ assert flagged == sorted(
+ ["+8.0%", "+3.0%", "22.5", "+5.0%", "+2.0%", "18.1", "+4.0%", "+1.0%", "30.2", "+5.7%", "1.35"]
+ )
+
+ released = ledger.redacted_release(_SCREEN, validation)
+
+ assert released is not None
+ for kept in (
+ "| 1 | 562500.SS", "| 2 | 562500.SS", "| 3 | 562500.SS", "| 9/16 Close | 12m | 6m |",
+ "| 12m mean return |", "| Mean beta (3 reported) |",
+ "Names 1 to 3 are up over 12m and 6m; the sleeve is 3 names in 1 sector.",
+ "Name 2 trades lower vs the 9/16 close.",
+ ):
+ assert kept in released, kept
+ for invented in ("8.0%", "22.5", "18.1", "30.2", "5.7%", "1.35"):
+ assert invented not in released, invented
+ assert "11 figure(s)" in released
+ assert ledger.validate_final_answer(released).valid is True
+
+
+def test_the_sweep_does_not_key_on_a_single_digit(tmp_path: Path) -> None:
+ """Cutting "5%" must not take every "5" on the page; two digits still sweep (37 above)."""
+ ledger = _ledger(tmp_path)
+ draft = HDR + " 较高点回撤 5%,跌破 5 日均线,关注 5 只同类基金。"
+ validation = ledger.validate_final_answer(draft)
+
+ released = ledger.redacted_release(draft, validation)
+
+ assert released is not None
+ assert "5%" not in released
+ assert "跌破 5 日均线,关注 5 只同类基金" in released
+ assert "※ 略去 1 处" in released
diff --git a/agent/tests/test_grounding_role_hardening.py b/agent/tests/test_grounding_role_hardening.py
index 2fb6fe8bd..6dc754b27 100644
--- a/agent/tests/test_grounding_role_hardening.py
+++ b/agent/tests/test_grounding_role_hardening.py
@@ -793,3 +793,22 @@ def test_the_spanish_var_report_from_1418_grounds_once_its_confidence_is_declare
assert declared.valid is True, declared.issues
assert invented.valid is False
+
+
+def test_a_worded_cell_still_checks_an_integer_price_in_the_thousands(tmp_path: Path) -> None:
+ """#1471 reads "1520 (limit)" as prose, and prose checks an integer price of 600519.SH."""
+ head = "600519.SH(akshare,CNY)\n\n| 项目 | 说明 |\n|---|---|\n"
+
+ invented = _ledger(tmp_path / "bad", MARKET_B, message=f"分析 {B}").validate_final_answer(
+ head + "| 入场 | 1520 (limit) |\n"
+ )
+ observed = _ledger(tmp_path / "good", MARKET_B, message=f"分析 {B}").validate_final_answer(
+ head + "| 入场 | 1450 (last close) |\n"
+ )
+ horizon = _ledger(tmp_path / "horizon", MARKET_B, message=f"分析 {B}").validate_final_answer(
+ head + "| 周期 | 200 日均线 |\n"
+ )
+
+ assert invented.valid is False
+ assert observed.valid is True, observed.issues
+ assert horizon.valid is True, horizon.issues