"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(trace): rebase trace offload onto current main
Haozhe Wu4f70258d40c6
diff --cc agent/cli/_legacy.pyindex 247e65cb1,547013c3d..ab13a767c--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@@ -1392,17 -1392,9 +1392,17 @@@ def cmd_run(prompt: str, max_iter: intdef _build_history_from_trace(run_dir: Path) -> List[Dict[str, str]]:- """Build conversation history from trace.jsonl.-- Checks sessions/<run_id>/ first (new location), then falls back to- runs/<run_id>/ (legacy location).- """+ """Build conversation history from trace.jsonl."""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():++ if trace_dir is None:+ return []- entries = TraceWriter.read(trace_dir)++ entries = TraceWriter.read(++ trace_dir,++ resolve_offloads=True,++ resolve_fields={"prompt", "content"},++ )history: List[Dict[str, str]] = []for e in entries:if e.get("type") == "start" and e.get("prompt"):@@@ -1429,10 -1420,6 +1429,8 @@@ def cmd_continuereturn 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:@@@ -2235,8 -2222,7 +2233,12 @@@ def cmd_show(run_id: str) -> Nonelines.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 []++ entries = (++ TraceWriter.read(trace_dir, resolve_offloads=True, resolve_fields={"content"})++ 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]@@@ -2295,12 -2281,12 +2297,16 @@@ 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():++ if trace_dir is None:+ console.print(f"[red]{run_id}/trace.jsonl not found[/red]")return- entries = TraceWriter.read(trace_dir)- entries = TraceWriter.read(run_dir)++ entries = TraceWriter.read(++ trace_dir,++ resolve_offloads=True,++ resolve_fields={"prompt", "content", "summary"},++ )if not entries:console.print(f"[red]{run_id}/trace.jsonl is empty or missing[/red]")return@@@ -2322,7 -2308,7 +2328,7 @@@elif etype == "tool_call":tool = entry.get("tool", "")args = entry.get("args", {})-- args_str = ", ".join(f"{k}={v[:40]}" for k, v in args.items()) if args else ""++ args_str = ", ".join(f"{k}={str(v)[:40]}" for k, v in args.items()) if args else ""console.print(f"[dim]{ts_str}[/dim] {iter_tag}[cyan]\u25b6 {tool}[/cyan]({args_str})")elif etype == "tool_result":tool = entry.get("tool", "")@@@ -2331,21 -2317,13 +2337,21 @@@ok = status == "ok"mark = "\u2713" if ok else "\u2717"color = "green" if ok else "red"- # 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 ""- preview = entry.get("preview", "")[:80]- console.print(f"[dim]{ts_str}[/dim] {iter_tag}[{color}]{mark} {tool}[/{color}] [dim]{elapsed}ms[/dim] {preview}")++ preview = (entry.get("preview") or entry.get("result_preview") or entry.get("result") or "")[:80]++ size_hint = ""++ if entry.get("result_path"):++ size_hint = f" [{int(entry.get('result_size') or 0) // 1024}K offloaded]"+ 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", "")++ content = entry.get("content") or entry.get("content_preview") or ""+ 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 --cc agent/src/agent/loop.pyindex aea0b0785,4f8b5885a..41c5167f0--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@@ -33,11 -35,10 +35,12 @@@ from src.goal.context importgoal_needs_continuation,goal_progress_tuple,)- from src.providers.chat import ChatLLM+ from src.providers.chat import ChatLLM, ProviderStreamErrorfrom src.tools.background_tools import get_background_manager++from src.tools.redaction import redact_payloadRUNS_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@@@ -57,6 -61,13 +63,31 @@@ TAIL_TOKEN_BUDGET = 20_00logger = logging.getLogger(__name__)++def _redact_trace_result(result: str) -> str:++ """Redact structured sensitive fields before persisting trace/event previews.++++ Args:++ result: Raw tool result string.++++ Returns:++ Redacted JSON string when ``result`` is JSON, otherwise the original++ text. Plain text is left unchanged because reliable free-text secret++ scrubbing would be more error-prone than helpful here.++ """++ try:++ payload = json.loads(result)++ except (TypeError, json.JSONDecodeError):++ return result++ return json.dumps(redact_payload(payload), ensure_ascii=False)+++++ def _format_timeout(seconds: float) -> str:+ """Return a human-readable timeout label."""+ if seconds < 1:+ return f"{seconds:.2f}s"+ return f"{seconds:.0f}s"++def estimate_tokens(messages: list) -> int:"""Rough token count estimate (~4 chars/token).@@@ -341,7 -352,6 +372,7 @@@ class AgentLoopself._cancelled: bool = Falseself._previous_summary: str = ""self._persistent_memory = persistent_memory- self._run_iteration: int = 0 # persistent iteration counter across run() calls++ self._run_iteration: int = 0def cancel(self) -> None:"""Cancel the current loop.@@@ -391,27 -401,8 +422,26 @@@messages = context.build_messages(llm_user_message, history)react_trace: List[Dict[str, Any]] = []- # 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(run_dir)- trace.write({"type": "start", "prompt": user_message[:500]})++ trace_dir = SESSIONS_DIR / session_id if session_id else run_dir+ trace = TraceWriter(trace_dir)-- # Resume iteration counter from existing trace when a fresh- # AgentLoop instance continues an existing session (CLI interactive- # mode creates a new AgentLoop per turn, all writing to the same- # sessions/<session_id>/trace.jsonl).- # IMPORTANT: this must run BEFORE writing start/message so that- # those entries carry the correct iter number for the resumed turn.+ if self._run_iteration == 0 and trace.path.exists():+ existing = TraceWriter.read(trace_dir)- max_iter = max((e.get("iter", 0) for e in existing if "iter" in e), default=0)- self._run_iteration = max_iter-- trace.write({"type": "start", "iter": self._run_iteration + 1, "prompt": user_message})- trace.write({"type": "message", "iter": self._run_iteration + 1, "role": "user", "content": user_message})++ self._run_iteration = max(++ (int(e.get("iter", 0)) for e in existing if "iter" in e),++ default=0,++ )++ trace.write_text_entry(++ {"type": "start", "iter": self._run_iteration + 1},++ field="prompt",++ value=user_message,++ offload_kind=f"start-{self._run_iteration + 1}",++ )++ trace.write_text_entry(++ {"type": "message", "iter": self._run_iteration + 1, "role": "user"},++ field="content",++ value=user_message,++ offload_kind=f"user-message-{self._run_iteration + 1}",++ )iteration = 0final_content = ""@@@ -422,12 -414,11 +453,13 @@@try:while iteration < self.max_iterations:if self._cancelled:- trace.write({"type": "cancelled", "iter": self._run_iteration})- trace.write({"type": "cancelled", "iter": iteration})++ trace.write({"type": "cancelled", "iter": self._run_iteration + 1})logger.info("AgentLoop cancelled by user")breakiteration += 1+ self._run_iteration += 1++ current_iter = self._run_iteration# Inject background task notificationsbg = get_background_manager()@@@ -449,7 -440,7 +481,7 @@@# Layer 3: auto_compact (token threshold exceeded)if tokens > TOKEN_THRESHOLD:logger.info(f"Auto compact triggered: {tokens} tokens > {TOKEN_THRESHOLD}")-- self._auto_compact(messages, run_dir, trace)++ self._auto_compact(messages, run_dir, trace, iteration=current_iter)logger.info(f"ReAct iteration {iteration}/{self.max_iterations}")@@@ -475,19 -468,73 +509,73 @@@def _on_text_chunk(delta: str) -> None:thinking_chunks.append(delta)- self._emit("text_delta", {"delta": delta, "iter": self._run_iteration})- self._emit("text_delta", {"delta": delta, "iter": iteration})++ self._emit("text_delta", {"delta": delta, "iter": current_iter})++ def _on_reasoning_chunk(delta: str) -> None:+ # Throttled: long reasoning streams produce hundreds of+ # chunks; emitting each one floods the SSE replay buffer+ # and evicts tool_call/text_delta events. The first chunk+ # of each iteration always emits immediately so the UI+ # flips to "Reasoning…" without delay.+ nonlocal reasoning_chars, last_reasoning_emit+ reasoning_chars += len(delta)+ now = _time.monotonic()+ if (+ last_reasoning_emit is not None+ and now - last_reasoning_emit < REASONING_DELTA_MIN_INTERVAL_S+ ):+ return+ last_reasoning_emit = now+ self._emit(+ "reasoning_delta",- {"iter": iteration, "chars": reasoning_chars},++ {"iter": current_iter, "chars": reasoning_chars},+ )# On last iteration, drop tool definitions to force text outputis_last_iteration = (iteration == self.max_iterations)tool_defs = None if is_last_iteration else self.registry.get_definitions()if is_last_iteration:- trace.write({"type": "forced_text_only", "iter": self._run_iteration})- trace.write({"type": "forced_text_only", "iter": iteration})++ trace.write({"type": "forced_text_only", "iter": current_iter})- response = self.llm.stream_chat(- messages,- tools=tool_defs,- on_text_chunk=_on_text_chunk,- )+ try:+ response = self.llm.stream_chat(+ messages,+ tools=tool_defs,+ on_text_chunk=_on_text_chunk,+ on_reasoning_chunk=_on_reasoning_chunk,+ )+ except ProviderStreamError as exc:+ # One retry for transient mid-stream failures (connection+ # reset, relay hiccup) — mirrors the swarm worker policy.+ # Deterministic 4xx errors fail immediately. Deltas from+ # the failed attempt are dropped so the trace does not+ # contain duplicated thinking text.+ if not exc.retryable:+ raise+ logger.warning(+ "Provider stream failed (iter %s), retrying once: %s",- iteration,++ current_iter,+ exc,+ )+ self._emit(+ "stream_reset",+ {- "iter": iteration,++ "iter": current_iter,+ "reason": "provider_stream_retry",+ "provider": exc.provider,+ "model": exc.model,+ },+ )+ thinking_chunks.clear()+ reasoning_chars = 0+ last_reasoning_emit = None+ _time.sleep(STREAM_RETRY_DELAY_S)+ response = self.llm.stream_chat(+ messages,+ tools=tool_defs,+ on_text_chunk=_on_text_chunk,+ on_reasoning_chunk=_on_reasoning_chunk,+ )usage = getattr(response, "usage_metadata", None) or {}if usage:self._emit(@@@ -496,7 -543,7 +584,7 @@@"input_tokens": int(usage.get("input_tokens") or 0),"output_tokens": int(usage.get("output_tokens") or 0),"total_tokens": int(usage.get("total_tokens") or 0),- "iter": self._run_iteration,- "iter": iteration,++ "iter": current_iter,},)if active_goal_id and session_id:@@@ -527,11 -574,22 +615,27 @@@thinking_text = "".join(thinking_chunks)if thinking_text:- trace.write({"type": "thinking", "iter": self._run_iteration, "content": thinking_text})- self._emit("thinking_done", {"iter": self._run_iteration, "content": thinking_text[:500]})- trace.write({"type": "thinking", "iter": iteration, "content": thinking_text[:2000]})- self._emit("thinking_done", {"iter": iteration, "content": thinking_text[:500]})++ trace.write_text_entry(++ {"type": "thinking", "iter": current_iter},++ field="content",++ value=thinking_text,++ offload_kind=f"thinking-{current_iter}",++ )++ self._emit("thinking_done", {"iter": current_iter, "content": thinking_text[:500]})if not response.has_tool_calls:final_content = response.content or ""+ if not final_content:+ empty_model_response_iter = iteration+ trace.write(+ {+ "type": "empty_model_response",- "iter": iteration,++ "iter": current_iter,+ "provider": os.getenv("LANGCHAIN_PROVIDER", "openai"),+ "model": getattr(self.llm, "model_name", None) or os.getenv("LANGCHAIN_MODEL_NAME", ""),+ }+ )+ breakshould_continue_goal = Falsecontinuation_snapshot = Noneif active_goal_id and session_id and GOAL_MAX_CONTINUATIONS > 0:@@@ -560,23 -618,22 +664,30 @@@trace.write({"type": "goal_continuation_suppressed",- "iter": self._run_iteration,- "iter": iteration,++ "iter": current_iter,"goal_id": active_goal_id,"progress": current_progress,"continuations": goal_continuations,})else:-- trace.write(++ trace.write_text_entry({"type": "goal_intermediate_answer",- "iter": self._run_iteration,- "iter": iteration,++ "iter": current_iter,"goal_id": active_goal_id,- "content": final_content,- "content": final_content[:2000],"progress": current_progress,-- }++ },++ field="content",++ value=final_content,++ offload_kind=f"goal-intermediate-answer-{current_iter}",++ )++ trace.write_text_entry(++ {"type": "message", "iter": current_iter, "role": "assistant"},++ field="content",++ value=final_content,++ offload_kind=f"assistant-message-{current_iter}",)- trace.write({"type": "message", "iter": self._run_iteration, "role": "assistant", "content": final_content})react_trace.append({"type": "goal_intermediate_answer", "content": final_content[:500]})@@@ -594,8 -651,7 +705,18 @@@goal_continuations += 1continue- trace.write({"type": "answer", "iter": self._run_iteration, "content": final_content})- trace.write({"type": "message", "iter": self._run_iteration, "role": "assistant", "content": final_content})- trace.write({"type": "answer", "iter": iteration, "content": final_content[:2000]})++ trace.write_text_entry(++ {"type": "answer", "iter": current_iter},++ field="content",++ value=final_content,++ offload_kind=f"answer-{current_iter}",++ )++ trace.write_text_entry(++ {"type": "message", "iter": current_iter, "role": "assistant"},++ field="content",++ value=final_content,++ offload_kind=f"assistant-message-{current_iter}",++ )react_trace.append({"type": "answer", "content": final_content[:500]})break@@@ -609,17 -665,22 +730,22 @@@# Execute tools with read/write batchingcompact_requested, focus_topic = self._process_tool_calls(- response.tool_calls, context, messages, trace, react_trace, self._run_iteration,- response.tool_calls, context, messages, trace, react_trace, iteration,++ response.tool_calls, context, messages, trace, react_trace, current_iter,)# Layer 3: compress after all tools have executedif compact_requested:logger.info("Manual compact triggered by model")-- self._auto_compact(messages, run_dir, trace, focus_topic=focus_topic)++ self._auto_compact(messages, run_dir, trace, focus_topic=focus_topic, iteration=current_iter)except Exception as exc:logger.exception(f"AgentLoop error: {exc}")- trace.write({"type": "end", "iter": self._run_iteration, "status": "error", "reason": str(exc), "iterations": iteration}) # per-run count+ error_code = (+ "provider_stream_error"+ if isinstance(exc, ProviderStreamError)+ else "agent_loop_error"+ )- trace.write({"type": "end", "status": "error", "reason": str(exc), "iterations": iteration})++ trace.write({"type": "end", "iter": self._run_iteration, "status": "error", "reason": str(exc), "iterations": iteration})trace.close()state_store.mark_failure(run_dir, str(exc))return {@@@ -801,8 -874,8 +940,10 @@@runnable: list[tuple] = []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) for k, v in args.items()}})- 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()}})++ redacted_args = redact_payload(args)++ event_args = {k: str(v)[:200] for k, v in redacted_args.items()}++ self._emit("tool_call", {"tool": tc.name, "arguments": event_args, "iter": iteration})++ trace.write({"type": "tool_call", "iter": iteration, "tool": tc.name, "call_id": tc.id, "args": redacted_args})runnable.append((tc, args))# Execute in parallel — each worker gets its own heartbeat + progress emitter.@@@ -846,8 -919,8 +987,10 @@@"""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) for k, v in args.items()}})- 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()}})++ redacted_args = redact_payload(args)++ event_args = {k: str(v)[:200] for k, v in redacted_args.items()}++ self._emit("tool_call", {"tool": tc.name, "arguments": event_args, "iter": iteration})++ trace.write({"type": "tool_call", "iter": iteration, "tool": tc.name, "call_id": tc.id, "args": redacted_args})logger.info(f"Tool call: {tc.name}({list(args.keys())})")result, elapsed_ms = self._invoke_tool(tc.name, args)@@@ -926,21 -1126,14 +1196,29 @@@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]})- 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]})++ trace_result = _redact_trace_result(result)+ trace.write_tool_result(+ call_id=tc.id,- result=result,++ result=trace_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]})++ preview = trace_result[:200]++ react_trace.append({"type": "tool_call", "tool": tc.name, "result_preview": preview})++ self._emit("tool_result", {"tool": tc.name, "status": status, "elapsed_ms": elapsed_ms, "preview": preview})# -- Context compression ----------------------------------------------------- def _auto_compact(self, messages: list, run_dir: Path, trace: TraceWriter,-- focus_topic: str = "") -> None:++ def _auto_compact(++ self,++ messages: list,++ run_dir: Path,++ trace: TraceWriter,++ focus_topic: str = "",++ iteration: int = 0,++ ) -> None:"""Layer 3/4/5: structured LLM summary with token-budget tail protection.Upgrades over the original:@@@ -955,10 -1148,9 +1233,11 @@@run_dir: Run directory.trace: TraceWriter.focus_topic: Optional topic to prioritize in the summary.++ iteration: Current trace iteration."""- # Save full transcript before compressing (uses trace dir so session-based- # runs store transcripts alongside trace.jsonl)- # Save full transcript before compressing- transcript_path = run_dir / f"transcript_{int(_time.time())}.jsonl"++ del run_dir++ # Save full transcript before compressing next to the active trace.+ 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")@@@ -1015,8 -1207,8 +1294,17 @@@self._previous_summary = summarytokens_before = estimate_tokens(messages)- trace.write({"type": "compact", "tokens_before": tokens_before, "summary": summary,- trace.write({"type": "compact", "tokens_before": tokens_before, "summary": summary[:500],-- "focus_topic": focus_topic or "(none)"})++ trace.write_text_entry(++ {++ "type": "compact",++ "iter": iteration,++ "tokens_before": tokens_before,++ "focus_topic": focus_topic or "(none)",++ },++ field="summary",++ value=summary,++ offload_kind=f"compact-summary-{iteration}",++ )self._emit("compact", {"tokens_before": tokens_before, "summary": summary[:200]})# Reconstruct: system + summary + acknowledge + preserved taildiff --cc agent/src/agent/trace.pyindex 1f568ae78,5251d81fd..661c2d837--- a/agent/src/agent/trace.py+++ b/agent/src/agent/trace.py@@@ -1,174 -1,66 +1,275 @@@"""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.++One JSON record per line; append + flush keeps the trace useful after crashes.++Large fields are written to sidecar files so traces can preserve full content++without turning every CLI/history read into a giant file load."""from __future__ import annotations++import hashlibimport json++import osimport timefrom pathlib import Path- from typing import Any, Dict, List, Optional-from typing import Any, Dict, List++from typing import Any, Dict, Iterable, List, Optional+- TOOL_RESULT_OFFLOAD_THRESHOLD = 50_000- OFFLOAD_PREVIEW_CHARS = 500++++def _env_int(name: str, default: int) -> int:++ """Read a positive integer environment variable with a safe fallback.++++ Args:++ name: Environment variable name.++ default: Fallback value.++++ Returns:++ Parsed positive integer, or ``default`` when unset/invalid.++ """++ raw = os.getenv(name)++ if raw is None:++ return default++ try:++ value = int(raw)++ except ValueError:++ return default++ return value if value > 0 else default++++++TOOL_RESULT_OFFLOAD_THRESHOLD = _env_int(++ "VIBE_TRADING_TRACE_TOOL_RESULT_INLINE_LIMIT",++ 50_000,++)++TRACE_TEXT_OFFLOAD_THRESHOLD = _env_int(++ "VIBE_TRADING_TRACE_TEXT_INLINE_LIMIT",++ 50_000,++)++OFFLOAD_PREVIEW_CHARS = _env_int("VIBE_TRADING_TRACE_PREVIEW_CHARS", 500)class 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.++ dir_path: Directory containing ``trace.jsonl`` and sidecar blobs.++ path: Path to the trace JSONL file."""- def __init__(self, run_dir: Path) -> None:+ def __init__(self, dir_path: Path) -> None:"""Initialize TraceWriter.Args:- dir_path: Directory where trace.jsonl (and tool-results/) are written.- run_dir: Run directory; trace.jsonl is written here.++ dir_path: Directory where trace files 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.dir_path.mkdir(parents=True, exist_ok=True)++ self.path = self.dir_path / "trace.jsonl"self._file = open(self.path, "a", encoding="utf-8")def write(self, entry: Dict[str, Any]) -> None:"""Write a trace record.Args:-- entry: Trace entry; a ts field is added automatically.++ entry: Trace entry; a ``ts`` field is added automatically."""if "ts" not in entry:entry["ts"] = time.time()self._file.write(json.dumps(entry, ensure_ascii=False) + "\n")self._file.flush()++ def write_text_entry(++ self,++ entry: Dict[str, Any],++ *,++ field: str,++ value: str,++ offload_kind: str,++ threshold: int | None = None,++ ) -> None:++ """Write an entry with one potentially large text field.++++ Args:++ entry: Base trace entry. Mutated before writing.++ field: Text field name, e.g. ``"content"`` or ``"prompt"``.++ value: Full text value to preserve.++ offload_kind: Stable label used in the sidecar filename hash input.++ threshold: Optional inline threshold override.++ """++ self._attach_text_field(++ entry,++ field=field,++ value=value,++ offload_kind=offload_kind,++ threshold=threshold or TRACE_TEXT_OFFLOAD_THRESHOLD,++ offload_dir_name="trace-blobs",++ )++ self.write(entry)+++ 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.++ """Write a tool_result entry, offloading large results to disk.++ Args:- call_id: Tool call ID.- result: Raw tool result string.++ call_id: Provider tool call ID.++ result: Raw tool result string after any caller-side redaction.+ tool_name: Tool name.- status: "ok" or "error".++ 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,- })++ entry: Dict[str, Any] = {++ "type": "tool_result",++ "iter": iteration,++ "tool": tool_name,++ "call_id": call_id,++ "status": status,++ "elapsed_ms": elapsed_ms,++ "preview": result[:OFFLOAD_PREVIEW_CHARS],++ }++ self._attach_text_field(++ entry,++ field="result",++ value=result,++ offload_kind=f"tool-result-{tool_name}-{call_id}",++ threshold=TOOL_RESULT_OFFLOAD_THRESHOLD,++ offload_dir_name="tool-results",++ preview_field="result_preview",++ )++ self.write(entry)+def close(self) -> None:"""Close the file handle."""self._file.close()- @staticmethod- def read(dir_path: Path) -> List[Dict[str, Any]]:- """Read trace.jsonl and return records.++ def _attach_text_field(++ self,++ entry: Dict[str, Any],++ *,++ field: str,++ value: str,++ offload_kind: str,++ threshold: int,++ offload_dir_name: str,++ preview_field: str | None = None,++ ) -> None:++ """Attach text inline or as a sidecar path."""++ if len(value) <= threshold:++ entry[field] = value++ return+- Offloaded tool results are resolved from their on-disk files- so the returned entries are self-contained.++ offload_dir = self.dir_path / offload_dir_name++ offload_dir.mkdir(parents=True, exist_ok=True)++ digest = hashlib.sha256(f"{offload_kind}\0{value}".encode("utf-8")).hexdigest()++ path = offload_dir / f"{digest[:24]}.txt"++ path.write_text(value, encoding="utf-8")++ entry[f"{field}_path"] = f"{offload_dir_name}/{path.name}"++ entry[preview_field or f"{field}_preview"] = value[:OFFLOAD_PREVIEW_CHARS]++ entry[f"{field}_size"] = len(value)+++ @staticmethod- def read(run_dir: Path) -> List[Dict[str, Any]]:- """Read trace.jsonl and return records.++ def read(++ dir_path: Path,++ *,++ resolve_offloads: bool = False,++ resolve_fields: Optional[Iterable[str]] = None,++ ) -> List[Dict[str, Any]]:++ """Read trace.jsonl records.Args:- dir_path: Directory containing trace.jsonl.- run_dir: Run directory.++ dir_path: Directory containing ``trace.jsonl``.++ resolve_offloads: Whether to read sidecar files back into entries.++ resolve_fields: Optional field allowlist to resolve. For example,++ ``{"content", "prompt"}`` avoids loading large tool results.Returns:List of trace records."""- path = run_dir / "trace.jsonl"+ path = dir_path / "trace.jsonl"if not path.exists():return []++ fields = set(resolve_fields) if resolve_fields is not None else Noneentries: 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-++ if resolve_offloads:++ TraceWriter._resolve_entry_offloads(dir_path, entry, fields)+ entries.append(entry)return entries+++ @staticmethod++ def _resolve_entry_offloads(++ dir_path: Path,++ entry: Dict[str, Any],++ fields: Optional[set[str]],++ ) -> None:++ """Resolve safe sidecar paths into their original fields."""++ for key, rel_path in list(entry.items()):++ if not key.endswith("_path") or not isinstance(rel_path, str):++ continue++ field = key[:-5]++ if fields is not None and field not in fields:++ continue++ if field in entry:++ continue++ result_file = TraceWriter._safe_sidecar_path(dir_path, rel_path)++ if result_file is None or not result_file.exists():++ continue++ try:++ entry[field] = result_file.read_text(encoding="utf-8")++ except (OSError, UnicodeDecodeError):++ continue++++ @staticmethod++ def _safe_sidecar_path(dir_path: Path, rel_path: str) -> Path | None:++ """Return a sidecar path only if it stays inside ``dir_path``."""++ root = dir_path.resolve()++ candidate = (dir_path / rel_path).resolve()++ try:++ candidate.relative_to(root)++ except ValueError:++ return None++ return candidate+++ @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.++ """Find the trace directory for a run/session id.++ 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.++ 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.++ Directory containing ``trace.jsonl``, or ``None`` when absent.+ """+ 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++ session_dir = sessions_dir / run_id++ if (session_dir / "trace.jsonl").exists():++ return session_dir+- run_trace = runs_dir / run_id / "trace.jsonl"- if run_trace.exists():- return runs_dir / run_id++ run_dir = runs_dir / run_id++ if (run_dir / "trace.jsonl").exists():++ return run_dir+- # Fall back to runs/ for backward compat (even if file doesn't exist yet)- return runs_dir / run_id++ return Nonediff --cc agent/tests/test_agent_loop_trace.pyindex 000000000,000000000..1422a1acfnew file mode 100644--- /dev/null+++ b/agent/tests/test_agent_loop_trace.py@@@ -1,0 -1,0 +1,147 @@@++"""AgentLoop trace integration tests for PR #206 rebase."""++++from __future__ import annotations++++import json++from pathlib import Path++from types import SimpleNamespace++from typing import Any, Callable++++import pytest++++import src.agent.loop as loop_mod++import src.agent.trace as trace_mod++from src.agent.context import ContextBuilder++from src.agent.loop import AgentLoop++from src.agent.trace import TraceWriter++++++class _Tool:++ is_readonly = False++ repeatable = True++++++class _SecretRegistry:++ """Minimal registry returning a JSON result with sensitive fields."""++++ _tools: dict[str, Any] = {}++++ def get(self, tool_name: str) -> _Tool:++ return _Tool()++++ def execute(self, tool_name: str, args: dict[str, Any]) -> str:++ del tool_name, args++ return json.dumps(++ {++ "status": "ok",++ "symbol": "AAPL",++ "authorization": "Bearer secret-token",++ "nested": {"api_key": "secret-key"},++ }++ )++++++def test_tool_call_trace_redacts_args_and_structured_results(tmp_path: Path) -> None:++ """Persistent trace entries should not store raw credentials/account fields."""++ agent = AgentLoop(++ registry=_SecretRegistry(), # type: ignore[arg-type]++ llm=SimpleNamespace(),++ max_iterations=1,++ )++ run_dir = tmp_path / "run"++ run_dir.mkdir()++ agent.memory.run_dir = str(run_dir)++ trace = TraceWriter(run_dir)++ messages: list[dict[str, Any]] = []++ react_trace: list[dict[str, Any]] = []++ tc = SimpleNamespace(++ id="tc_secret",++ name="secret_tool",++ arguments={++ "symbol": "AAPL",++ "api_key": "raw-secret",++ "nested": {"authorization": "Bearer raw-secret"},++ },++ )++++ agent._execute_single(tc, ContextBuilder, messages, trace, react_trace, 1)++ trace.close()++++ entries = TraceWriter.read(run_dir, resolve_offloads=True)++ tool_call = next(entry for entry in entries if entry["type"] == "tool_call")++ assert tool_call["args"]["symbol"] == "AAPL"++ assert tool_call["args"]["api_key"] == "[redacted]"++ assert tool_call["args"]["nested"]["authorization"] == "[redacted]"++++ tool_result = next(entry for entry in entries if entry["type"] == "tool_result")++ assert "secret-token" not in json.dumps(tool_result)++ assert "secret-key" not in json.dumps(tool_result)++ result_payload = json.loads(tool_result["result"])++ assert result_payload["authorization"] == "[redacted]"++ assert result_payload["nested"]["api_key"] == "[redacted]"++ assert messages[0]["content"].count("secret-token") == 1++++++class _LongAnswerResponse:++ content = "final answer " * 10++ tool_calls: list[Any] = []++ reasoning_content: str | None = None++ has_tool_calls = False++ usage_metadata: dict[str, int] | None = None++++++class _LongAnswerLLM:++ def stream_chat(++ self,++ messages: list[dict[str, Any]],++ tools: list[Any] | None = None,++ on_text_chunk: Callable[[str], None] | None = None,++ on_reasoning_chunk: Callable[[str], None] | None = None,++ ) -> _LongAnswerResponse:++ del messages, tools, on_reasoning_chunk++ if on_text_chunk:++ on_text_chunk("final answer ")++ return _LongAnswerResponse()++++ def chat(self, messages: list[dict[str, Any]], **_: Any) -> _LongAnswerResponse:++ del messages++ return _LongAnswerResponse()++++++def test_session_trace_uses_session_dir_and_round_trips_long_answer(++ monkeypatch: pytest.MonkeyPatch,++ tmp_path: Path,++) -> None:++ """Session runs aggregate trace.jsonl under sessions/<id> without truncation."""++ monkeypatch.setattr(trace_mod, "TRACE_TEXT_OFFLOAD_THRESHOLD", 16)++ monkeypatch.setattr(loop_mod, "SESSIONS_DIR", tmp_path / "sessions")++ agent = AgentLoop(++ registry=_SecretRegistry(), # type: ignore[arg-type]++ llm=_LongAnswerLLM(),++ max_iterations=1,++ )++ run_dir = tmp_path / "run"++ run_dir.mkdir()++ agent.memory.run_dir = str(run_dir)++++ result = agent.run(user_message="hello from session", session_id="sid123")++++ assert result["status"] == "success"++ trace_dir = tmp_path / "sessions" / "sid123"++ assert (trace_dir / "trace.jsonl").exists()++ assert not (run_dir / "trace.jsonl").exists()++++ unresolved = TraceWriter.read(trace_dir)++ answer = next(entry for entry in unresolved if entry["type"] == "answer")++ assert "content" not in answer++ assert answer["content_size"] == len(result["content"])++++ resolved = TraceWriter.read(++ trace_dir,++ resolve_offloads=True,++ resolve_fields={"content", "prompt"},++ )++ answer = next(entry for entry in resolved if entry["type"] == "answer")++ start = next(entry for entry in resolved if entry["type"] == "start")++ assert answer["content"] == result["content"]++ assert start["prompt"] == "hello from session"diff --cc agent/tests/test_trace_writer.pyindex 9aaf6082b,000000000..1f0227287mode 100644,000000..100644--- a/agent/tests/test_trace_writer.py+++ b/agent/tests/test_trace_writer.py@@@ -1,398 -1,0 +1,129 @@@- """Tests for TraceWriter with offload support."""++"""TraceWriter offload and path-safety tests."""++++from __future__ import annotations++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,++import src.agent.trace as trace_mod++from src.agent.trace import TraceWriter++++++def _raw_entries(trace_dir: Path) -> list[dict]:++ return [++ json.loads(line)++ for line in (trace_dir / "trace.jsonl").read_text(encoding="utf-8").splitlines()++ if line.strip()++ ]++++++def test_tool_result_offload_uses_safe_name_and_resolves_only_on_request(++ monkeypatch: pytest.MonkeyPatch,++ tmp_path: Path,++) -> None:++ """Large tool results should not trust provider-supplied call IDs as paths."""++ monkeypatch.setattr(trace_mod, "TOOL_RESULT_OFFLOAD_THRESHOLD", 8)++ trace = TraceWriter(tmp_path)++++ trace.write_tool_result(++ call_id="../escape/token",++ result="large result body",++ tool_name="danger_tool",++ status="ok",++ elapsed_ms=12,++ iteration=3,++ )++ trace.close()++++ [entry] = _raw_entries(tmp_path)++ assert "result" not in entry++ assert entry["preview"] == "large result body"[: trace_mod.OFFLOAD_PREVIEW_CHARS]++ assert entry["result_preview"] == entry["preview"]++ assert entry["result_size"] == len("large result body")++ assert entry["result_path"].startswith("tool-results/")++ assert ".." not in Path(entry["result_path"]).parts++ assert Path(entry["result_path"]).name == Path(entry["result_path"]).as_posix().split("/")[-1]++ assert not (tmp_path.parent / "escape" / "token").exists()++++ unresolved = TraceWriter.read(tmp_path)++ assert "result" not in unresolved[0]++++ resolved = TraceWriter.read(tmp_path, resolve_offloads=True)++ assert resolved[0]["result"] == "large result body"++++++def test_trace_reader_refuses_offload_path_escape(tmp_path: Path) -> None:++ """A malicious trace.jsonl must not make read() open files outside trace dir."""++ secret_file = tmp_path / "secret.txt"++ secret_file.write_text("do-not-read", encoding="utf-8")++ trace_dir = tmp_path / "trace"++ trace_dir.mkdir()++ (trace_dir / "trace.jsonl").write_text(++ json.dumps(++ {++ "type": "tool_result",++ "iter": 1,++ "tool": "ghost",++ "result_path": "../secret.txt",++ "result_preview": "x",++ "result_size": 11,++ }+ )- tw.close()-- offload_dir = session_dir / "tool-results"- assert offload_dir.exists()- assert (offload_dir / "big-call.txt").exists()--- class TestTraceFieldConsistency:- """Every entry carries `iter` right after `type`."""-- def test_tool_result_iter_second(self) -> None:- """write_tool_result puts iter right after type."""- with tempfile.TemporaryDirectory() as tmp:- tw = TraceWriter(Path(tmp))- tw.write_tool_result("c1", "result", "tool", "ok", 10, 42)- tw.close()-- entry = json.loads((Path(tmp) / "trace.jsonl").read_text())- keys = list(entry.keys())- assert keys[:2] == ["type", "iter"], f"keys={keys}"- assert entry["iter"] == 42-- def test_generic_write_preserves_type_then_iter(self) -> None:- """When caller passes type+iter first, field order is preserved on disk."""- with tempfile.TemporaryDirectory() as tmp:- tw = TraceWriter(Path(tmp))- tw.write({"type": "start", "iter": 3, "prompt": "hello"})- tw.write({"type": "end", "iter": 5, "status": "success", "iterations": 2})- tw.close()-- for lineno, line in enumerate(- (Path(tmp) / "trace.jsonl").read_text().splitlines()- ):- entry = json.loads(line)- keys = list(entry.keys())- assert keys[0] == "type", f"line {lineno}: type not first: {keys}"- assert keys[1] == "iter", f"line {lineno}: iter not second: {keys}"-- def test_all_entry_types_carry_iter(self) -> None:- """All semantically distinct entry types have iter."""- with tempfile.TemporaryDirectory() as tmp:- tw = TraceWriter(Path(tmp))- tw.write({"type": "start", "iter": 1, "prompt": "test"})- tw.write({"type": "message", "iter": 1, "role": "user", "content": "test"})- tw.write({"type": "thinking", "iter": 1, "content": "..."})- tw.write_tool_result("c1", "x", "tool", "ok", 10, 1)- tw.write({"type": "answer", "iter": 1, "content": "done"})- tw.write({"type": "message", "iter": 1, "role": "assistant", "content": "done"})- tw.write({"type": "cancelled", "iter": 1})- tw.write({"type": "forced_text_only", "iter": 1})- tw.write_tool_result("c2", "x", "tool", "error", 5, 1)- tw.write({"type": "end", "iter": 1, "status": "success", "iterations": 1})- tw.close()-- entries = TraceWriter.read(Path(tmp))- assert len(entries) > 0- for e in entries:- assert "iter" in e, f"{e['type']} missing iter"- keys = list(e.keys())- assert keys[0] == "type", f"{e['type']}: type not first: {keys}"- assert keys[1] == "iter", f"{e['type']}: iter not second: keys={keys}"++ + "\n",++ encoding="utf-8",++ )++++ [entry] = TraceWriter.read(trace_dir, resolve_offloads=True)++++ assert "result" not in entry++++++def test_text_field_offload_round_trips_selected_fields(++ monkeypatch: pytest.MonkeyPatch,++ tmp_path: Path,++) -> None:++ """Long prompt/answer fields can be offloaded without forcing all blobs open."""++ monkeypatch.setattr(trace_mod, "TRACE_TEXT_OFFLOAD_THRESHOLD", 8)++ trace = TraceWriter(tmp_path)++ trace.write_text_entry(++ {"type": "answer", "iter": 1},++ field="content",++ value="long final answer",++ offload_kind="answer",++ )++ trace.close()++++ unresolved = TraceWriter.read(tmp_path)++ assert "content" not in unresolved[0]++ assert unresolved[0]["content_preview"] == "long final answer"[: trace_mod.OFFLOAD_PREVIEW_CHARS]++++ still_unresolved = TraceWriter.read(++ tmp_path,++ resolve_offloads=True,++ resolve_fields={"result"},++ )++ assert "content" not in still_unresolved[0]++++ resolved = TraceWriter.read(++ tmp_path,++ resolve_offloads=True,++ resolve_fields={"content"},++ )++ assert resolved[0]["content"] == "long final answer"++++++def test_find_trace_dir_prefers_sessions_then_runs(tmp_path: Path) -> None:++ """Session traces are preferred while legacy run traces still work."""++ sessions = tmp_path / "sessions"++ runs = tmp_path / "runs"++ session_dir = sessions / "abc"++ run_dir = runs / "abc"++ session_dir.mkdir(parents=True)++ run_dir.mkdir(parents=True)++ (session_dir / "trace.jsonl").write_text('{"type":"session"}\n', encoding="utf-8")++ (run_dir / "trace.jsonl").write_text('{"type":"run"}\n', encoding="utf-8")++++ assert TraceWriter.find_trace_dir("abc", runs_dir=runs, sessions_dir=sessions) == session_dir++ assert TraceWriter.find_trace_dir("missing", runs_dir=runs, sessions_dir=sessions) is None