"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
refactor(grounding): revision cap 2, per-figure corrections, status events
Haozhe Wude3a4223d6df
diff --git a/agent/src/agent/grounding/ledger.py b/agent/src/agent/grounding/ledger.pyindex 26471648b..5ea9afece 100644--- a/agent/src/agent/grounding/ledger.py+++ b/agent/src/agent/grounding/ledger.py@@ -161,6 +161,11 @@ class GroundingLedger("""Return the number of final drafts checked so far."""return len(self._validations)+ @property+ def figures_removed(self) -> int:+ """Return how many figures the discounted release cut, or 0."""+ return int((self._released or {}).get("figures_removed", 0))+def identity_summary(self) -> dict[str, Any]:"""Return compact identity state for traces and tool errors."""return {diff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.pyindex df9c5e4a8..43d720a7b 100644--- a/agent/src/agent/grounding/policies.py+++ b/agent/src/agent/grounding/policies.py@@ -120,6 +120,25 @@ def _close_any(value: float, targets: Iterable[float]) -> bool:return any(_close(value, target) for target in targets)+def _nearest(value: float, targets: Iterable[float], limit: int = 3) -> list[float]:+ """The observed values closest to a rejected figure.++ A range ("0.567-1.053") tells the model the figure is outside the window;+ the nearest prints tell it what to write instead, which is what spec 6 asks+ the correction prompt to say.++ Args:+ value: The rejected figure's value.+ targets: Every value the relevant evidence pool holds.+ limit: How many to name.++ Returns:+ Up to ``limit`` distinct observed values, closest first.+ """+ unique = sorted({float(target) for target in targets}, key=lambda item: (abs(item - value), item))+ return unique[:limit]++def _written_half_unit(text: str) -> float:"""Half a unit of the last digit a figure was WRITTEN with.@@ -602,6 +621,7 @@ class _PolicyMixin:f"is declared observed from {declaration.ref}, whose results do ""not contain it",source_tool_call_ids=[declaration.ref],+ observed_nearest=_nearest(figure.value, referenced),)]prices = self._price_pool(@@ -647,6 +667,7 @@ class _PolicyMixin:date=figure.date,observed_min=observed[0],observed_max=observed[-1],+ observed_nearest=_nearest(figure.value, observed),)]@@ -743,6 +764,12 @@ class _PolicyMixin:result, _ = derivationif declaration is not None and self._result_matches(declaration, result):return []+ # Reported in the figure's OWN units. ``_result_matches`` compares a+ # percent-written figure against ``result * 100``, so telling a model+ # that wrote "12%" that its formula "evaluates to -0.3675" names a+ # number that appears nowhere in the comparison it just failed.+ scaled = result * 100.0 if figure.percent else result+ shown = f"{scaled:.6g}%" if figure.percent else f"{scaled:.6g}"return [self._figure_issue("numeric_claim_conflict",@@ -750,7 +777,8 @@ class _PolicyMixin:"derived",symbol,"derivation_result_mismatch",- f"is declared derived, but its own formula evaluates to {result:g}",+ f"is declared derived, but its own formula evaluates to {shown}",+ derived_result=shown,)]@@ -803,6 +831,7 @@ class _PolicyMixin:f"{min(prices):g}–{max(prices):g} and its note derives no value",observed_min=min(prices),observed_max=max(prices),+ observed_nearest=_nearest(figure.value, prices),)]diff --git a/agent/src/agent/grounding/release.py b/agent/src/agent/grounding/release.pyindex 138f93140..887a7d567 100644--- a/agent/src/agent/grounding/release.py+++ b/agent/src/agent/grounding/release.py@@ -31,6 +31,16 @@ from src.agent.grounding.policies import ValidationResultMAX_GROUNDING_RECOVERY_ROUNDS = 6+# Drafts the gate may reject on the correction path before the run stops+# revising: the first is handed back with a correction prompt, the second is+# released with its rejected figures cut (spec §0). Two, because a revision+# costs a full model round on a report the user is already waiting for, and+# the third and fourth rounds bought nothing measurable: the release+# path now cuts the figures the gate objected to and ships the rest, so the+# alternative to another round is a discounted answer, not a refusal.+MAX_GROUNDING_REVISIONS = 2++# Issue codes whose figure can be cut out of its clause and the draft released# (see ``redacted_release``), and the provenance codes a data note repairs._REDACTABLE_CODES = frozenset(@@ -83,6 +93,79 @@ def _format_price(value: float) -> str:return format(value, ".10g")+#: What the evidence says about a figure, keyed on the validator's reason. The+#: reason is a state of the CHECK, never a word read out of the answer, so this+#: table is language-independent the way the roles it reports on are.+_CORRECTION_REASONS = {+ "undeclared": "it is not declared at all",+ "no_evidence": "this session holds no evidence of that kind to check it against",+ "value_mismatch": "the observed evidence is {range}",+ "not_in_referenced_call": "call {ref} returned no such value",+ "no_formula": "its note states no arithmetic",+ "formula_not_evaluable": "its note is not an arithmetic expression over two or more operands",+ "formula_not_anchored": "no operand of its note is a value this session observed",+ "no_symbol": "the run holds evidence for more than one instrument and the note names none",+ "derivation_result_mismatch": "its own note evaluates to {result}",+ "outside_observed_range": "it is outside the observed range {range} and its note derives no value",+ "citation_without_source": "its note names no source",+ "cited_as_observed": "it is presented as an observed value of this instrument",+ "unparseable_declaration": "the declaration line could not be read as `value | role | note | ref`",+ "symbol_never_handled": "no tool call in this session passed in or returned that symbol",+}+++def _correction_line(issue: dict[str, Any]) -> str:+ """Render one rejected figure as `written | declared role | evidence`.++ Args:+ issue: One figure-scoped validation issue.++ Returns:+ The line the correction prompt shows for that figure.+ """+ role = issue.get("role")+ declared = f"declared {role}" if role else "not declared"+ if issue.get("code") == "figure_undeclared":+ declared = "not declared"+ reason = str(issue.get("reason") or "")+ template = _CORRECTION_REASONS.get(reason, reason or "it could not be verified")+ low, high = issue.get("observed_min"), issue.get("observed_max")+ span = (+ f"{_format_price(float(low))}\u2013{_format_price(float(high))}"+ if isinstance(low, (int, float)) and isinstance(high, (int, float))+ else "empty"+ )+ result = issue.get("derived_result") # already rendered in the figure's own units+ evidence = template.format(+ range=span,+ ref=issue.get("source_tool_call_ids", [""])[0] if issue.get("source_tool_call_ids") else "",+ result=result if result else "a different value",+ )+ nearest = issue.get("observed_nearest") or []+ if nearest:+ evidence += "; nearest observed " + ", ".join(_format_price(float(item)) for item in nearest)+ symbol = issue.get("symbol")+ subject = f"{issue.get('value')} ({symbol})" if symbol else str(issue.get("value"))+ return f"{subject} | {declared} | {evidence}"+++def _digit_key(text: str) -> str:+ """The digits a figure was written with, ignoring how it was decorated.++ ``37%``, ``37 %`` and a bare ``37`` share one key; ``3`` and ``3.0`` do+ not, because they are not the same number as written and sweeping one for+ the other would cut an unrelated count.++ Args:+ text: The figure exactly as it appears in the answer.++ Returns:+ The comparable digit string, or "" when there is none.+ """+ body = text.strip().rstrip("%\uff05").strip().lstrip("+-")+ return body.replace(",", "").strip()++def _strip_release_markers(content: str) -> str:"""Remove any redaction marker or release note the MODEL wrote.@@ -109,60 +192,48 @@ class _ReleaseMixin:"""Release behaviour of :class:`GroundingLedger`."""def correction_prompt(self, validation: ValidationResult) -> str:- """Build bounded feedback for one rejected model draft.-- The feedback is per NUMBER, not per rule: every figure issue carries- the value as it was written, the role it was declared under and the- reason that role failed, so the message says "0.95 is a proposed level- outside the observed range 0.567–1.053 and its note derives no value"- instead of restating the policy. Each figure then has exactly three- ways out, and they are spelled out once at the end.+ """Build bounded per-figure feedback for one rejected model draft.++ The feedback is per NUMBER, not per rule (spec 6). Each rejected figure+ gets one line naming three things: the figure exactly as it was+ written, the role it was DECLARED under, and what the EVIDENCE says+ about it — the range that was observed, the values nearest to it, or+ the value its own note evaluates to. The three ways out are then stated+ once, because they are the same three for every figure.++ Args:+ validation: The rejected draft's validation result.++ Returns:+ The system message handed back to the model."""lines = ["[GROUNDING GATE] The previous draft was rejected and was not released to the user.",- "Correct every issue using the existing structured identity and tool evidence:",+ "Every figure below, exactly as you wrote it, with what you declared and what the evidence says:",]- for issue in validation.issues[:12]:- lines.append(f"- {issue.get('message', issue.get('code', 'grounding error'))}")- # Name the exact values that must be REMOVED, not rephrased. The model- # tends to restate a rejected figure in a new format; the gate then- # rejects it again and the run burns iterations until the fallback.- banned: list[str] = []- for issue in validation.issues:- if issue.get("code") not in _REDACTABLE_CODES:- continue- value = issue.get("value")- if value is None:- continue- symbol = issue.get("symbol") or ""- label = f"{value:g}" if isinstance(value, (int, float)) else str(value)- banned.append(f"{label} ({symbol})" if symbol else label)- if banned:- deduped = list(dict.fromkeys(banned))- lines.append(- "Every figure above must be either DECLARED with the role it really "- "has, REWRITTEN to a value the tools returned, or REMOVED. Do not "- "restate a rejected value in another format: " + ", ".join(deduped) + "."+ figures, others = [], []+ for issue in validation.issues[:24]:+ (figures if issue.get("value") is not None else others).append(issue)+ lines.extend(f"- {_correction_line(issue)}" for issue in figures)+ lines.extend(+ f"- {issue.get('message', issue.get('code', 'grounding error'))}" for issue in others+ )+ if figures:+ lines.extend(+ [+ "Fix EVERY figure above in one of exactly three ways:",+ " (1) DECLARE it with the role it really has, in the figures block;",+ " (2) REWRITE it to a value this session's tools actually returned;",+ " (3) REMOVE it from the answer.",+ "Restating a rejected value in another format is none of the three and fails again.",+ ])- repeated: list[str] = []- for prior in self._validations:- for prior_issue in prior.get("issues", []):- prior_value = prior_issue.get("value")- if prior_value is None:- continue- mark = (- f"{prior_value:g}"- if isinstance(prior_value, (int, float))- else str(prior_value)- )- if any(entry.startswith(mark) for entry in deduped):- repeated.append(mark)+ repeated = self._repeatedly_rejected(figures)if repeated:lines.append(- "These value(s) have now been rejected repeatedly across drafts: "- + ", ".join(dict.fromkeys(repeated))- + ". Repeating them in any form keeps failing; drop them, or show "- "the full derivation from the observed inputs."+ "These value(s) have now been rejected across more than one draft: "+ + ", ".join(repeated)+ + ". Take option (2) or (3) for them.")lines.extend([@@ -207,6 +278,28 @@ class _ReleaseMixin:)return "\n".join(lines)+ def _repeatedly_rejected(self, issues: Sequence[dict[str, Any]]) -> list[str]:+ """Figures this draft repeats that an earlier draft was already refused for.++ The model tends to restate a rejected figure in a new format rather+ than drop it; the gate refuses it again and the run burns its whole+ revision budget on one number.++ Args:+ issues: The current draft's figure issues.++ Returns:+ The repeated figures as written, in order, without duplicates.+ """+ current = {str(issue.get("value")) for issue in issues}+ repeated = [+ str(prior_issue.get("value"))+ for prior in self._validations[:-1]+ for prior_issue in prior.get("issues", [])+ if str(prior_issue.get("value")) in current+ ]+ return list(dict.fromkeys(repeated))+def recovery_action(self, validation: ValidationResult) -> str | None:"""Decide the next safe read-only recovery step for a rejected draft.@@ -454,14 +547,10 @@ class _ReleaseMixin:appended if that is all that remains, and the cut document isre-validated by the same gate: only text that passes is returned.- The document-wide "sweep every other copy of the figure" second stage- is gone. It existed because the old validators only ever looked at- clauses carrying a price word, so the same rejected number could stand- untouched in a bullet or under a non-OHLC table header while the- footnote claimed it had been removed. Every measurement-shaped number- is now located and checked individually, so an occurrence that was not- flagged is one this gate grounded, and cutting it would remove a- figure the evidence supports.+ A document-wide sweep then removes any UNCHECKED restatement of a+ figure that was cut (see :meth:`_sweep_same_values`), so the footnote's+ count is the number of places the figure no longer appears, not the+ number of spans the validator happened to flag.Fail-closed by construction. None — leave the canned fallback in place— whenever the run never observed a price at all, an issue is not a@@ -484,30 +573,39 @@ class _ReleaseMixin:# cuts will actually be made in.check = validation if text == content else self._validate(text, record=False)removed = 0+ keys: set[str] = set()for _ in range(_MAX_REDACTION_PASSES):if check.valid:breakcodes = {issue.get("code") for issue in check.issues}if not codes <= (_REDACTABLE_CODES | _REPAIRABLE_PROVENANCE_CODES):return None- cut, count = self._cut_flagged(text, check.issues)+ cut, cut_texts = self._cut_flagged(text, check.issues)if cut is None:return None- if count:+ if cut_texts:text = cut- removed += count+ removed += len(cut_texts)+ keys.update(_digit_key(item) for item in cut_texts)check = self._validate(text, record=False)if check.valid:breakrepaired = self.repair_provenance(text, check)if repaired is None:- if count == 0:+ if not cut_texts:return Nonecontinuetext = repairedcheck = self._validate(text, record=False)if not check.valid or removed == 0:return None+ # A cut figure can still be standing where the shape rules never look.+ swept, swept_texts = self._sweep_same_values(text, keys - {""})+ if swept_texts:+ recheck = self._validate(swept, record=False)+ if not recheck.valid:+ return None+ text, check, removed = swept, recheck, removed + len(swept_texts)body = check.released_textnote = self._release_note(removed, body)# The note carries the observed range and the canonical symbols, so it@@ -559,7 +657,7 @@ class _ReleaseMixin:self,text: str,issues: Sequence[dict[str, Any]],- ) -> tuple[str | None, int]:+ ) -> tuple[str | None, list[str]]:"""Replace every flagged figure with the omission marker.An issue naming one figure cuts that figure. An issue with no value —@@ -572,8 +670,9 @@ class _ReleaseMixin:issues: The issues raised against it.Returns:- ``(rewritten text, figures replaced)``, or ``(None, 0)`` when a- flagged issue could not be located and the release must fail closed.+ ``(rewritten text, figures replaced as written)``, or+ ``(None, [])`` when a flagged issue could not be located and the+ release must fail closed."""block = parse_figures_block(text)figures = scan_figures(text, block)@@ -583,7 +682,7 @@ class _ReleaseMixin:continuespan = self._issue_span(text, issue)if span is None:- return None, 0+ return None, []if issue.get("value") is None:cuts.update((figure.start, figure.end)@@ -594,14 +693,65 @@ class _ReleaseMixin:)else:cuts.add(span)+ return self._apply_cuts(text, cuts)++ def _sweep_same_values(self, text: str, keys: set[str]) -> tuple[str, list[str]]:+ """Cut every UNCHECKED restatement of a figure that was already cut.++ Cutting a figure at its own span leaves the same claim standing+ wherever the shape rules do not check it. A bare integer is the one+ such place: "回撤 37%" is a measurement and is verified, while the+ "37" of "回撤 37 个百分点" is a bare integer that spec 3 deliberately+ does not check, so the number the footnote says was removed would+ still be on the page.++ Only bare figures are swept. A measurement-shaped occurrence that+ survived the cuts is one this gate CHECKED and grounded, and removing+ it would delete a figure the evidence supports; an exempt occurrence+ is a date, a security code or fenced text, and cutting those corrupts+ the structure they belong to.++ Args:+ text: The already-cut document.+ keys: Digit keys of the figures that were cut.++ Returns:+ ``(rewritten text, figures swept as written)``.+ """+ if not keys:+ return text, []+ block = parse_figures_block(text)+ cuts = {+ (figure.start, figure.end)+ for figure in scan_figures(text, block)+ if figure.shape == "bare" and _digit_key(figure.text) in keys+ }+ swept, cut_texts = self._apply_cuts(text, cuts)+ return (text, []) if swept is None else (swept, cut_texts)++ def _apply_cuts(+ self,+ text: str,+ cuts: set[tuple[int, int]],+ ) -> tuple[str | None, list[str]]:+ """Replace each span with the omission marker in the script it sits in.++ Args:+ text: The document to rewrite.+ cuts: Spans of the figures to remove.++ Returns:+ ``(rewritten text, the figures removed as written)``.+ """if not cuts:- return text, 0+ return text, []pieces: list[str] = []+ removed: list[str] = []cursor = 0- count = 0for start, end in sorted(cuts):if start < cursor:continue+ removed.append(text[start:end])start = max(cursor, currency_prefix_start(text, start))end = currency_suffix_end(text, end)marker = self._marker_for(text, start)@@ -619,9 +769,8 @@ class _ReleaseMixin:pieces.append(text[cursor:start])pieces.append(marker)cursor = end- count += 1pieces.append(text[cursor:])- return "".join(pieces), count+ return "".join(pieces), removeddef _marker_for(self, text: str, position: int) -> str:"""Pick the omission marker in the script of the line being cut.diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 9a69a2267..31a230878 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -29,6 +29,7 @@ from typing import Any, Callable, Dict, List, Mapping, Optionalfrom src.agent.context import ContextBuilderfrom src.agent.grounding import GroundingLedger+from src.agent.grounding.release import MAX_GROUNDING_REVISIONSfrom src.agent.memory import WorkspaceMemoryfrom src.agent.progress import HeartbeatTimer, ProgressEvent, _set_emitterfrom src.agent.tool_progress import RECOVERY_MESSAGE, ToolProgress@@ -1272,6 +1273,7 @@ class AgentLoop:content_filter_circuit_breaker = Falseempty_model_response_iter: int | None = Noneconsecutive_empty_responses = 0+ grounding_revisions = 0llm_usage_summary = _new_llm_usage_summary(self.llm)last_response_model: str | None = Nonegoal_continuations = 0@@ -1697,6 +1699,10 @@ class AgentLoop:)final_content = repairedvalidation = recheck+ if validation.valid:+ # The figures block is the model's declaration to+ # the gate, not answer text.+ final_content = validation.released_textif not validation.valid:trace.write_text_entry({@@ -1736,6 +1742,14 @@ class AgentLoop:"content": f"<system>{self._grounding.recovery_prompt(recovery, validation)}</system>",})+ self._emit(+ "grounding_status",+ {+ "stage": "revising",+ "round": self._grounding.validation_count,+ "issues": len(validation.issues),+ },+ )final_content = ""continuemessages.append(@@ -1746,14 +1760,26 @@ class AgentLoop:)rejected_draft = final_contentfinal_content = ""- # One extra revision when real iteration budget remains;- # each revision costs one iteration, so without budget the- # run must stop revising and release the safe fallback.- revision_cap = 4 if self.max_iterations - iteration >= 3 else 3+ # The budget counts drafts rejected on this+ # correction path; the last one is released with+ # its figures cut. A draft that triggered bounded+ # recovery is not counted (it re-fetches evidence+ # rather than rewording), so a run that had to+ # resolve its symbol first still gets a corrected+ # draft.+ grounding_revisions += 1if (iteration < self.max_iterations- and self._grounding.validation_count < revision_cap+ and grounding_revisions < MAX_GROUNDING_REVISIONS):+ self._emit(+ "grounding_status",+ {+ "stage": "revising",+ "round": self._grounding.validation_count,+ "issues": len(validation.issues),+ },+ )continue# Out of revisions. The last draft is still the# analysis the user waited minutes for; release it@@ -1781,6 +1807,13 @@ class AgentLoop:})final_content = released+ self._emit(+ "grounding_status",+ {+ "stage": "released_redacted",+ "removed": self._grounding.figures_removed,+ },+ )self._released_fallback_reason = ("final answer released with unverified figures "f"redacted after {rejected_drafts} rejected drafts"diff --git a/agent/tests/test_grounding_figures_contract.py b/agent/tests/test_grounding_figures_contract.pyindex aae7ea6e9..c9ad3494f 100644--- a/agent/tests/test_grounding_figures_contract.py+++ b/agent/tests/test_grounding_figures_contract.py@@ -557,18 +557,60 @@ def test_undeclared_mode_does_not_guess_proposed_or_derived(tmp_path: Path) -> Ndef test_the_correction_prompt_names_each_figure_and_its_reason(tmp_path: Path,) -> None:- """§6: the feedback is per number, not a restatement of the policy."""+ """§6: the feedback is per number, not a restatement of the policy.++ Three things per figure — what was written, what was declared, what the+ evidence says — plus the three fixes stated once.+ """ledger = _ledger(tmp_path)validation = ledger.validate_final_answer(HDR + " 建议买入价 2.50 元。" + _block(HDR_ROW, "2.50 | proposed | entry"))prompt = ledger.correction_prompt(validation)+ line = next(row for row in prompt.splitlines() if row.startswith("- 2.50"))- assert "2.50" in prompt- assert "0.567" in prompt and "1.053" in prompt+ assert "declared proposed" in line+ assert "0.567" in line and "1.053" in line+ assert "nearest observed 1.053, 1.04, 1.02" in lineassert "figures" in prompt- assert "DECLARED" in prompt and "REWRITTEN" in prompt and "REMOVED" in prompt+ assert "DECLARE" in prompt and "REWRITE" in prompt and "REMOVE" in prompt+++def test_a_value_is_called_repeated_only_from_its_second_rejection(+ tmp_path: Path,+) -> None:+ """The current draft is not its own predecessor.++ Comparing against every recorded validation, the current one included,+ told the model on its FIRST rejection that the figure had been refused+ "repeatedly", which is false and trains it to ignore the line.+ """+ ledger = _ledger(tmp_path)+ draft = HDR + " 建议买入价 2.50 元。" + _block(HDR_ROW, "2.50 | proposed | entry")++ first = ledger.correction_prompt(ledger.validate_final_answer(draft))+ second = ledger.correction_prompt(ledger.validate_final_answer(draft))++ assert "more than one draft" not in first+ assert "more than one draft: 2.50." in second+++def test_a_derived_percent_is_corrected_in_its_own_units(tmp_path: Path) -> None:+ """A model that wrote "12%" is told what its formula gives in percent."""+ ledger = _ledger(tmp_path)+ validation = ledger.validate_final_answer(+ HDR+ + " 较 5 月高点回撤 12%。"+ + _block(HDR_ROW, "12% | derived | (0.666 − 1.053) / 1.053 | c1")+ )++ prompt = ledger.correction_prompt(validation)+ line = next(row for row in prompt.splitlines() if row.startswith("- 12"))++ assert "declared derived" in line+ assert "evaluates to -36.7521%" in line+ assert "-0.36" not in prompt# ---------------------------------------------------------------------------diff --git a/agent/tests/test_grounding_recovery.py b/agent/tests/test_grounding_recovery.pyindex fe1e6ab04..6b5298cb8 100644--- a/agent/tests/test_grounding_recovery.py+++ b/agent/tests/test_grounding_recovery.py@@ -350,7 +350,12 @@ class _FailingDraftLLM:return LLMResponse(content="")-def _run_direct_loop(tmp_path: Path, llm: Any, max_iterations: int = 8) -> dict[str, Any]:+def _run_direct_loop(+ tmp_path: Path,+ llm: Any,+ max_iterations: int = 8,+ events: list[tuple[str, dict[str, Any]]] | None = None,+) -> dict[str, Any]:from src.agent.loop import AgentLoopfrom src.memory.persistent import PersistentMemoryfrom src.tools import build_registry@@ -361,6 +366,9 @@ def _run_direct_loop(tmp_path: Path, llm: Any, max_iterations: int = 8) -> dict[llm=llm,max_iterations=max_iterations,persistent_memory=pm,+ event_callback=(lambda event, data: events.append((event, data)))+ if events is not None+ else None,)run_dir = tmp_path / "run"run_dir.mkdir(parents=True, exist_ok=True)@@ -375,14 +383,24 @@ def test_loop_runs_recovery_before_fallback(from src.agent.trace import TraceWriterllm = _FailingDraftLLM()+ events: list[tuple[str, dict[str, Any]]] = []- result = _run_direct_loop(tmp_path, llm, max_iterations=6)+ result = _run_direct_loop(tmp_path, llm, max_iterations=6, events=events)trace = TraceWriter.read(tmp_path / "run")recovery_entries = [e for e in trace if e.get("type") == "grounding_recovery"]# Symbol resolution budget is two: two recovery turns, then fallback.assert [e.get("action") for e in recovery_entries] == ["search_symbol", "search_symbol"]- assert llm.calls >= 3+ # Two recovery drafts, then the correction path: one draft handed back+ # and the one that ends revising. Recovery does not spend the revision+ # cap, and every rejection that leads to another draft is announced.+ assert llm.calls == 4+ statuses = [data for event, data in events if event == "grounding_status"]+ assert [(status["stage"], status["round"]) for status in statuses] == [+ ("revising", 1),+ ("revising", 2),+ ("revising", 3),+ ]# Recovery and correction steering must never be mid-conversation system# messages: Anthropic only accepts a single leading system block.assert_system_messages_only_lead(llm.messages_history)diff --git a/agent/tests/test_grounding_release.py b/agent/tests/test_grounding_release.pyindex 09e20700e..ad2836796 100644--- a/agent/tests/test_grounding_release.py+++ b/agent/tests/test_grounding_release.py@@ -712,8 +712,13 @@ def test_loop_releases_the_redacted_draft_instead_of_the_canned_refusal(tmp_pathreported = re.search(r"after (\d+) rejected drafts", end["reason"])assert reported is not None, end["reason"]assert int(reported.group(1)) == agent._grounding.validation_count- assert int(reported.group(1)) == 4- assert llm.calls >= 5+ # Revision cap 2: the first draft is corrected, the second is released cut.+ assert int(reported.group(1)) == 2+ assert llm.calls == len(_SCRIPT_HEAD) + 2+ statuses = [data for event, data in events if event == "grounding_status"]+ assert [status["stage"] for status in statuses] == ["revising", "released_redacted"]+ assert statuses[0]["round"] == 1 and statuses[0]["issues"] >= 1+ assert statuses[1]["removed"] == 1assert_system_messages_only_lead(llm.messages_history)@@ -1805,3 +1810,84 @@ def test_line_offsets_are_a_monotone_scan() -> None:assert all(content[offset : offset + len(line)] == line for line, offset in positions)+++# ---------------------------------------------------------------------------+# Revision cap 2 plumbing: the released text, the status events, the sweep+# ---------------------------------------------------------------------------+++def test_loop_releases_a_valid_draft_without_its_figures_block(tmp_path: Path) -> None:+ """The block is the model's declaration to the gate, never answer text."""+ prose = "562500.SS(Yahoo,CNY)在 2026-06-23 的已观测收盘价为 1.137。"+ draft = prose + "\n\n```figures\n1.137 | observed | 562500.SS close 2026-06-23 | prices\n```"+ llm = _ScriptedLLM(_SCRIPT_HEAD + [_Response(content=draft)])++ result, events, agent = _run(tmp_path, llm, max_iterations=8)++ assert result["status"] == "success"+ assert result.get("degraded") is None+ assert result["content"] == prose+ streamed = "".join(data.get("delta", "") for event, data in events if event == "text_delta")+ assert streamed == prose+ assert llm.calls == len(_SCRIPT_HEAD) + 1+ assert not [event for event, _ in events if event == "grounding_status"]+ artifact = json.loads(+ (tmp_path / "run" / "artifacts" / "grounding_evidence.json").read_text(encoding="utf-8")+ )+ assert "1.137 | observed" in artifact["validations"][-1]["figures_block"]+++def test_the_sweep_cuts_a_bare_restatement_of_a_cut_figure(tmp_path: Path) -> None:+ """The footnote's count is where the figure no longer appears.++ "37%" is a measurement and is cut at its span; "37 个百分点" is a bare+ integer the shape rules never check, so without the sweep the number the+ footnote says was removed would still be on the page.+ """+ ledger = _ledger(tmp_path)+ draft = HDR + " 较高点回撤 37%,即回撤 37 个百分点;20 日均线走平。"+ validation = ledger.validate_final_answer(draft)++ released = ledger.redacted_release(draft, validation)++ assert released is not None+ assert "37" not in released+ assert "20 日均线" in released and "1.171" in released+ assert "※ 略去 2 处" in released+ assert ledger.figures_removed == 2+++def test_the_sweep_leaves_a_bare_integer_with_different_digits(tmp_path: Path) -> None:+ """Cutting "0.95" must not take the "95" of an unrelated count with it."""+ ledger = _ledger(tmp_path)+ draft = HDR + " 建议买入价 0.95 元,计划持有 95 天。"+ validation = ledger.validate_final_answer(draft)++ released = ledger.redacted_release(draft, validation)++ assert released is not None+ assert "0.95" not in released+ assert "持有 95 天" in released+ assert "※ 略去 1 处" in released+ assert ledger.figures_removed == 1+++def test_the_sweep_never_cuts_a_figure_the_gate_checked(tmp_path: Path) -> None:+ """Only bare integers are swept; a decimal sharing the cut figure's digits stays.++ "1.171%" is cut, and the observed close "1.171 元" carries the same digits.+ The close is a measurement the gate checked and grounded, so sweeping it+ would delete a figure the evidence supports.+ """+ ledger = _ledger(tmp_path)+ draft = HDR + " 日内振幅 1.171%。"+ validation = ledger.validate_final_answer(draft)+ assert [issue for issue in validation.issues if issue.get("value") is not None]++ released = ledger.redacted_release(draft, validation)++ assert released is not None+ assert "最新收盘价 1.171 元" in released+ assert "1.171%" not in released+ assert "※ 略去 1 处" in released