"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(agent): complete trace.jsonl — zero truncation, message entries, tool result offload
zwrongc4dec47576ca
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex 5d9524fd4..247e65cb1 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -1392,9 +1392,17 @@ def cmd_run(prompt: str, max_iter: int, *, json_mode: bool = False, no_rich: boodef _build_history_from_trace(run_dir: Path) -> List[Dict[str, str]]:- """Build conversation history from trace.jsonl."""+ """Build conversation history from trace.jsonl.++ Checks sessions/<run_id>/ first (new location), then falls back to+ runs/<run_id>/ (legacy location).+ """from src.agent.trace import TraceWriter- entries = TraceWriter.read(run_dir)++ trace_dir = TraceWriter.find_trace_dir(run_dir.name, runs_dir=RUNS_DIR, sessions_dir=SESSIONS_DIR)+ if trace_dir is None or not (trace_dir / "trace.jsonl").exists():+ return []+ entries = TraceWriter.read(trace_dir)history: List[Dict[str, str]] = []for e in entries:if e.get("type") == "start" and e.get("prompt"):@@ -1414,13 +1422,18 @@ def cmd_continue() -> int:"""Continue an existing run."""run_dir = RUNS_DIR / run_id- if not run_dir.exists():+ session_trace_dir = SESSIONS_DIR / run_id+ if not run_dir.exists() and not session_trace_dir.exists():if no_rich:print(f"Run {run_id} not found")return EXIT_USAGE_ERRORconsole.print(f"[red]Run {run_id} not found[/red]")return EXIT_USAGE_ERROR+ # Ensure run_dir exists (for artifact storage) even if trace is in sessions/+ if not run_dir.exists():+ run_dir.mkdir(parents=True, exist_ok=True)+history = _build_history_from_trace(run_dir)if not json_mode and no_rich:print(f"Continue {run_id}: {prompt[:120]}\n")@@ -2222,7 +2235,8 @@ def cmd_show(run_id: str) -> None:lines.extend(f" {k}: {v}" for k, v in metrics.items())from src.agent.trace import TraceWriter- entries = TraceWriter.read(run_dir)+ trace_dir = TraceWriter.find_trace_dir(run_id, runs_dir=RUNS_DIR, sessions_dir=SESSIONS_DIR)+ entries = TraceWriter.read(trace_dir) if trace_dir else []answers = [e["content"] for e in entries if e.get("type") == "answer" and e.get("content")]if answers:summary = answers[-1][:200]@@ -2281,12 +2295,12 @@ def cmd_trace(run_id: str) -> None:"""Replay trace.jsonl to show full execution."""from src.agent.trace import TraceWriter- run_dir = RUNS_DIR / run_id- if not run_dir.exists():- console.print(f"[red]{run_id} not found[/red]")+ trace_dir = TraceWriter.find_trace_dir(run_id, runs_dir=RUNS_DIR, sessions_dir=SESSIONS_DIR)+ if trace_dir is None or not (trace_dir / "trace.jsonl").exists():+ console.print(f"[red]{run_id}/trace.jsonl not found[/red]")return- entries = TraceWriter.read(run_dir)+ entries = TraceWriter.read(trace_dir)if not entries:console.print(f"[red]{run_id}/trace.jsonl is empty or missing[/red]")return@@ -2317,13 +2331,21 @@ def cmd_trace(run_id: str) -> None:ok = status == "ok"mark = "\u2713" if ok else "\u2717"color = "green" if ok else "red"- preview = entry.get("preview", "")[:80]- console.print(f"[dim]{ts_str}[/dim] {iter_tag}[{color}]{mark} {tool}[/{color}] [dim]{elapsed}ms[/dim] {preview}")+ # New format: result (inline) or result_preview (offloaded)+ preview = (entry.get("result_preview") or entry.get("result") or "")[:80]+ offloaded = "result_path" in entry+ size_hint = f" [{entry.get('result_size', 0)//1024}K offloaded]" if offloaded else ""+ console.print(f"[dim]{ts_str}[/dim] {iter_tag}[{color}]{mark} {tool}[/{color}] [dim]{elapsed}ms[/dim] {preview}{size_hint}")elif etype == "tool_skipped":console.print(f"[dim]{ts_str}[/dim] {iter_tag}[yellow]\u2298 {entry.get('tool', '')} (skipped)[/yellow]")+ elif etype == "message":+ role = entry.get("role", "?")+ content = entry.get("content", "")+ role_color = "cyan" if role == "user" else "green"+ console.print(f"\n[dim]{ts_str}[/dim] {iter_tag}[bold {role_color}]{role.upper()}[/bold {role_color}] {content[:120]}")elif etype == "answer":content = entry.get("content", "")- console.print(f"\n[dim]{ts_str}[/dim] {iter_tag}[bold green]ANSWER[/bold green]\n{content[:500]}")+ console.print(f"\n[dim]{ts_str}[/dim] {iter_tag}[bold green]ANSWER[/bold green]\n{content}")elif etype == "end":status = entry.get("status", "?")iters = entry.get("iterations", "?")diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 9795b6697..4e4a23d9c 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -37,6 +37,7 @@ from src.providers.chat import ChatLLMfrom src.tools.background_tools import get_background_managerRUNS_DIR = Path(__file__).resolve().parents[2] / "runs"+SESSIONS_DIR = Path(__file__).resolve().parents[2] / "sessions"TOKEN_THRESHOLD = int(os.getenv("TOKEN_THRESHOLD", "40000"))KEEP_RECENT = 3TOOL_RESULT_LIMIT = 10_000@@ -389,8 +390,15 @@ class AgentLoop:messages = context.build_messages(llm_user_message, history)react_trace: List[Dict[str, Any]] = []- trace = TraceWriter(run_dir)- trace.write({"type": "start", "prompt": user_message[:500]})+ # Trace location: sessions/<session_id>/ when session_id is valid,+ # otherwise falls back to runs/<run_dir>/ for one-off -p mode.+ if session_id:+ trace_dir = SESSIONS_DIR / session_id+ else:+ trace_dir = run_dir+ trace = TraceWriter(trace_dir)+ trace.write({"type": "start", "prompt": user_message})+ trace.write({"type": "message", "role": "user", "content": user_message})iteration = 0final_content = ""@@ -505,7 +513,7 @@ class AgentLoop:thinking_text = "".join(thinking_chunks)if thinking_text:- trace.write({"type": "thinking", "iter": iteration, "content": thinking_text[:2000]})+ trace.write({"type": "thinking", "iter": iteration, "content": thinking_text})self._emit("thinking_done", {"iter": iteration, "content": thinking_text[:500]})if not response.has_tool_calls:@@ -550,10 +558,11 @@ class AgentLoop:"type": "goal_intermediate_answer","iter": iteration,"goal_id": active_goal_id,- "content": final_content[:2000],+ "content": final_content,"progress": current_progress,})+ trace.write({"type": "message", "role": "assistant", "content": final_content})react_trace.append({"type": "goal_intermediate_answer", "content": final_content[:500]})@@ -571,7 +580,8 @@ class AgentLoop:goal_continuations += 1continue- trace.write({"type": "answer", "iter": iteration, "content": final_content[:2000]})+ trace.write({"type": "answer", "iter": iteration, "content": final_content})+ trace.write({"type": "message", "role": "assistant", "content": final_content})react_trace.append({"type": "answer", "content": final_content[:500]})break@@ -777,7 +787,7 @@ class AgentLoop:for tc in tool_calls:args = _normalize_tool_run_dir(tc.arguments, self.memory.run_dir)self._emit("tool_call", {"tool": tc.name, "arguments": {k: str(v)[:200] for k, v in args.items()}, "iter": iteration})- trace.write({"type": "tool_call", "iter": iteration, "tool": tc.name, "call_id": tc.id, "args": {k: str(v)[:200] for k, v in args.items()}})+ trace.write({"type": "tool_call", "iter": iteration, "tool": tc.name, "call_id": tc.id, "args": {k: str(v) for k, v in args.items()}})runnable.append((tc, args))# Execute in parallel — each worker gets its own heartbeat + progress emitter.@@ -822,7 +832,7 @@ class AgentLoop:args = _normalize_tool_run_dir(tc.arguments, self.memory.run_dir)self._emit("tool_call", {"tool": tc.name, "arguments": {k: str(v)[:200] for k, v in args.items()}, "iter": iteration})- trace.write({"type": "tool_call", "iter": iteration, "tool": tc.name, "call_id": tc.id, "args": {k: str(v)[:200] for k, v in args.items()}})+ trace.write({"type": "tool_call", "iter": iteration, "tool": tc.name, "call_id": tc.id, "args": {k: str(v) for k, v in args.items()}})logger.info(f"Tool call: {tc.name}({list(args.keys())})")result, elapsed_ms = self._invoke_tool(tc.name, args)@@ -901,7 +911,14 @@ class AgentLoop:truncated = result[:TOOL_RESULT_LIMIT]messages.append(context.format_tool_result(tc.id, tc.name, truncated))- trace.write({"type": "tool_result", "iter": iteration, "tool": tc.name, "call_id": tc.id, "status": status, "elapsed_ms": elapsed_ms, "preview": result[:200]})+ trace.write_tool_result(+ call_id=tc.id,+ result=result,+ tool_name=tc.name,+ status=status,+ elapsed_ms=elapsed_ms,+ iteration=iteration,+ )react_trace.append({"type": "tool_call", "tool": tc.name, "result_preview": result[:200]})self._emit("tool_result", {"tool": tc.name, "status": status, "elapsed_ms": elapsed_ms, "preview": result[:200]})@@ -924,8 +941,9 @@ class AgentLoop:trace: TraceWriter.focus_topic: Optional topic to prioritize in the summary."""- # Save full transcript before compressing- transcript_path = run_dir / f"transcript_{int(_time.time())}.jsonl"+ # Save full transcript before compressing (uses trace dir so session-based+ # runs store transcripts alongside trace.jsonl)+ transcript_path = trace.dir_path / f"transcript_{int(_time.time())}.jsonl"with open(transcript_path, "w", encoding="utf-8") as f:for msg in messages:f.write(json.dumps(msg, default=str, ensure_ascii=False) + "\n")@@ -982,7 +1000,7 @@ class AgentLoop:self._previous_summary = summarytokens_before = estimate_tokens(messages)- trace.write({"type": "compact", "tokens_before": tokens_before, "summary": summary[:500],+ trace.write({"type": "compact", "tokens_before": tokens_before, "summary": summary,"focus_topic": focus_topic or "(none)"})self._emit("compact", {"tokens_before": tokens_before, "summary": summary[:200]})diff --git a/agent/src/agent/trace.py b/agent/src/agent/trace.pyindex 5251d81fd..1f568ae78 100644--- a/agent/src/agent/trace.py+++ b/agent/src/agent/trace.py@@ -1,6 +1,7 @@"""TraceWriter: crash-safe JSONL trace writer.One JSON record per line; append + flush guarantees no data loss on crash.+Large tool results (>50K chars) are offloaded to separate files."""from __future__ import annotations@@ -8,23 +9,29 @@ from __future__ import annotationsimport jsonimport timefrom pathlib import Path-from typing import Any, Dict, List+from typing import Any, Dict, List, Optional++TOOL_RESULT_OFFLOAD_THRESHOLD = 50_000+OFFLOAD_PREVIEW_CHARS = 500class TraceWriter:"""JSONL trace writer, one record per line, crash-safe.Attributes:+ dir_path: Directory containing trace.jsonl and tool-results/.path: Path to the trace.jsonl file."""- def __init__(self, run_dir: Path) -> None:+ def __init__(self, dir_path: Path) -> None:"""Initialize TraceWriter.Args:- run_dir: Run directory; trace.jsonl is written here.+ dir_path: Directory where trace.jsonl (and tool-results/) are written."""- self.path = run_dir / "trace.jsonl"+ self.dir_path = dir_path+ dir_path.mkdir(parents=True, exist_ok=True)+ self.path = dir_path / "trace.jsonl"self._file = open(self.path, "a", encoding="utf-8")def write(self, entry: Dict[str, Any]) -> None:@@ -38,29 +45,130 @@ class TraceWriter:self._file.write(json.dumps(entry, ensure_ascii=False) + "\n")self._file.flush()+ def write_tool_result(+ self,+ call_id: str,+ result: str,+ tool_name: str,+ status: str,+ elapsed_ms: int,+ iteration: int,+ ) -> None:+ """Write a tool_result trace entry, offloading large results to disk.++ Results ≤ TOOL_RESULT_OFFLOAD_THRESHOLD are stored inline in the JSONL.+ Larger results are written to ``tool-results/<call_id>.txt`` and the+ trace entry carries a path + preview instead.++ Args:+ call_id: Tool call ID.+ result: Raw tool result string.+ tool_name: Tool name.+ status: "ok" or "error".+ elapsed_ms: Execution time in milliseconds.+ iteration: Current iteration number.+ """+ if len(result) > TOOL_RESULT_OFFLOAD_THRESHOLD:+ offload_dir = self.dir_path / "tool-results"+ offload_dir.mkdir(exist_ok=True)+ fname = f"{call_id}.txt"+ (offload_dir / fname).write_text(result, encoding="utf-8")+ self.write({+ "type": "tool_result",+ "iter": iteration,+ "tool": tool_name,+ "call_id": call_id,+ "status": status,+ "elapsed_ms": elapsed_ms,+ "result_path": f"tool-results/{fname}",+ "result_preview": result[:OFFLOAD_PREVIEW_CHARS],+ "result_size": len(result),+ })+ else:+ self.write({+ "type": "tool_result",+ "iter": iteration,+ "tool": tool_name,+ "call_id": call_id,+ "status": status,+ "elapsed_ms": elapsed_ms,+ "result": result,+ })+def close(self) -> None:"""Close the file handle."""self._file.close()@staticmethod- def read(run_dir: Path) -> List[Dict[str, Any]]:+ def read(dir_path: Path) -> List[Dict[str, Any]]:"""Read trace.jsonl and return records.+ Offloaded tool results are resolved from their on-disk files+ so the returned entries are self-contained.+Args:- run_dir: Run directory.+ dir_path: Directory containing trace.jsonl.Returns:List of trace records."""- path = run_dir / "trace.jsonl"+ path = dir_path / "trace.jsonl"if not path.exists():return []entries: List[Dict[str, Any]] = []for line in path.read_text(encoding="utf-8").splitlines():line = line.strip()- if line:- try:- entries.append(json.loads(line))- except json.JSONDecodeError:- pass+ if not line:+ continue+ try:+ entry = json.loads(line)+ except json.JSONDecodeError:+ continue++ # Resolve offloaded tool results+ if "result_path" in entry and "result" not in entry:+ result_file = dir_path / entry["result_path"]+ if result_file.exists():+ try:+ entry["result"] = result_file.read_text(encoding="utf-8")+ except (OSError, UnicodeDecodeError):+ pass++ entries.append(entry)return entries++ @staticmethod+ def find_trace_dir(+ run_id: str,+ runs_dir: Optional[Path] = None,+ sessions_dir: Optional[Path] = None,+ ) -> Optional[Path]:+ """Find the trace directory for a given run_id.++ Checks sessions/ first (new location), then runs/ (legacy).+ Returns the directory Path if found, or None.++ Args:+ run_id: Run or session ID.+ runs_dir: Base runs directory. Defaults to agent/runs.+ sessions_dir: Base sessions directory. Defaults to agent/sessions.++ Returns:+ Path to the directory containing trace.jsonl, or None.+ """+ if sessions_dir is None:+ sessions_dir = Path(__file__).resolve().parents[2] / "sessions"+ if runs_dir is None:+ runs_dir = Path(__file__).resolve().parents[2] / "runs"++ # Prefer sessions/ first (new location)+ session_trace = sessions_dir / run_id / "trace.jsonl"+ if session_trace.exists():+ return sessions_dir / run_id++ run_trace = runs_dir / run_id / "trace.jsonl"+ if run_trace.exists():+ return runs_dir / run_id++ # Fall back to runs/ for backward compat (even if file doesn't exist yet)+ return runs_dir / run_iddiff --git a/agent/tests/test_trace_writer.py b/agent/tests/test_trace_writer.pynew file mode 100644index 000000000..7fd15c311--- /dev/null+++ b/agent/tests/test_trace_writer.py@@ -0,0 +1,342 @@+"""Tests for TraceWriter with offload support."""++import json+import tempfile+from pathlib import Path++import pytest++from src.agent.trace import (+ OFFLOAD_PREVIEW_CHARS,+ TOOL_RESULT_OFFLOAD_THRESHOLD,+ TraceWriter,+)+++class TestTraceWriterInline:+ """Tool results ≤ threshold are stored inline."""++ def test_write_basic_entry(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ tw = TraceWriter(Path(tmp))+ tw.write({"type": "start", "prompt": "hello"})+ tw.close()++ entries = TraceWriter.read(Path(tmp))+ assert len(entries) == 1+ assert entries[0]["type"] == "start"+ assert entries[0]["prompt"] == "hello"+ assert "ts" in entries[0]++ def test_write_tool_result_inline(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ tw = TraceWriter(Path(tmp))+ result = "small result"+ tw.write_tool_result(+ call_id="call-1",+ result=result,+ tool_name="test_tool",+ status="ok",+ elapsed_ms=42,+ iteration=1,+ )+ tw.close()++ entries = TraceWriter.read(Path(tmp))+ assert len(entries) == 1+ e = entries[0]+ assert e["type"] == "tool_result"+ assert e["tool"] == "test_tool"+ assert e["call_id"] == "call-1"+ assert e["status"] == "ok"+ assert e["elapsed_ms"] == 42+ assert e["iter"] == 1+ assert e["result"] == "small result"+ assert "result_path" not in e # No offload++ def test_write_tool_result_inline_boundary(self) -> None:+ """Exactly at threshold — still inline."""+ with tempfile.TemporaryDirectory() as tmp:+ tw = TraceWriter(Path(tmp))+ result = "x" * TOOL_RESULT_OFFLOAD_THRESHOLD+ tw.write_tool_result(+ call_id="call-bnd",+ result=result,+ tool_name="test_tool",+ status="ok",+ elapsed_ms=10,+ iteration=2,+ )+ tw.close()++ entries = TraceWriter.read(Path(tmp))+ assert len(entries) == 1+ e = entries[0]+ assert e["result"] == result+ assert "result_path" not in e++ def test_multiple_entries(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ tw = TraceWriter(Path(tmp))+ for i in range(5):+ tw.write_tool_result(+ call_id=f"call-{i}",+ result=f"result-{i}",+ tool_name="tool",+ status="ok",+ elapsed_ms=i,+ iteration=i,+ )+ tw.close()++ entries = TraceWriter.read(Path(tmp))+ assert len(entries) == 5+ assert all(e["result"] for e in entries)+++class TestTraceWriterOffload:+ """Tool results > threshold are offloaded to disk."""++ def test_offload_large_result(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ tw = TraceWriter(Path(tmp))+ result = "y" * (TOOL_RESULT_OFFLOAD_THRESHOLD + 1)+ tw.write_tool_result(+ call_id="call-off",+ result=result,+ tool_name="big_tool",+ status="ok",+ elapsed_ms=999,+ iteration=3,+ )+ tw.close()++ # Check JSONL entry+ path = Path(tmp) / "trace.jsonl"+ raw = path.read_text(encoding="utf-8")+ lines = [l for l in raw.splitlines() if l.strip()]+ assert len(lines) == 1+ entry = json.loads(lines[0])+ assert entry["type"] == "tool_result"+ assert entry["tool"] == "big_tool"+ assert "result" not in entry # Offloaded, not inline+ assert entry["result_path"] == "tool-results/call-off.txt"+ assert entry["result_preview"] == result[:OFFLOAD_PREVIEW_CHARS]+ assert entry["result_size"] == len(result)++ # Check offloaded file exists and is complete+ offload_file = Path(tmp) / "tool-results" / "call-off.txt"+ assert offload_file.exists()+ assert offload_file.read_text(encoding="utf-8") == result++ def test_read_resolves_offloaded_results(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ tw = TraceWriter(Path(tmp))+ big_result = "BIG_DATA_" * 10000 # ~90K chars — above threshold+ tw.write_tool_result(+ call_id="call-resolve",+ result=big_result,+ tool_name="read_tool",+ status="ok",+ elapsed_ms=50,+ iteration=1,+ )+ tw.close()++ # TraceWriter.read should resolve the offloaded result+ entries = TraceWriter.read(Path(tmp))+ assert len(entries) == 1+ e = entries[0]+ assert e["result"] == big_result+ # Metadata still present+ assert e["result_path"] == "tool-results/call-resolve.txt"+ assert e["result_preview"] == big_result[:OFFLOAD_PREVIEW_CHARS]+ assert e["result_size"] == len(big_result)++ def test_mixed_inline_and_offload(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ tw = TraceWriter(Path(tmp))+ small = "small"+ big = "B" * (TOOL_RESULT_OFFLOAD_THRESHOLD + 100)+ tw.write_tool_result(+ call_id="small-1", result=small, tool_name="t",+ status="ok", elapsed_ms=1, iteration=1,+ )+ tw.write_tool_result(+ call_id="big-1", result=big, tool_name="t",+ status="ok", elapsed_ms=2, iteration=2,+ )+ tw.write_tool_result(+ call_id="small-2", result=small, tool_name="t",+ status="ok", elapsed_ms=3, iteration=3,+ )+ tw.close()++ entries = TraceWriter.read(Path(tmp))+ assert len(entries) == 3+ # Small results inline+ assert entries[0]["result"] == small+ assert "result_path" not in entries[0]+ # Big result offloaded but resolved+ assert entries[1]["result"] == big+ assert entries[1]["result_path"] == "tool-results/big-1.txt"+ # Second small also inline+ assert entries[2]["result"] == small+ assert "result_path" not in entries[2]++ # Offload file exists+ assert (Path(tmp) / "tool-results" / "big-1.txt").exists()++ def test_offload_file_content_complete(self) -> None:+ """Offloaded result must be byte-exact, not truncated."""+ with tempfile.TemporaryDirectory() as tmp:+ tw = TraceWriter(Path(tmp))+ # Use varied content to catch encoding issues+ result = "🎯 TRADE " * 6000 + "中文测试" * 2500 + "!\n" * 1000+ # Ensure it's above threshold+ assert len(result) > TOOL_RESULT_OFFLOAD_THRESHOLD+ tw.write_tool_result(+ call_id="unicode-test",+ result=result,+ tool_name="t",+ status="ok",+ elapsed_ms=10,+ iteration=1,+ )+ tw.close()++ offload_file = Path(tmp) / "tool-results" / "unicode-test.txt"+ assert offload_file.read_text(encoding="utf-8") == result++ entries = TraceWriter.read(Path(tmp))+ assert entries[0]["result"] == result+++class TestTraceWriterRead:+ """Edge cases for read()."""++ def test_read_empty_dir(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ entries = TraceWriter.read(Path(tmp))+ assert entries == []++ def test_read_missing_file(self) -> None:+ entries = TraceWriter.read(Path("/nonexistent/path"))+ assert entries == []++ def test_read_malformed_lines(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "trace.jsonl"+ path.write_text(+ '{"type": "ok", "ts": 1}\n'+ 'not json at all\n'+ '{"type": "also-ok", "ts": 2}\n',+ encoding="utf-8",+ )+ entries = TraceWriter.read(Path(tmp))+ assert len(entries) == 2+ assert entries[0]["type"] == "ok"+ assert entries[1]["type"] == "also-ok"++ def test_read_offloaded_missing_file(self) -> None:+ """When offload file is missing, result is not resolved but entry is kept."""+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "trace.jsonl"+ path.write_text(+ json.dumps({+ "type": "tool_result",+ "tool": "ghost",+ "result_path": "tool-results/missing.txt",+ "result_preview": "ghost...",+ "result_size": 99999,+ }) + "\n",+ encoding="utf-8",+ )+ entries = TraceWriter.read(Path(tmp))+ assert len(entries) == 1+ e = entries[0]+ assert "result" not in e # Could not be resolved+ assert e["result_path"] == "tool-results/missing.txt"+++class TestTraceWriterFindTraceDir:+ """find_trace_dir resolves the correct directory for a run_id."""++ def test_finds_sessions_first(self, tmp_path: Path) -> None:+ sessions = tmp_path / "sessions"+ runs = tmp_path / "runs"+ # Create trace in sessions/+ session_dir = sessions / "test-run"+ session_dir.mkdir(parents=True)+ (session_dir / "trace.jsonl").write_text('{"type": "start"}')++ found = TraceWriter.find_trace_dir("test-run", runs_dir=runs, sessions_dir=sessions)+ assert found == session_dir++ def test_falls_back_to_runs(self, tmp_path: Path) -> None:+ sessions = tmp_path / "sessions"+ runs = tmp_path / "runs"+ # Create trace in runs/ only+ run_dir = runs / "test-run"+ run_dir.mkdir(parents=True)+ (run_dir / "trace.jsonl").write_text('{"type": "start"}')++ found = TraceWriter.find_trace_dir("test-run", runs_dir=runs, sessions_dir=sessions)+ assert found == run_dir++ def test_sessions_takes_priority(self, tmp_path: Path) -> None:+ """When trace exists in both sessions/ and runs/, sessions/ wins."""+ sessions = tmp_path / "sessions"+ runs = tmp_path / "runs"+ session_dir = sessions / "dual-run"+ run_dir = runs / "dual-run"+ session_dir.mkdir(parents=True)+ run_dir.mkdir(parents=True)+ (session_dir / "trace.jsonl").write_text('{"type": "session"}')+ (run_dir / "trace.jsonl").write_text('{"type": "run"}')++ found = TraceWriter.find_trace_dir("dual-run", runs_dir=runs, sessions_dir=sessions)+ assert found == session_dir++ def test_returns_none_when_missing(self, tmp_path: Path) -> None:+ sessions = tmp_path / "sessions"+ runs = tmp_path / "runs"+ sessions.mkdir(parents=True)+ runs.mkdir(parents=True)++ found = TraceWriter.find_trace_dir("nowhere", runs_dir=runs, sessions_dir=sessions)+ # Falls back to runs/ dir path even if trace.jsonl doesn't exist+ assert found == runs / "nowhere"+++class TestTraceWriterSessionDir:+ """Session-based trace directory creation."""++ def test_creates_dir_if_missing(self, tmp_path: Path) -> None:+ session_dir = tmp_path / "sessions" / "new-session"+ assert not session_dir.exists()++ tw = TraceWriter(session_dir)+ tw.write({"type": "start"})+ tw.close()++ assert session_dir.exists()+ assert (session_dir / "trace.jsonl").exists()++ def test_offload_creates_tool_results_dir(self, tmp_path: Path) -> None:+ session_dir = tmp_path / "sessions" / "offload-test"+ tw = TraceWriter(session_dir)+ big = "X" * (TOOL_RESULT_OFFLOAD_THRESHOLD + 10)+ tw.write_tool_result(+ call_id="big-call",+ result=big,+ tool_name="t",+ status="ok",+ elapsed_ms=1,+ iteration=1,+ )+ tw.close()++ offload_dir = session_dir / "tool-results"+ assert offload_dir.exists()+ assert (offload_dir / "big-call.txt").exists()