"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(agent): stop repeated discovery without new evidence
eunwoo song7b356266789f
diff --git a/README.md b/README.mdindex 64e8622c3..b66b09c69 100644--- a/README.md+++ b/README.md@@ -406,6 +406,15 @@ Their credentials go to the OS keyring (macOS Keychain, Windows Credential ManagMost runs follow the same evidence path: route the request, load the right market context, execute tools, validate outputs, and keep the artifacts inspectable.+The agent stops with a visible recovery request after eight consecutive tool-call+iterations without a new successful observation. Repeating the same read result+or a failed call does not reset this budget. Identical failed calls are skipped+until a successful state-changing tool executes or a new run starts; changed+arguments can still execute. The recovery asks for an artifact path or permission+to rerun the missing research step, and the run remains failed even if older+metrics exist. This guard is separate from the wall-clock activity watchdog.++| Layer | What happens ||-------|--------------|| **Plan** | Selects the relevant finance skills, tools, data sources, and swarm preset when useful. |diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 29a9187d6..3c973cfeb 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -31,6 +31,7 @@ from src.agent.context import ContextBuilderfrom src.agent.grounding import GroundingLedgerfrom src.agent.memory import WorkspaceMemoryfrom src.agent.progress import HeartbeatTimer, ProgressEvent, _set_emitter+from src.agent.tool_progress import RECOVERY_MESSAGE, ToolProgressfrom src.agent.tools import ToolRegistryfrom src.agent.trace import TraceWriterfrom src.core.state import RunStateStore@@ -840,8 +841,6 @@ def _looks_like_tool_call_syntax(content: str) -> bool:)--# Task target-file detection: a user message usually names the file to# create or update ("update C:\\...\\plan.md"). If a run approaches its# iteration cap without having written that file, the loop must remind the@@ -1093,6 +1092,7 @@ class AgentLoop:# 5-9x each (2026-08-20 INTC run) because it could no longer see its# own verification records.self._called_identical: dict[tuple[str, str], str] = {}+ self._tool_progress = ToolProgress()def cancel(self) -> None:"""Cancel the current loop.@@ -1187,6 +1187,7 @@ class AgentLoop:self._last_activity_wall = _time.time()self._run_done = threading.Event()self._called_identical = {}+ self._tool_progress = ToolProgress()run_started_wall = _time.time()state_store = RunStateStore()@@ -1246,6 +1247,7 @@ class AgentLoop:iteration = 0final_content = ""+ no_progress_reason: str | None = Nonecontent_filter_count = 0consecutive_content_filter_count = 0content_filter_circuit_breaker = False@@ -1816,6 +1818,31 @@ class AgentLoop:response.tool_calls, context, messages, trace, react_trace, current_iter,)+ if (+ not self._cancel_event.is_set()+ and self._tool_progress.finish_iteration()+ ):+ no_progress_reason = "no_progress: " + RECOVERY_MESSAGE+ final_content = RECOVERY_MESSAGE+ trace.write(+ {+ "type": "no_progress",+ "iter": current_iter,+ "iterations_without_progress": self._tool_progress.stalled_iterations,+ }+ )+ trace.write_text_entry(+ {"type": "answer", "iter": current_iter},+ field="content",+ value=final_content,+ offload_kind=f"answer-{current_iter}",+ )+ react_trace.append({"type": "answer", "content": final_content})+ self._emit(+ "text_delta", {"delta": final_content, "iter": current_iter}+ )+ break+# Layer 3: compress after all tools have executedif compact_requested:logger.info("Manual compact triggered by model")@@ -1857,6 +1884,10 @@ class AgentLoop:final_reason = "cancelled by user"state_store.mark_cancelled(run_dir, final_reason)final_status = "cancelled"+ elif no_progress_reason is not None:+ final_reason = no_progress_reason+ state_store.mark_failure(run_dir, final_reason)+ final_status = "failed"elif content_filter_circuit_breaker:final_reason = (f"content_filter_circuit_breaker: "@@ -2076,6 +2107,24 @@ class AgentLoop:# un-serialisable call would collapse into a single identity and# the second one would be skipped without ever running.dedup_key = self._identical_call_key(tc.name, tc.arguments)+ if dedup_key is not None and dedup_key in self._tool_progress.failed:+ failed_result = json.dumps(+ {+ "status": "error",+ "skipped": True,+ "reason": "This exact call already failed in this run. Change strategy or ask the user for help.",+ }+ )+ self._record_blocked_tool_call(+ tc,+ failed_result,+ context,+ messages,+ trace,+ react_trace,+ iteration,+ )+ continueif (dedup_key is not Noneand dedup_key in self._called_ok@@ -2200,7 +2249,7 @@ class AgentLoop:react_trace: list,iteration: int,) -> None:- """Record an identity-gated call without invoking its implementation.+ """Record a blocked call without invoking its implementation.Args:tc: Provider tool-call object.@@ -2730,6 +2779,14 @@ class AgentLoop:self._last_activity_wall = _time.time()success = _is_tool_success(result)+ if update_memory:+ self._tool_progress.record(+ tc.name,+ self._identical_call_key(tc.name, tc.arguments),+ result,+ success=success,+ is_readonly=self._is_tool_readonly(tc.name),+ )if success:recorded_key = self._identical_call_key(tc.name, tc.arguments)if recorded_key is not None:diff --git a/agent/src/agent/tool_progress.py b/agent/src/agent/tool_progress.pynew file mode 100644index 000000000..f20b4e9ca--- /dev/null+++ b/agent/src/agent/tool_progress.py@@ -0,0 +1,63 @@+"""Per-run tool observations, independent of the activity watchdog."""++from __future__ import annotations++import hashlib+import json++NO_PROGRESS_LIMIT = 8+RECOVERY_MESSAGE = (+ "I stopped because repeated tool attempts did not produce new information. "+ "I cannot reliably answer from the previous summary alone. Please provide "+ "the artifact path or confirm that you want to rerun the missing research step."+)+++class ToolProgress:+ """Bound repeated discovery without treating activity as new evidence."""++ def __init__(self) -> None:+ self.failed: set[tuple[str, str]] = set()+ self._observations: set[tuple[str, str | None, str]] = set()+ self._new_observation = False+ self.stalled_iterations = 0++ def record(+ self,+ name: str,+ key: tuple[str, str] | None,+ result: str,+ *,+ success: bool,+ is_readonly: bool = True,+ ) -> None:+ """Record an executed call; synthetic skips must not enter this ledger."""+ if not success:+ if key is not None:+ self.failed.add(key)+ return+ if not is_readonly:+ self.failed.clear()+ if not is_readonly and key is None:+ self._new_observation = True+ return+ try:+ result = json.dumps(json.loads(result), sort_keys=True, ensure_ascii=False)+ except (ValueError, TypeError):+ pass+ observation = (+ name,+ None if is_readonly else key[1],+ hashlib.sha256(result.encode("utf-8")).hexdigest(),+ )+ if observation not in self._observations:+ self._observations.add(observation)+ self._new_observation = True++ def finish_iteration(self) -> bool:+ """Return whether the run exhausted its consecutive no-progress budget."""+ self.stalled_iterations = (+ 0 if self._new_observation else self.stalled_iterations + 1+ )+ self._new_observation = False+ return self.stalled_iterations >= NO_PROGRESS_LIMITdiff --git a/agent/tests/test_agent_loop_deterministic_cache.py b/agent/tests/test_agent_loop_deterministic_cache.pyindex 9f22b9fd9..6abd2b9f0 100644--- a/agent/tests/test_agent_loop_deterministic_cache.py+++ b/agent/tests/test_agent_loop_deterministic_cache.py@@ -167,16 +167,20 @@ def test_non_deterministic_tool_is_never_cached(agent_factory) -> None:def test_failed_deterministic_call_is_not_cached(agent_factory) -> None:- """A failure must be retryable, not frozen in for the rest of the run."""+ """Failures are skipped by the retry guard, never served as cached success."""tool = _CountingTool(deterministic=True, status="error")agent, run_dir, _ = agent_factory(tool)messages, records = _drive(- agent, tool.name, run_dir, [{"a": 1}, {"a": 1}],+ agent,+ tool.name,+ run_dir,+ [{"a": 1}, {"a": 1}, {"a": 2}],)- assert len(tool.calls) == 2- assert len(messages) == 2+ assert len(tool.calls) == 2 # Changed arguments still execute.+ assert len(messages) == 3+ assert json.loads(messages[1]["content"])["skipped"] is Trueassert not any(r["type"] == "tool_result_cached" for r in records)diff --git a/agent/tests/test_agent_loop_no_progress.py b/agent/tests/test_agent_loop_no_progress.pynew file mode 100644index 000000000..7e1d9f7e6--- /dev/null+++ b/agent/tests/test_agent_loop_no_progress.py@@ -0,0 +1,196 @@+"""A busy discovery loop must stop visibly when it cannot gain information."""++from __future__ import annotations++import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from src.agent.loop import AgentLoop+from src.agent.tools import BaseTool, ToolRegistry+from src.agent.trace import TraceWriter+++class DiscoveryTool(BaseTool):+ name = "read_document"+ description = "Read an artifact (offline test double)."+ parameters = {"type": "object", "properties": {"path": {"type": "string"}}}+ is_readonly = True+ repeatable = True++ def __init__(self, results: list[str]) -> None:+ self.results = results+ self.calls = 0++ def execute(self, **kwargs: object) -> str:+ self.calls += 1+ return self.results[min(self.calls - 1, len(self.results) - 1)]+++class DiscoveryLLM:+ model_name = "offline"++ def __init__(self, *, vary_arguments: bool = False, finish_after: int = 50) -> None:+ self.calls = 0+ self.vary_arguments = vary_arguments+ self.finish_after = finish_after++ def stream_chat(self, messages: list[dict], **kwargs: object) -> SimpleNamespace:+ self.calls += 1+ done = self.calls > self.finish_after+ return SimpleNamespace(+ content="Found the artifact." if done else "",+ reasoning_content=None,+ has_tool_calls=not done,+ tool_calls=(+ []+ if done+ else [+ SimpleNamespace(+ id=f"read-{self.calls}",+ name="read_document",+ arguments={+ "path": (+ f"guess-{self.calls}"+ if self.vary_arguments+ else "missing.csv"+ )+ },+ )+ ]+ ),+ )+++def build_loop(tmp_path: Path, tool: DiscoveryTool, llm: DiscoveryLLM):+ registry = ToolRegistry()+ registry.register(tool)+ events = []+ loop = AgentLoop(+ registry=registry,+ llm=llm,+ max_iterations=24,+ event_callback=lambda name, data: events.append((name, data)),+ )+ run_dir = tmp_path / "run"+ run_dir.mkdir()+ loop.memory.run_dir = str(run_dir)+ return loop, events, run_dir++[email protected]("vary_arguments", [False, True])+def test_failed_discovery_stops_with_visible_recovery(tmp_path, vary_arguments):+ tool = DiscoveryTool(['{"status":"error","message":"File not found"}'])+ loop, events, run_dir = build_loop(+ tmp_path, tool, DiscoveryLLM(vary_arguments=vary_arguments)+ )+ result = loop.run("Find the artifacts from my previous backtest.")++ assert result["status"] == "failed"+ assert result["iterations"] == 8+ assert tool.calls == (8 if vary_arguments else 1)+ assert "no_progress" in result["reason"]+ assert "path" in result["content"]+ assert "rerun" in result["content"]+ assert any(+ name == "text_delta" and data["delta"] == result["content"]+ for name, data in events+ )+ assert json.loads((run_dir / "state.json").read_text())["status"] == "failed"+ records = list(TraceWriter.read(run_dir))+ assert any(r["type"] == "no_progress" for r in records)+ assert records[-1]["type"] == "end" and records[-1]["status"] == "failed"++[email protected]("readonly", [True, False])+def test_new_observations_or_distinct_writes_keep_running(tmp_path, readonly):+ results = [json.dumps({"status": "ok", "value": i}) for i in range(12)]+ tool = DiscoveryTool(results if readonly else ['{"status":"ok"}'])+ tool.is_readonly = readonly+ loop, _, _ = build_loop(+ tmp_path, tool, DiscoveryLLM(vary_arguments=True, finish_after=12)+ )+ result = loop.run("Read each artifact.")+ assert result["status"] == "success"+ assert result["iterations"] == 13+ assert tool.calls == 12+++def test_rephrased_reads_of_the_same_result_are_not_progress(tmp_path):+ tool = DiscoveryTool(['{"status":"ok","snippets":[]}'])+ loop, _, _ = build_loop(tmp_path, tool, DiscoveryLLM(vary_arguments=True))+ result = loop.run("Find the prior artifact.")+ assert result["status"] == "failed"+ assert result["iterations"] == 9 # First result is new, subsequent ones are not.+ assert "no_progress" in result["reason"]+++def test_failed_call_ledger_resets_for_a_new_run(tmp_path):+ tool = DiscoveryTool(['{"status":"error"}'])+ loop, _, _ = build_loop(tmp_path, tool, DiscoveryLLM())+ first = loop.run("Read the artifact.")+ second = loop.run("Try again after I repaired the artifact.")+ assert first["iterations"] == second["iterations"] == 8+ assert tool.calls == 2+++def test_old_metrics_do_not_turn_no_progress_into_success(tmp_path):+ tool = DiscoveryTool(['{"status":"error"}'])+ loop, _, run_dir = build_loop(tmp_path, tool, DiscoveryLLM())+ (run_dir / "artifacts").mkdir()+ (run_dir / "artifacts" / "metrics.csv").write_text("return\n0.1\n")+ result = loop.run("Explain this previous run using its original trades.")+ assert result["status"] == "failed"+ assert "no_progress" in result["reason"]+++def test_successful_repair_allows_a_previously_failed_read(tmp_path):+ from src.agent.context import ContextBuilder++ tool = DiscoveryTool(['{"status":"error"}', '{"status":"ok","data":"repaired"}'])+ loop, _, run_dir = build_loop(tmp_path, tool, DiscoveryLLM())+ repair = DiscoveryTool(['{"status":"ok"}'])+ repair.name = "repair_file"+ repair.is_readonly = False+ loop.registry.register(repair)+ trace = TraceWriter(run_dir)+ messages = []+ for i, name in enumerate([tool.name, repair.name, tool.name]):+ loop._process_tool_calls(+ [SimpleNamespace(id=str(i), name=name, arguments={"path": "missing.csv"})],+ ContextBuilder,+ messages,+ trace,+ [],+ i,+ )+ trace.close()+ assert tool.calls == 2+ assert json.loads(messages[-1]["content"])["data"] == "repaired"+++def test_authorization_denial_does_not_poison_an_unexecuted_call(tmp_path):+ from src.agent.context import ContextBuilder++ tool = DiscoveryTool(['{"status":"ok"}'])+ loop, _, run_dir = build_loop(tmp_path, tool, DiscoveryLLM())+ trace = TraceWriter(run_dir)+ messages = []+ call = SimpleNamespace(+ id="denied", name=tool.name, arguments={"path": "artifact.csv"}+ )+ loop._record_blocked_tool_call(+ call,+ '{"status":"error","reason":"identity not yet resolved"}',+ ContextBuilder,+ messages,+ trace,+ [],+ 1,+ )+ call = SimpleNamespace(id="authorized", name=tool.name, arguments=call.arguments)+ loop._process_tool_calls([call], ContextBuilder, messages, trace, [], 2)+ trace.close()+ assert tool.calls == 1