Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(swarm): persist a worker's message log wherever its summary is written

cgycorey2c1cf120b157
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index 16716116c..3ab7422f9 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -651,8 +651,7 @@ def _run_worker_impl(
summary = _best_summary(messages, last_assistant_content) or f"Worker timed out after {elapsed:.0f}s ({iteration} iterations)"
summary = _resolve_summary(artifact_dir, summary)
_emit(event_callback, "worker_timeout", agent_id, task_id, {"elapsed": elapsed})
- _write_summary(artifact_dir, summary)
- _persist_messages(artifact_dir, messages)
+ _finalize_run(artifact_dir, summary, messages)
return WorkerResult(
status="timeout",
summary=summary,
@@ -671,8 +670,7 @@ def _run_worker_impl(
cancelled_summary = last_assistant_content or f"Cancelled after {iteration} iterations"
summary = _resolve_summary(artifact_dir, cancelled_summary)
_emit(event_callback, "worker_cancelled", agent_id, task_id, {"iterations": iteration})
- _write_summary(artifact_dir, summary)
- _persist_messages(artifact_dir, messages)
+ _finalize_run(artifact_dir, summary, messages)
return WorkerResult(
status="cancelled",
summary=summary,
@@ -691,7 +689,7 @@ def _run_worker_impl(
summary = last_assistant_content or f"Worker context too large (~{token_estimate} tokens, {iteration} iterations)"
summary = _resolve_summary(artifact_dir, summary)
_emit(event_callback, "worker_token_limit", agent_id, task_id, {"tokens": token_estimate})
- _write_summary(artifact_dir, summary)
+ _finalize_run(artifact_dir, summary, messages)
return WorkerResult(
status="token_limit",
summary=summary,
@@ -837,8 +835,7 @@ def _run_worker_impl(
cancelled_summary = last_assistant_content or f"Cancelled after {iteration} iterations"
summary = _resolve_summary(artifact_dir, cancelled_summary)
_emit(event_callback, "worker_cancelled", agent_id, task_id, {"iterations": iteration})
- _write_summary(artifact_dir, summary)
- _persist_messages(artifact_dir, messages)
+ _finalize_run(artifact_dir, summary, messages)
return WorkerResult(
status="cancelled",
summary=summary,
@@ -890,7 +887,7 @@ def _run_worker_impl(
{"count": content_filter_count},
)
summary = _resolve_summary(artifact_dir, last_assistant_content or "")
- _write_summary(artifact_dir, summary)
+ _finalize_run(artifact_dir, summary, messages)
return WorkerResult(
status="failed",
summary=summary,
@@ -926,7 +923,7 @@ def _run_worker_impl(
if not response.has_tool_calls:
summary = response.content or last_assistant_content or "(no summary)"
summary = _resolve_summary(artifact_dir, summary)
- _write_summary(artifact_dir, summary)
+ _finalize_run(artifact_dir, summary, messages)
reason = _classify_deliverable(
summary,
is_data_agent=_is_data_agent(agent_spec),
@@ -1043,8 +1040,7 @@ def _run_worker_impl(
# Hit iteration limit — use last meaningful content as summary
summary = _best_summary(messages, last_assistant_content) or f"Worker hit iteration limit ({max_iterations} iterations)"
summary = _resolve_summary(artifact_dir, summary)
- _write_summary(artifact_dir, summary)
- _persist_messages(artifact_dir, messages)
+ _finalize_run(artifact_dir, summary, messages)
reason = _classify_deliverable(
summary,
is_data_agent=_is_data_agent(agent_spec),
@@ -1313,6 +1309,24 @@ def _resolve_summary(artifact_dir: Path, fallback: str) -> str:
return fallback
+def _finalize_run(artifact_dir: Path, summary: str, messages: list[dict]) -> None:
+ """Persist a worker's terminal summary and message log together.
+
+ Both files are written through one call, so a terminal path that reports a
+ summary cannot omit the message log: ``messages.json`` is the only record
+ of the arguments a model asked a tool for, which is what a post-mortem of a
+ bad tool call needs. The LLM-call-failure handler writes neither file and is
+ unchanged.
+
+ Args:
+ artifact_dir: Path to artifacts/{agent_id}/ directory.
+ summary: Final summary text for this worker run.
+ messages: Message history, including tool call arguments.
+ """
+ _write_summary(artifact_dir, summary)
+ _persist_messages(artifact_dir, messages)
+
+
def _persist_messages(artifact_dir: Path, messages: list[dict]) -> None:
"""Persist messages to disk for post-mortem analysis."""
try:
diff --git a/agent/tests/test_swarm_worker_message_log.py b/agent/tests/test_swarm_worker_message_log.py
new file mode 100644
index 000000000..a08c42b22
--- /dev/null
+++ b/agent/tests/test_swarm_worker_message_log.py
@@ -0,0 +1,173 @@
+"""A worker's terminal summary and message log are persisted together.
+
+``messages.json`` is the only record of the arguments a model asked a tool
+for: the assistant message carries ``function.arguments`` verbatim, while the
+event stream redacts ``run_dir`` from the argument preview. A terminal path
+that reports a summary must also write the log, so a completed run, a token
+limit and a content-filter trip all leave the same two files.
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Callable
+from pathlib import Path
+
+import pytest
+
+import src.swarm.worker as worker_mod
+from src.agent.tools import BaseTool, ToolRegistry
+from src.providers.chat import LLMResponse, ToolCallRequest
+from src.swarm.models import SwarmAgentSpec, SwarmTask
+from src.swarm.worker import agent_artifact_dir, run_worker
+
+
+class _ProbeTool(BaseTool):
+ """Return one canned result so the worker reaches a terminal state."""
+
+ name = "market_probe"
+ description = "Return a canned market result."
+ parameters = {"type": "object", "properties": {}}
+
+ def execute(self, **kwargs) -> str:
+ return '{"status": "ok", "data": [1]}'
+
+
+class _ScriptedLLM:
+ """One tool call carrying arguments, then a final answer with no tools."""
+
+ def __init__(self) -> None:
+ self._responses = [
+ LLMResponse(
+ content=None,
+ tool_calls=[
+ ToolCallRequest(
+ id="call-1",
+ name="market_probe",
+ arguments={"symbol": "BTC-USDT", "window": 7},
+ )
+ ],
+ finish_reason="tool_calls",
+ ),
+ LLMResponse(
+ content="Completed the requested market analysis with a clear conclusion.",
+ tool_calls=[],
+ finish_reason="stop",
+ ),
+ ]
+
+ def stream_chat(self, messages, tools=None, timeout=None, on_text_chunk=None):
+ return self._responses.pop(0)
+
+ def close(self) -> None:
+ """No-op: the scripted stub owns no HTTP client."""
+
+
+class _ContentFilteredLLM:
+ """Every response is blocked, so the worker trips its circuit breaker."""
+
+ def __init__(self) -> None:
+ self._remaining = 20
+
+ def stream_chat(self, messages, tools=None, timeout=None, on_text_chunk=None):
+ self._remaining -= 1
+ if self._remaining >= 0:
+ return LLMResponse(content="", content_filter_triggered=True)
+ return LLMResponse(content="unreachable", tool_calls=[])
+
+ def close(self) -> None:
+ """No-op: the scripted stub owns no HTTP client."""
+
+
+def _run_worker_to_terminal(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ llm_factory: Callable[[], object] | None = None,
+ max_iterations: int = 3,
+):
+ """Run the real worker on a scripted model until it stops."""
+ monkeypatch.setattr(worker_mod, "_STREAM_RETRY_DELAY_S", 0.0)
+ registry = ToolRegistry()
+ registry.register(_ProbeTool())
+ monkeypatch.setattr(
+ worker_mod, "build_swarm_registry", lambda *args, **kwargs: registry
+ )
+ monkeypatch.setattr(
+ worker_mod, "ChatLLM", lambda *args, **kwargs: (llm_factory or _ScriptedLLM)()
+ )
+ return run_worker(
+ agent_spec=SwarmAgentSpec(
+ id="analyst",
+ role="Analyst",
+ system_prompt="Analyse the result.",
+ tools=["market_probe"],
+ max_iterations=max_iterations,
+ ),
+ task=SwarmTask(
+ id="task", agent_id="analyst", prompt_template="Probe the market."
+ ),
+ upstream_summaries={},
+ user_vars={},
+ run_dir=tmp_path,
+ event_callback=lambda event: None,
+ )
+
+
+def test_completed_run_persists_the_message_log(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A worker that completes must leave a message log, not only a summary."""
+ result = _run_worker_to_terminal(tmp_path, monkeypatch)
+ artifact_dir = agent_artifact_dir(tmp_path, "analyst")
+
+ assert result.status == "completed", result.error
+ assert (artifact_dir / "summary.md").is_file()
+ assert (artifact_dir / "messages.json").is_file()
+
+
+def test_token_limit_run_persists_the_message_log(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A worker stopped by the token limit must leave a message log too."""
+ monkeypatch.setattr(worker_mod, "_MAX_TOKEN_ESTIMATE", 0)
+ result = _run_worker_to_terminal(tmp_path, monkeypatch)
+ artifact_dir = agent_artifact_dir(tmp_path, "analyst")
+
+ assert result.status == "token_limit"
+ assert (artifact_dir / "summary.md").is_file()
+ assert (artifact_dir / "messages.json").is_file()
+
+
+def test_content_filter_circuit_breaker_persists_the_message_log(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A worker failed by the content-filter breaker must leave a log too."""
+ result = _run_worker_to_terminal(
+ tmp_path,
+ monkeypatch,
+ llm_factory=_ContentFilteredLLM,
+ max_iterations=20,
+ )
+ artifact_dir = agent_artifact_dir(tmp_path, "analyst")
+
+ assert result.status == "failed"
+ assert "circuit_breaker" in (result.error or "")
+ assert (artifact_dir / "summary.md").is_file()
+ assert (artifact_dir / "messages.json").is_file()
+
+
+def test_message_log_carries_the_tool_call_arguments(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The log must hold what the model asked the tool for, not only roles."""
+ _run_worker_to_terminal(tmp_path, monkeypatch)
+ log_path = agent_artifact_dir(tmp_path, "analyst") / "messages.json"
+ messages = json.loads(log_path.read_text(encoding="utf-8"))
+
+ assert any(
+ '"symbol": "BTC-USDT"' in call["function"]["arguments"]
+ for message in messages
+ if message.get("role") == "assistant"
+ for call in message.get("tool_calls", [])
+ )