"""Keep a paid run's console output next to its result file (added 2026-09-23). The result JSONs hold scores; the console holds the WHY — every rejected planner attempt with its validator error, retrieval distances, per-turn steps. Before this, that text lived only in whatever terminal or temp file launched the run, and was lost with it. `start_run_log` tees stdout + stderr into `/logs/_.log` for the rest of the process. Call it first in `main`, before anything logs: structlog's default logger binds the stream on first use. ANSI colour codes are stripped from the file. """ from __future__ import annotations import re import sys from datetime import datetime from pathlib import Path from typing import TextIO _ANSI = re.compile(r"\x1b\[[0-9;]*m") class _Tee: def __init__(self, console: TextIO, file: TextIO) -> None: self._console, self._file = console, file def write(self, s: str) -> int: self._console.write(s) self._file.write(_ANSI.sub("", s)) return len(s) def flush(self) -> None: self._console.flush() self._file.flush() def isatty(self) -> bool: return self._console.isatty() def __getattr__(self, name: str): # encoding, fileno, … — whatever callers ask for return getattr(self._console, name) def run_stamp() -> str: return datetime.now().strftime("%Y-%m-%d_%H%M%S") def start_run_log(results_dir: Path, name: str, stamp: str) -> Path: """Tee this process's stdout/stderr into `results_dir/logs/{name}_{stamp}.log`.""" logs = results_dir / "logs" logs.mkdir(parents=True, exist_ok=True) path = logs / f"{name}_{stamp}.log" fh = path.open("w", encoding="utf-8") sys.stdout = _Tee(sys.stdout, fh) sys.stderr = _Tee(sys.stderr, fh) print(f"[run log] {path}") return path