Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix: resolve report.md into worker summary and sanitize event payloads

Peng Qianca26b0660a67
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index c81536981..80de1e87b 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -299,6 +299,7 @@ def run_worker(
elapsed = time.monotonic() - t0
if elapsed > timeout:
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)
@@ -315,6 +316,7 @@ def run_worker(
token_estimate = len(json.dumps(messages, ensure_ascii=False)) // 4
if token_estimate > _MAX_TOKEN_ESTIMATE:
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)
return WorkerResult(
@@ -363,7 +365,7 @@ def run_worker(
_emit(event_callback, "worker_failed", agent_id, task_id, {"error": error_msg})
return WorkerResult(
status="failed",
- summary=last_assistant_content or "",
+ summary=_resolve_summary(artifact_dir, last_assistant_content or ""),
artifact_paths=_collect_artifacts(artifact_dir),
iterations=iteration,
error=error_msg,
@@ -383,6 +385,7 @@ def run_worker(
# If no tool calls, this is the final response
if not response.has_tool_calls:
summary = response.content or last_assistant_content or "(no summary)"
+ summary = _resolve_summary(artifact_dir, summary)
_emit(event_callback, "worker_completed", agent_id, task_id, {"iterations": iteration + 1})
_write_summary(artifact_dir, summary)
return WorkerResult(
@@ -408,7 +411,7 @@ def run_worker(
_emit(
event_callback, "tool_call", agent_id, task_id,
{"tool": tc.name, "iteration": iteration,
- "arguments": {k: v for k, v in tc.arguments.items() if k != "run_dir"}},
+ "arguments": {k: (v if len(str(v)) <= 200 else str(v)[:200] + "...") for k, v in tc.arguments.items() if k != "run_dir"}},
)
tc_start = time.monotonic()
args = {**tc.arguments, "run_dir": str(artifact_dir)}
@@ -418,7 +421,7 @@ def run_worker(
event_callback, "tool_result", agent_id, task_id,
{"tool": tc.name, "elapsed_ms": int(tc_elapsed * 1000),
"status": "ok", "iteration": iteration,
- "result": str(result)[:5000]},
+ "result_preview": str(result)[:500]},
)
messages.append(
ContextBuilder.format_tool_result(tc.id, tc.name, result[:10_000])
@@ -426,6 +429,7 @@ def run_worker(
# 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)
_emit(event_callback, "worker_iteration_limit", agent_id, task_id)
_write_summary(artifact_dir, summary)
_persist_messages(artifact_dir, messages)
@@ -451,6 +455,19 @@ def _best_summary(messages: list[dict], fallback: str) -> str:
return fallback
+def _resolve_summary(artifact_dir: Path, fallback: str) -> str:
+ """Return report.md content if it exists, otherwise fall back to text."""
+ report_path = artifact_dir / "report.md"
+ try:
+ if report_path.is_file():
+ content = report_path.read_text(encoding="utf-8").strip()
+ if content:
+ return content
+ except Exception:
+ logger.warning("Failed to read report.md from %s", artifact_dir, exc_info=True)
+ return fallback
+
+
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_report.py b/agent/tests/test_swarm_worker_report.py
new file mode 100644
index 000000000..2f30796d8
--- /dev/null
+++ b/agent/tests/test_swarm_worker_report.py
@@ -0,0 +1,56 @@
+"""Tests for swarm worker report.md → summary handoff."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from unittest.mock import MagicMock
+
+from src.swarm.worker import _resolve_summary, _best_summary, WorkerResult
+
+
+def test_resolve_summary_reads_report_md(tmp_path: Path) -> None:
+ """When report.md exists in artifact dir, _resolve_summary returns its content."""
+ report_content = "# Analysis Report\n\nKey finding: bullish."
+ (tmp_path / "report.md").write_text(report_content, encoding="utf-8")
+
+ result = _resolve_summary(tmp_path, "short fallback")
+ assert result == report_content
+
+
+def test_resolve_summary_falls_back_when_no_report(tmp_path: Path) -> None:
+ """When report.md does not exist, _resolve_summary returns the fallback."""
+ result = _resolve_summary(tmp_path, "short fallback")
+ assert result == "short fallback"
+
+
+def test_resolve_summary_falls_back_when_empty_report(tmp_path: Path) -> None:
+ """When report.md is empty/whitespace, _resolve_summary returns the fallback."""
+ (tmp_path / "report.md").write_text(" \n\n ", encoding="utf-8")
+
+ result = _resolve_summary(tmp_path, "short fallback")
+ assert result == "short fallback"
+
+
+def test_best_summary_picks_longest_assistant_text() -> None:
+ """_best_summary returns the longest assistant message over 100 chars."""
+ messages = [
+ {"role": "assistant", "content": "Short text"},
+ {"role": "assistant", "content": "A" * 200},
+ {"role": "assistant", "content": "B" * 300},
+ ]
+ result = _best_summary(messages, "fallback")
+ assert result == "B" * 300
+
+
+def test_best_summary_falls_back() -> None:
+ """_best_summary returns fallback when no assistant messages qualify."""
+ messages = [{"role": "user", "content": "hello"}]
+ result = _best_summary(messages, "fallback")
+ assert result == "fallback"
+
+
+def test_resolve_summary_handles_read_error(tmp_path: Path) -> None:
+ """_resolve_summary returns fallback if reading report.md fails."""
+ result = _resolve_summary(Path("/nonexistent/path/xyz"), "fallback")
+ assert result == "fallback"