"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(agent): unblock tools whose results microcompact cleared
Yufeng He4642dc9f4921
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 923c108cb..7db7c901e 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -434,19 +434,30 @@ def _verification_ledger(messages: list) -> str:breakreturn "\n".join(unique)-def _microcompact(messages: list) -> None:+def _microcompact(messages: list) -> list:"""Layer 1: silently prune old tool results, keeping the most recent N intact.Args:messages: Message list (mutated in place).++ Returns:+ Names of tools whose every result just became unreadable. The caller+ drops these from the dedup ledger: blocking a re-call with "use the+ previous result" only makes sense while that result is still in+ context, and a cleared result is not."""tool_msgs = [m for m in messages if m.get("role") == "tool"]if len(tool_msgs) <= KEEP_RECENT:- return+ return []+ newly_cleared = []for msg in tool_msgs[:-KEEP_RECENT]:content = msg.get("content", "")if isinstance(content, str) and len(content) > 100:msg["content"] = "[cleared]"+ if msg.get("name"):+ newly_cleared.append(msg["name"])+ surviving = {m.get("name") for m in tool_msgs if m.get("content") != "[cleared]"}+ return sorted(set(newly_cleared) - surviving)def _context_collapse(messages: list) -> None:@@ -1159,7 +1170,13 @@ class AgentLoop:# tool history available for the model to reference instead of# having every result past the most recent few cleared.if tokens > int(_token_threshold() * 0.5):- _microcompact(messages)+ unreadable_tools = _microcompact(messages)+ if unreadable_tools:+ # The dedup ledger may only point the model at results+ # that are still in context; a cleared result is not,+ # so those tools become callable again.+ self._called_ok.difference_update(unreadable_tools)+ trace.write({"type": "microcompact_cleared", "iter": iteration, "tools": unreadable_tools})tokens = estimate_tokens(messages)# Layer 2: context collapse (fold long text, zero API cost)diff --git a/agent/tests/test_loop_helpers.py b/agent/tests/test_loop_helpers.pyindex b3e1db506..2083f18bc 100644--- a/agent/tests/test_loop_helpers.py+++ b/agent/tests/test_loop_helpers.py@@ -24,10 +24,12 @@ from src.agent.loop import ()-def _apply_microcompact_gate(messages: list) -> None:+def _apply_microcompact_gate(messages: list, called_ok: set | None = None) -> None:"""Mirror AgentLoop layer-1 gate (``loop.py`` ~572-573)."""if estimate_tokens(messages) > MICROCOMPACT_THRESHOLD:- _microcompact(messages)+ unreadable = _microcompact(messages)+ if called_ok is not None:+ called_ok.difference_update(unreadable)# ---------------------------------------------------------------------------@@ -147,6 +149,72 @@ class TestMicrocompactThresholdGate:assert len(preserved) == KEEP_RECENT+class TestMicrocompactDedupLedger:+ """#1343: a cleared result cannot back "use the previous result", so the+ tools it came from must leave the dedup ledger and become callable again."""++ @staticmethod+ def _tool(name: str, content: str) -> dict:+ return {"role": "tool", "name": name, "content": content, "tool_call_id": f"tc_{name}_{len(content)}"}++ def test_cleared_tool_is_returned_for_unblocking(self) -> None:+ messages = [+ self._tool("get_fund_flow", "x" * 200),+ self._tool("get_stock_news", "y" * 200),+ self._tool("recent_a", "a" * 200),+ self._tool("recent_b", "b" * 200),+ self._tool("recent_c", "c" * 200),+ ]+ assert _microcompact(messages) == ["get_fund_flow", "get_stock_news"]++ def test_tool_with_surviving_result_stays_blocked(self) -> None:+ # Same name has an old cleared result AND a result inside KEEP_RECENT:+ # the model can still read one, so the dedup block must stay.+ messages = [+ self._tool("get_fund_flow", "x" * 200),+ self._tool("other", "y" * 200),+ self._tool("get_fund_flow", "fresh" + "z" * 200),+ self._tool("recent_b", "b" * 200),+ self._tool("recent_c", "c" * 200),+ ]+ assert _microcompact(messages) == ["other"]++ def test_short_old_result_still_counts_as_readable(self) -> None:+ messages = [+ self._tool("get_fund_flow", "x" * 200),+ self._tool("get_fund_flow", "ok"),+ self._tool("recent_a", "a" * 200),+ self._tool("recent_b", "b" * 200),+ self._tool("recent_c", "c" * 200),+ ]+ assert _microcompact(messages) == []++ def test_unnamed_messages_clear_without_unblocking(self) -> None:+ messages = [{"role": "tool", "content": "x" * 200, "tool_call_id": f"tc_{i}"} for i in range(KEEP_RECENT + 2)]+ assert _microcompact(messages) == []++ def test_second_pass_reports_nothing_new(self) -> None:+ messages = [+ self._tool("get_fund_flow", "x" * 200),+ self._tool("recent_a", "a" * 200),+ self._tool("recent_b", "b" * 200),+ self._tool("recent_c", "c" * 200),+ ]+ assert _microcompact(messages) == ["get_fund_flow"]+ assert _microcompact(messages) == []++ def test_gate_updates_dedup_ledger(self) -> None:+ messages = [{"role": "system", "content": "sys"}]+ messages.append({"role": "user", "content": "x" * (MICROCOMPACT_THRESHOLD * 4 + 1000)})+ messages.append(self._tool("get_fund_flow", "y" * 200))+ for name in ("recent_a", "recent_b", "recent_c"):+ messages.append(self._tool(name, "z" * 200))++ called_ok = {"get_fund_flow", "recent_a"}+ _apply_microcompact_gate(messages, called_ok)+ assert called_ok == {"recent_a"}++# ---------------------------------------------------------------------------# _context_collapse# ---------------------------------------------------------------------------